RT# 82137 - default payment amount now has processing fee in total if processing...
[freeside.git] / bin / cust_bill-credit
1 #!/usr/bin/perl -w
2
3 use strict;
4 use vars qw( $opt_d $opt_s $opt_p $opt_m $opt_c $opt_e $opt_r );
5 use Getopt::Std;
6 use Date::Parse qw(str2time);
7 use FS::UID qw( dbh adminsuidsetup );
8 use FS::Record qw( qsearch qsearchs );
9 use FS::cust_main_county;
10 use FS::cust_bill;
11 use FS::msg_template;
12 use FS::cust_credit;
13 use FS::cust_credit_bill;
14
15 getopts('d:s:pm:c:er');
16
17 my $user = shift or &usage;
18 adminsuidsetup $user;
19
20 #i should be an option
21 my $taxname = 'HST, ON';
22 my $rate = '13';
23                                                                                 
24 my $oldAutoCommit = $FS::UID::AutoCommit;
25 local $FS::UID::AutoCommit = 0;
26 my $dbh = dbh;
27
28 ###
29 # find tax classes with double taxes
30 ##
31
32 #my $sql = "select distinct taxclass from cust_main_county where taxname = '$taxname';";
33 #my $sth = dbh->prepare($sql) or die dbh->errstr;
34 #$sth->execute or die $sth->errstr;
35 #my @taxclasses = map $_->[0], @{ $sth->fetchall_arrayref() };
36 #
37 #my %taxclass = map {
38 #                my $taxclass = $_;
39 #                my @cust_main_county = qsearch('cust_main_county', {
40 #                                         'taxclass' => $taxclass,
41 #                                         'taxname'  => $taxname,
42 #                                         'tax'      => { op=>'>', value=>'0' },
43 #                                       });
44 #
45 #                $taxclass => ( scalar(@cust_main_county) > 1 );
46 #
47 #              } @taxclasses;
48
49 my %taxclass = map { $_ => 1 } (
50   'InternetService',
51   'ComputerSetup-Remote',
52   'Config File- Static IPs',
53   'GST',
54   'GST + PST',
55   'GST ONLY',
56   'HST ONLY',
57   'HardwareRental',
58   'HardwareSale',
59   'HardwareSale_WEx',
60   'InternetService_WEx',
61   'LondDistanceFixedRate',
62   'LondDistanceVariableRate',
63   'PST',
64   'SARA-ONLY-GSTPayable',
65   'SetupInternet',
66   'SetupVoice',
67   'Shipping',
68   'SoftwareLicenseToUse',
69   'TDMPRI',
70   'TDMPRI_WEx',
71   'WarrantyCoverageHardware',
72   'WarrantyCoverageSoftware',
73   'WebHosting',
74   'federal and qst',
75   'telephoneNumber',
76   'LongDistanceFixedRate_WEx',
77   'LongDistanceVariableRate_WEx',
78 );
79
80 ###
81 # find invoices
82 ###
83
84 #my $extra_sql = $opt_s ? " AND cust_main.state = '$opt_s' " : '';
85
86 my $start_date = $opt_d ? str2time($opt_d) : 0;
87 my $end_date = 1375471643;
88
89 my @cust_bill = qsearch({
90   'select'    => 'cust_bill.*',
91   'table'     => 'cust_bill',
92   'addl_from' => 'LEFT JOIN cust_main USING ( custnum )',
93   'hashref'   => { '_date' => { op=>'>', value=>$start_date } },
94   'extra_sql' => " AND _date < $end_date ",
95 #  'extra_sql' => $extra_sql,
96 });
97
98 my( @billpkgnums, @setuprecurs, @amounts );
99
100 foreach my $cust_bill ( @cust_bill ) {
101
102   my $tax = $cust_bill->tax;
103
104   my $cust_main = $cust_bill->cust_main;
105
106   next if $cust_bill->charged == 0
107        or $tax == 0
108        or $cust_main->tax eq 'Y';
109
110   my $credit = 0;
111
112   @billpkgnums = ();
113   @setuprecurs = ();
114   @amounts = ();
115
116   foreach my $cust_bill_pkg ( $cust_bill->cust_bill_pkg ) {
117     my $cust_pkg = $cust_bill_pkg->cust_pkg or next;
118
119     my $loc = $cust_pkg->cust_location_or_main;
120     next if $opt_s && $loc->state ne $opt_s;
121
122     my $part_pkg = $cust_pkg->part_pkg;
123     next unless $taxclass{ $part_pkg->taxclass };
124
125     #my $amount = $cust_bill_pkg->setup + $cust_bill_pkg->recur;
126     #$credit += $rate * $amount / 100;
127
128     if ( $cust_bill_pkg->setup ) {
129       my $scredit = sprintf('%.2f', ($rate * $cust_bill_pkg->setup / 100) + 0.00000001);
130       $credit += $scredit;
131       push @setuprecurs, 'setup';
132       push @billpkgnums, $cust_bill_pkg->billpkgnum;
133       push @amounts, $scredit;
134     } 
135
136     if ( $cust_bill_pkg->recur ) {
137       my $rcredit = sprintf('%.2f', ($rate * $cust_bill_pkg->recur / 100) + 0.00000001);
138       $credit += $rcredit;
139       push @setuprecurs, 'recur';
140       push @billpkgnums, $cust_bill_pkg->billpkgnum;
141       push @amounts, $rcredit;
142     }
143
144   }
145
146   $credit = sprintf('%.2f', $credit + 0.00000001);
147
148   next if $credit == 0;
149
150   #$credit = sprintf('%.2f', $credit + 0.00000001);
151
152   warn "invoice ". $cust_bill->invnum. ": credit of $credit is more than orignally taxed ($tax)\n" if $credit > $tax;
153
154   warn "invoice ". $cust_bill->invnum. ": credit of $credit is more than 50% of originally taxed ($tax)\n" if $credit-0.01 > $tax/2;
155
156   #my $cr_percent = sprintf('%.1f', 100 * $credit / $tax);
157
158   if ( $opt_p ) {
159     #print $cust_bill->invnum. ','. $cust_bill->custnum. ",$tax,$credit,$cr_percent%\n";
160     print $cust_bill->invnum. ','. $cust_bill->custnum. ',"'.
161           $cust_bill->cust_main->name. '",'. "$tax,$credit\n";
162   }
163
164   if ( $opt_m && ! $opt_r ) {
165
166     my $msg_template = qsearchs('msg_template', { 'msgnum' => $opt_m } )
167         or die "Template $opt_m not found";
168     my $error = $msg_template->send(
169       'cust_main' => $cust_main,
170       'object'    => $cust_main,
171     );
172     if ( $error ) {
173       warn "error sending email for invnum ". $cust_bill->invnum. ','.
174            " custnum ". $cust_bill->custnum. ": $error\n";
175     }
176   }
177
178   if ( $opt_c ) {
179     my $cust_credit = new FS::cust_credit {
180       'custnum'   => $cust_main->custnum,
181       'amount'    => $credit,
182       'reasonnum' => $opt_c,
183     };
184     my $error = $cust_credit->insert;
185     if ( $error ) {
186       warn "error inserting credit: $error\n";
187     }
188     my $cust_credit_bill = new FS::cust_credit_bill {
189       'crednum' => $cust_credit->crednum,
190       'invnum'  => $cust_bill->invnum,
191       'amount'  => $credit,
192     };
193     my $aerror = $cust_credit_bill->insert;
194     if ( $aerror ) {
195       warn "error applying credit to invnum ". $cust_bill->invnum. ": $aerror\n";
196     }
197   }
198
199   if ( $opt_e && ! $opt_r ) {
200     eval { $cust_bill->email };
201     if ( $@ ) {
202       warn "error sending invnum ". $cust_bill->invnum. ','.
203          " custnum ". $cust_bill->custnum. ": $@\n";
204     }
205   }
206
207 }
208
209 if ( $opt_r ) {
210   $dbh->rollback or die $dbh->errstr; #if $oldAutoCommit;
211 } else {
212   $dbh->commit or die $dbh->errstr; #if $oldAutoCommit;
213 }
214
215 sub usage {                                                                     
216   die "usage:  cust_bill-credit [ -d date ] [ -s state ] [ -p ] [ -m templatenum ] [ -c reasonnum ] [ -e ] [ -r ] employee_username\n";
217 }                                                                               
218                                                                                 
219 =head1 NAME                                                                     
220                                                                                 
221 cust_bill-credit
222                                                                                 
223 =head1 SYNOPSIS                                                                 
224                                                                                 
225   cust_bill-credit [ -d date ] [ -s state ] [ -p ] [ -m templatenum ] [ -c reasonnum ] [ -e ] employee_username   
226                                                                                 
227 =head1 DESCRIPTION
228
229 Command-line tool to search for and credit invoices.
230
231 -d: Search for invoices starting from this date
232
233 -s: Search for invoices for packages within this state
234
235 -p: Print an informational line for each invoice with invnum, custnum, original tax amount, calculate credit, and credit percentage of original.
236
237 -m: Send an email to the customer with this message template.
238
239 -c: Credit the invoice for one-half of the taxation amount, using this reason.
240
241 -e: re-Email invoice
242
243 -r: dRy run
244
245 employee_username
246
247 =head1 BUGS
248
249 =head1 SEE ALSO
250
251 L<FS::part_pkg>
252
253 =cut
254
255 1;