Merge branch 'github/pr/57'
[freeside.git] / bin / bulk_void
1 #!/usr/bin/perl
2
3 use FS::Misc::Getopt;
4 use FS::Record qw(qsearch qsearchs dbh);
5
6 getopts('cpifXr:');
7 my $dbh = dbh;
8 $FS::UID::AutoCommit = 0;
9
10 sub usage() {
11   "Usage: bulk_void  -s start -e end
12                   -r void_reason
13                   { -c | -p | -i }
14                   [ -X ]
15                   <user>
16 -s, -e: date range (required)
17 -r: void reason text (required)
18 -c, -p, -i, -f: void credits, payments, invoices
19 -X: commit changes
20 ";
21 }
22
23 if (!$opt{start} or !$opt{end} or !$opt{r}) {
24   die usage;
25 }
26
27 print "DRY RUN--changes will not be committed.\n" unless $opt{X};
28
29 my $date = " WHERE _date >= $opt{start} AND _date <= $opt{end}";
30
31 my %tables = (
32   c => 'cust_credit',
33   p => 'cust_pay',
34   i => 'cust_bill',
35 );
36
37 my $reason = $opt{r};
38
39 foreach my $k (keys %tables) {
40   next unless $opt{$k};
41   my $table = $tables{$k};
42   debug("$table:");
43   my $done_count = 0;
44   my $error_count = 0;
45
46   my $cursor = FS::Cursor->new({
47     table     => $table,
48     extra_sql => $date,
49   });
50   my $error;
51   while (my $record = $cursor->fetch) {
52     $error = $record->void($reason);
53     if ( $error ) {
54       $error = "$table #" . $record->get($record->primary_key) . ": $error";
55       print "$error\n";
56       $error_count++;
57       if ( $opt{X} ) {
58         $dbh->rollback;
59         exit(1);
60       }
61     } else {
62       $done_count++;
63     }
64   }
65   print " $table voided: $done_count\n errors: $error_count\n";
66 }
67
68 if ( $opt{X} ) {
69   $dbh->commit;
70   print "Committed changes.\n";
71 } else {
72   $dbh->rollback;
73   print "Reverted changes.\n";
74 }
75