RT#18834: Cacti integration [added graph generation]
[freeside.git] / bin / import-prepaid-cards
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use Text::CSV;
6 use FS::UID qw(adminsuidsetup);
7 use FS::Record qw(qsearch qsearchs dbh);
8 use FS::prepay_credit;
9 use Data::Dumper;
10 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
11
12 print "started time=".time."\n";
13
14 # INSTRUCTIONS: save the spreadsheet as CSV (in ASCII), set the
15 # below variables, and run this script, passing in a fs username as an arg.
16
17 ### SET THESE!
18 my $file = '/home/levinse/prepaidcards.csv';
19 my $amount = '11.95';
20 my $dry = 0;
21 ###
22
23 my $user = shift;
24 adminsuidsetup $user;
25
26 local $SIG{HUP} = 'IGNORE';
27 local $SIG{INT} = 'IGNORE';
28 local $SIG{QUIT} = 'IGNORE';
29 local $SIG{TERM} = 'IGNORE';
30 local $SIG{TSTP} = 'IGNORE';
31 local $SIG{PIPE} = 'IGNORE';
32
33 my $oldAutoCommit = $FS::UID::AutoCommit;
34 local $FS::UID::AutoCommit = 0;
35 my $dbh = dbh;
36
37 my $skipto = 0; 
38 my $limit = 0;
39 my $linenum = 1;
40 my $debug = 0;
41
42 sub trim {
43     my $str = shift;
44     $str =~ s/^\s+|\s+$//g;
45     $str;
46 }
47
48 sub suffer {
49     my $linenum = shift;
50     my @columns = @_;
51
52     my $cardnum = trim($columns[0]);
53
54     my $prepay_credit = new FS::prepay_credit { 'identifier' => $cardnum,
55                                        'amount'     => $amount,
56                                     };
57     my $error = $prepay_credit->insert;
58     fatal("error inserting card: $error") if $error;
59
60     warn "Pass $linenum\n" if $debug;
61     my $time = time;
62     print "Done $linenum time=$time\n" if ($linenum % 1000 == 0);
63 }
64
65 sub fatal {
66     my $msg = shift;
67     $dbh->rollback if $oldAutoCommit;
68     die $msg;
69 }
70
71 my $csv = new Text::CSV;
72 open (CSV, "<", $file) or die $!;
73 print "Starting main loop time=".time."\n";
74 while (<CSV>) {
75     if ( $linenum == 1 ) { # skip header
76         $linenum++;
77         next;
78     }
79
80     if( $skipto > $linenum ) { # debug stuff
81         $linenum++;
82         next;
83     }
84
85     last if $limit > 0 && $limit <= $linenum;
86
87     # kept getting these errors for many lines:
88     # "EIQ - Binary character inside quoted field, binary off"
89     $_ =~ s/[^[:ascii:]]//g;
90
91     if ($csv->parse($_)) {
92         my @columns = $csv->fields();
93         suffer($linenum,@columns);
94     } else {
95         my $err = $csv->error_diag . "(" . $csv->error_input . ")";
96         print "WARNING: failed to parse line $linenum: " . $csv->error_diag
97             . " (" . $csv->error_input . ")\n";
98     }
99     $linenum++;
100 }
101 close CSV;
102
103 fatal("COMMIT ABORTED DUE TO DRY RUN BEING ON") if $dry;
104 $dbh->commit or die $dbh->errstr if $oldAutoCommit;