Invoice Line Sanity Check
Checks invoice lines for negative values, quantity errors, subtotal drift, and duplicate SKU rows.
Purpose
Checks invoice lines for negative values, quantity errors, subtotal drift, and duplicate SKU rows.
Snippet details
ContextEcommerceLevelAdvancedCopy-and-paste statusMarked safe after review.Categories
- Security
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Invoice Line Sanity Check.
*
* Purpose:
* Checks invoice lines for negative values, quantity errors, subtotal drift, and duplicate SKU rows.
*
* @param array $invoice_lines Invoice line rows.
* @return array Invoice sanity issues.
*/
function ogSnippetInvoiceLineSanityCheck(array $invoice_lines): array {
$issues = array();
$seen_skus = array();
foreach ($invoice_lines as $index => $line) {
$sku = (string) $line['sku'];
$quantity = (int) $line['quantity'];
$unit = (int) $line['unit_cents'];
$line_total = (int) $line['line_total_cents'];
if ($quantity < 1 || $unit < 0 || $line_total < 0) {
$issues[] = 'Invalid value at row '.$index;
}
if ($quantity * $unit !== $line_total) {
$issues[] = 'Subtotal drift at row '.$index;
}
if (isset($seen_skus[$sku])) {
$issues[] = 'Duplicate SKU: '.$sku;
}
$seen_skus[$sku] = true;
}
return $issues;
}
$invoice_issues = ogSnippetInvoiceLineSanityCheck(array(array('sku' => 'PLASMA-RIFLE', 'quantity' => 2, 'unit_cents' => 3000, 'line_total_cents' => 5900)));
echo count($invoice_issues);