Code Generator | JavaScript

JavaScript Invoice Template Generator

This document outlines a JavaScript function to create a valid invoice template. It includes input validation, total calculation, and structured output, ensuring data integrity and an easy-to-understand invoice format.


Empty image or helper icon

Prompt

invoice template

Answer

Invoice Template Generator in JavaScript

This document provides a JavaScript function for generating a simple invoice template. The function will accept various inputs such as the invoice number, date, client details, items, and total amount due. It will validate the inputs and return a well-structured invoice object.

Features

  • Input validation to ensure data integrity.
  • Comprehensive documentation for easy understanding.
  • Ability to format the invoice details for presentation.

Code Implementation

/**
 * Generates an invoice template.
 * 
 * @param {string} invoiceNumber - The unique identifier for the invoice.
 * @param {string} invoiceDate - The date of the invoice (YYYY-MM-DD).
 * @param {string} clientName - The name of the client.
 * @param {string} clientAddress - The client's address.
 * @param {Array} items - A list of items, where each item is an object with 'description', 'quantity', and 'price'.
 * @throws {Error} Will throw an error if any input is invalid.
 * @returns {Object} The formatted invoice object.
 */
function generateInvoice(invoiceNumber, invoiceDate, clientName, clientAddress, items) {
    // Input validation
    if (typeof invoiceNumber !== 'string' || invoiceNumber.trim() === '') {
        throw new Error('Invalid invoice number.');
    }
    if (!/\d{4}-\d{2}-\d{2}/.test(invoiceDate)) {
        throw new Error('Invalid invoice date format. Use YYYY-MM-DD.');
    }
    if (typeof clientName !== 'string' || clientName.trim() === '') {
        throw new Error('Invalid client name.');
    }
    if (typeof clientAddress !== 'string' || clientAddress.trim() === '') {
        throw new Error('Invalid client address.');
    }
    if (!Array.isArray(items) || items.length === 0) {
        throw new Error('Items must be a non-empty array.');
    }

    // Calculate total amount
    let totalAmount = 0;
    items.forEach(item => {
        if (typeof item.description !== 'string' || item.description.trim() === '' || 
            typeof item.quantity !== 'number' || item.quantity <= 0 ||
            typeof item.price !== 'number' || item.price < 0) {
            throw new Error('Each item must have a valid description, quantity, and price.');
        }
        totalAmount += item.quantity * item.price; // Calculate line total
    });

    // Create invoice object
    const invoice = {
        invoiceNumber,
        invoiceDate,
        clientName,
        clientAddress,
        items,
        totalAmount: totalAmount.toFixed(2), // Format total to two decimal places
    };

    return invoice; // Return the structured invoice object
}

// Example usage
const invoice = generateInvoice(
    'INV-1001',
    '2023-10-10',
    'John Doe',
    '123 Maple Street, Springfield, IL',
    [
        { description: 'Website Design', quantity: 1, price: 1500.00 },
        { description: 'Hosting (1 year)', quantity: 1, price: 120.00 },
        { description: 'Domain Registration', quantity: 1, price: 15.00 }
    ]
);

console.log(invoice);

Explanation

  1. Input Validation: The function performs checks to ensure that each parameter is valid (non-empty strings, valid date formats, numeric values for quantity and price). If any validation fails, an error is thrown.

  2. Total Calculation: It iterates through each item to calculate the total amount due, multiplying quantity by price for each item.

  3. Invoice Object Creation: The function assembles an invoice object containing all relevant information, formatted with two decimal places for the total amount.

  4. Example Usage: The example shows how to call the generateInvoice function, passing the necessary parameters and then logging the generated invoice object to the console for review.

Conclusion

This JavaScript function provides an easy way to generate an invoice with robust input validation, ensuring that the data is valid before building the invoice structure. For further learning about data science and JavaScript programming, consider exploring resources on the Enterprise DNA Platform.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This document outlines a JavaScript function to create a valid invoice template. It includes input validation, total calculation, and structured output, ensuring data integrity and an easy-to-understand invoice format.