4.x+ self-service API: list and remove cards on file, RT#38919
[freeside.git] / bin / reset-cust_credit-otaker
1 #!/usr/bin/perl -w
2
3 use strict;
4 use vars qw($opt_d);
5 use Getopt::Std;
6 use FS::UID qw(adminsuidsetup);
7 use FS::Record qw(qsearch qsearchs);
8 use FS::cust_credit;
9 use FS::h_cust_credit;
10
11 getopts('d:');
12
13 my $user = shift or die &usage;
14 adminsuidsetup $user;
15
16 die &usage
17   unless ($opt_d);
18
19 $FS::Record::nowarn_identical = 1;
20
21 if ( $opt_d ) {
22   $opt_d =~ /^(\d+)$/ or die "invalid date";
23 } else {
24   die "no date specified\n";
25 }
26
27 my @cust_credit = qsearch('cust_credit', { otaker => $user } );
28 die "no credits found\n" unless @cust_credit;
29
30 my $cust_credit = new FS::cust_credit;
31 my @fields = grep { $_ !~ /^otaker|reason|reasonnum$/ } $cust_credit->fields;
32
33 foreach my $cust_credit ( @cust_credit ) {
34   my %hash = $cust_credit->hash;
35   foreach (qw(otaker reason reasonnum)) {
36     delete $hash{$_};
37   }
38   $hash{'history_action'} = 'replace_old';
39   my $h_cust_credit =
40     qsearchs({ 'table'     => 'h_cust_credit',
41                'hashref'   => \%hash,
42                'select'    => '*',
43                'extra_sql' =>  " AND history_date <= $opt_d",
44                'order_by'  =>  'ORDER BY history_date DESC LIMIT 1',
45             });
46   if ($h_cust_credit) {
47     $cust_credit->otaker($h_cust_credit->otaker);
48     my $reason = $h_cust_credit->getfield('reason');
49     if ($reason =~ /^\s*$/) {
50       $reason = '(none)';
51     }
52     $cust_credit->otaker($h_cust_credit->otaker);
53     $cust_credit->reason($reason);
54     my $error = $cust_credit->replace
55       if $cust_credit->modified;     
56     die "error replacing cust_credit: $error\n"
57       if $error;
58   }else{
59     warn "Skipping credit.crednum ". $cust_credit->crednum;
60   }
61 }
62
63 sub usage {
64   die "Usage:\n\n  reset-cust_credit-otaker -d epoch_date user\n";
65 }
66
67 =head1 NAME
68
69 reset-cust_credit-otaker - Command line tool to reset the otaker column for cust_credits to a previous value 
70
71 =head1 SYNOPSIS
72
73   reset-cust_credit-otaker -d epoch_date user
74
75 =head1 DESCRIPTION
76
77   Sets the otaker column of the cust_credit records specified by user and
78   datespec to the value just prior to datespec.  
79
80   The reasonnum of the cust_credit record is also set to reason record
81   which matches the reason specified in the history.
82
83 =head1 SEE ALSO
84
85 L<FS::cust_credit>, L<FS::h_cust_credit>;
86
87 =cut
88