Created
September 2, 2019 10:56
-
-
Save ciaranmcnulty/6c531175028a712761809521c4fe4691 to your computer and use it in GitHub Desktop.
Script to fix Capital On Tap statements for importing cleanly into Crunch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env php | |
<?php | |
$usage = <<<USAGE | |
Usage: | |
./cot-statement-fixer starting-balance filename.csv | |
USAGE; | |
if (count($argv)!==3){ | |
die($usage); | |
} | |
$balance = $argv[1]; | |
$filename = $argv[2]; | |
if (!is_numeric($balance)) { | |
echo "Balance must be numeric\n\n"; | |
die($usage); | |
} | |
try | |
{ | |
$file = new SplFileObject($filename); | |
} | |
catch (RuntimeException $e) | |
{ | |
echo "File not found\n\n"; | |
} | |
$headers = [ | |
0 => 'Date', | |
1 => 'Description', | |
2 => 'Amount', | |
3 => 'Merchant Name', | |
4 => 'Card Ending', | |
]; | |
$keys = array_flip($headers); | |
if ($file->fgetcsv() != $headers) { | |
echo "Badly formed CSV\n\n"; | |
die($usage); | |
} | |
$outfile = new SplFileObject('php://stdout', 'w'); | |
$outfile->fputcsv([ | |
'Date', | |
'Description', | |
'Amount', | |
'Balance' | |
]); | |
while (!$file->eof()) { | |
$data[] = $file->fgetcsv(); | |
} | |
$data = array_reverse($data); // date order | |
foreach ($data as $datum) { | |
if('0'===$datum[$keys['Amount']]) { // skip empty 'finance charge' | |
continue; | |
} | |
$amount = -$datum[$keys['Amount']]; | |
$balance += $amount; | |
$outfile->fputcsv([ | |
$datum[$keys['Date']], | |
$datum[$keys['Description']] ?? $datum[$keys['Merchant Name']], | |
round($amount, 2), | |
round($balance, 2) | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment