To start with, deleting invoices, not the best approach. It's better to cancel them outright. This way, for all legal purposes they're still there
That being said, here's a hook that'll run through these and cancel them on run. There's two spots you want to change, pretty well documented there. Save this as a php file in whmcs/includes/hooks
<?php
/*
Hook to automatically cancel invoices after XXX days on cron run
Provided courtesy of https://www.whmcs.guru/
*/
if (!defined("WHMCS"))
die("This file cannot be accessed directly");
use Illuminate\Database\Capsule\Manager as Capsule;
function guru_unpaid_addfunds($vars)
{
//BEGIN CHANGE SECTION
//change the period here
$olderthan = "30";
//whmcs API user, change it
$apiuser="CHANGEME";
//END CHANGE SECTION
logActivity('Starting daily funds invoice cleanup ', 0);
$invoices = Capsule::table('tblinvoices')->select('id', 'date')->WHERE('status', 'Unpaid')->get();
foreach ($invoices as $data)
{
$myid = $data->id;
$mydate = $data->date;
$createdon = strtotime($mydate);
$calctime = time() - ($olderthan * 24 * 60 * 60);
if ($createdon > $calctime)
{
//skip it, we shouldn't be here yet
continue;
}
//do something with myid and unique column
$numrows = Capsule::table('tblinvoiceitems') ->select('id')->WHERE('invoiceid', $myid) ->WHERE('type', 'AddFunds')->count();
//invoice matches , cancel it
if ($numrows > 0)
{
$notedate = date("F j, Y");
//this invoice matches, so let's delete it
$command = 'UpdateInvoice';
$values['invoiceid'] = $myid;
$values['status'] = 'Cancelled';
$values['notes'] = "Automatically cancelled via daily cron run on $notedate";
$results = localAPI($command, $values, $apiuser);
logActivity('Invoice ID $myid - Cancelled due to daily funds invoice cleanup', 0);
//print_r($results);
}
}
logActivity('Ending daily funds invoice cleanup ', 0);
}
add_hook("DailyCronJob",1,"guru_unpaid_addfunds");
?>
This will log the cancellation, both in admin logs, and in the invoice notes itself (will overwrite anything in the existing invoice notes), and trigger only on unpaid addfunds invoices