Skip to content

Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.

1.2 KB
Raw Blame
import type { InvoiceItemData } from "@/app/schema";

import { calculateItemTotals } from "./calculate-item-totals";

/**
 * Check if calculated item totals (discountAmount, netAmount, vatAmount, preTaxAmount)
 * differ from existing item's values.
 *
 * @param item InvoiceItemData to check for changes
 * @returns true if any total value differs, false otherwise
 */
export function hasItemTotalsChanged(item: InvoiceItemData): boolean {
  const calculated = calculateItemTotals(item);

  return (
    calculated?.discountAmount !== item.discountAmount ||
    calculated?.netAmount !== item.netAmount ||
    calculated?.vatAmount !== item.vatAmount ||
    calculated?.preTaxAmount !== item.preTaxAmount
  );
}

/**
 * Check if any item in array has changed totals (netAmount, vatAmount, preTaxAmount).
 *
 * If any item has changed totals, we need to recalculate the totals for all items.
 *
 * @param items Array of InvoiceItemData
 * @returns true if any item has changed totals, false otherwise
 */
export function hasAnyItemTotalsChanged(
  items: ReadonlyArray<InvoiceItemData>,
): boolean {
  return items.some((item) => {
    return hasItemTotalsChanged(item);
  });
}