first stab at BoM download
[freeside.git] / FS / FS / cust_pay_batch.pm
1 package FS::cust_pay_batch;
2
3 use strict;
4 use vars qw( @ISA );
5 use FS::Record qw(dbh qsearchs);
6 use Business::CreditCard;
7
8 @ISA = qw( FS::Record );
9
10 =head1 NAME
11
12 FS::cust_pay_batch - Object methods for batch cards
13
14 =head1 SYNOPSIS
15
16   use FS::cust_pay_batch;
17
18   $record = new FS::cust_pay_batch \%hash;
19   $record = new FS::cust_pay_batch { 'column' => 'value' };
20
21   $error = $record->insert;
22
23   $error = $new_record->replace($old_record);
24
25   $error = $record->delete;
26
27   $error = $record->check;
28
29 =head1 DESCRIPTION
30
31 An FS::cust_pay_batch object represents a credit card transaction ready to be
32 batched (sent to a processor).  FS::cust_pay_batch inherits from FS::Record.  
33 Typically called by the collect method of an FS::cust_main object.  The
34 following fields are currently supported:
35
36 =over 4
37
38 =item paybatchnum - primary key (automatically assigned)
39
40 =item payinfo
41
42 =item exp - card expiration 
43
44 =item amount 
45
46 =item invnum - invoice
47
48 =item custnum - customer 
49
50 =item payname - name on card 
51
52 =item first - name 
53
54 =item last - name 
55
56 =item address1 
57
58 =item address2 
59
60 =item city 
61
62 =item state 
63
64 =item zip 
65
66 =item country 
67
68 =back
69
70 =head1 METHODS
71
72 =over 4
73
74 =item new HASHREF
75
76 Creates a new record.  To add the record to the database, see L<"insert">.
77
78 Note that this stores the hash reference, not a distinct copy of the hash it
79 points to.  You can ask the object for a copy with the I<hash> method.
80
81 =cut
82
83 sub table { 'cust_pay_batch'; }
84
85 =item insert
86
87 Adds this record to the database.  If there is an error, returns the error,
88 otherwise returns false.
89
90 =item delete
91
92 Delete this record from the database.  If there is an error, returns the error,
93 otherwise returns false.
94
95 =item replace OLD_RECORD
96
97 #inactive
98 #
99 #Replaces the OLD_RECORD with this one in the database.  If there is an error,
100 #returns the error, otherwise returns false.
101
102 =cut
103
104 sub replace {
105   return "Can't (yet?) replace batched transactions!";
106 }
107
108 =item check
109
110 Checks all fields to make sure this is a valid transaction.  If there is
111 an error, returns the error, otherwise returns false.  Called by the insert
112 and repalce methods.
113
114 =cut
115
116 sub check {
117   my $self = shift;
118
119   my $error = 
120       $self->ut_numbern('paybatchnum')
121     || $self->ut_numbern('trancode') #depriciated
122     || $self->ut_number('payinfo') 
123     || $self->ut_money('amount')
124     || $self->ut_number('invnum')
125     || $self->ut_number('custnum')
126     || $self->ut_text('address1')
127     || $self->ut_textn('address2')
128     || $self->ut_text('city')
129     || $self->ut_textn('state')
130   ;
131
132   return $error if $error;
133
134   $self->getfield('last') =~ /^([\w \,\.\-\']+)$/ or return "Illegal last name";
135   $self->setfield('last',$1);
136
137   $self->first =~ /^([\w \,\.\-\']+)$/ or return "Illegal first name";
138   $self->first($1);
139
140   # FIXME
141   # there is no point in false laziness here
142   # we will effectively set "check_payinfo to 0"
143   # we can change that when we finish the refactor
144   
145   #my $cardnum = $self->cardnum;
146   #$cardnum =~ s/\D//g;
147   #$cardnum =~ /^(\d{13,16})$/
148   #  or return "Illegal credit card number";
149   #$cardnum = $1;
150   #$self->cardnum($cardnum);
151   #validate($cardnum) or return "Illegal credit card number";
152   #return "Unknown card type" if cardtype($cardnum) eq "Unknown";
153
154   if ( $self->exp eq '' ) {
155     return "Expiration date required"; #unless 
156     $self->exp('');
157   } else {
158     if ( $self->exp =~ /^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})$/ ) {
159       $self->exp("$1-$2-$3");
160     } elsif ( $self->exp =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
161       if ( length($2) == 4 ) {
162         $self->exp("$2-$1-01");
163       } elsif ( $2 > 98 ) { #should pry change to check for "this year"
164         $self->exp("19$2-$1-01");
165       } else {
166         $self->exp("20$2-$1-01");
167       }
168     } else {
169       return "Illegal expiration date";
170     }
171   }
172
173   if ( $self->payname eq '' ) {
174     $self->payname( $self->first. " ". $self->getfield('last') );
175   } else {
176     $self->payname =~ /^([\w \,\.\-\']+)$/
177       or return "Illegal billing name";
178     $self->payname($1);
179   }
180
181   #$self->zip =~ /^\s*(\w[\w\-\s]{3,8}\w)\s*$/
182   #  or return "Illegal zip: ". $self->zip;
183   #$self->zip($1);
184
185   $self->country =~ /^(\w\w)$/ or return "Illegal country: ". $self->country;
186   $self->country($1);
187
188   $error = $self->ut_zip('zip', $self->country);
189   return $error if $error;
190
191   #check invnum, custnum, ?
192
193   $self->SUPER::check;
194 }
195
196 =item cust_main
197
198 Returns the customer (see L<FS::cust_main>) for this batched credit card
199 payment.
200
201 =cut
202
203 sub cust_main {
204   my $self = shift;
205   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
206 }
207
208 =back
209
210 =head1 SUBROUTINES
211
212 =over 4
213
214 =item import_results
215
216 =cut
217
218 sub import_results {
219   use Time::Local;
220   use FS::cust_pay;
221   eval "use Text::CSV_XS;";
222   die $@ if $@;
223 #
224   my $param = shift;
225   my $fh = $param->{'filehandle'};
226   my $format = $param->{'format'};
227   my $paybatch = $param->{'paybatch'};
228
229   my @fields;
230   my $end_condition;
231   my $end_hook;
232   my $hook;
233   my $approved_condition;
234   my $declined_condition;
235
236   if ( $format eq 'csv-td_canada_trust-merchant_pc_batch' ) {
237
238     @fields = (
239       'paybatchnum', # Reference#:  Invoice number of the transaction
240       'paid',        # Amount:  Amount of the transaction.  Dollars and cents
241                      #          with no decimal entered.
242       '',            # Card Type:  0 - MCrd, 1 - Visa, 2 - AMEX, 3 - Discover,
243                      #             4 - Insignia, 5 - Diners/EnRoute, 6 - JCB
244       '_date',       # Transaction Date:  Date the Transaction was processed
245       'time',        # Transaction Time:  Time the transaction was processed
246       'payinfo',     # Card Number:  Card number for the transaction
247       '',            # Expiry Date:  Expiry date of the card
248       '',            # Auth#:  Authorization number entered for force post
249                      #         transaction
250       'type',        # Transaction Type:  0 - purchase, 40 - refund,
251                      #                    20 - force post
252       'result',      # Processing Result: 3 - Approval,
253                      #                    4 - Declined/Amount over limit,
254                      #                    5 - Invalid/Expired/stolen card,
255                      #                    6 - Comm Error
256       '',            # Terminal ID: Terminal ID used to process the transaction
257     );
258
259     $end_condition = sub {
260       my $hash = shift;
261       $hash->{'type'} eq '0BC';
262     };
263
264     $end_hook = sub {
265       my( $hash, $total) = @_;
266       $total = sprintf("%.2f", $total);
267       my $batch_total = sprintf("%.2f", $hash->{'paybatchnum'} / 100 );
268       return "Our total $total does not match bank total $batch_total!"
269         if $total != $batch_total;
270       '';
271     };
272
273     $hook = sub {
274       my $hash = shift;
275       $hash->{'paid'} = sprintf("%.2f", $hash->{'paid'} / 100 );
276       $hash->{'_date'} = timelocal( substr($hash->{'time'},  4, 2),
277                                     substr($hash->{'time'},  2, 2),
278                                     substr($hash->{'time'},  0, 2),
279                                     substr($hash->{'_date'}, 6, 2),
280                                     substr($hash->{'_date'}, 4, 2)-1,
281                                     substr($hash->{'_date'}, 0, 4)-1900, );
282     };
283
284     $approved_condition = sub {
285       my $hash = shift;
286       $hash->{'type'} eq '0' && $hash->{'result'} == 3;
287     };
288
289     $declined_condition = sub {
290       my $hash = shift;
291       $hash->{'type'} eq '0' && (    $hash->{'result'} == 4
292                                   || $hash->{'result'} == 5 );
293     };
294
295
296   } else {
297     return "Unknown format $format";
298   }
299
300   my $csv = new Text::CSV_XS;
301
302   local $SIG{HUP} = 'IGNORE';
303   local $SIG{INT} = 'IGNORE';
304   local $SIG{QUIT} = 'IGNORE';
305   local $SIG{TERM} = 'IGNORE';
306   local $SIG{TSTP} = 'IGNORE';
307   local $SIG{PIPE} = 'IGNORE';
308
309   my $oldAutoCommit = $FS::UID::AutoCommit;
310   local $FS::UID::AutoCommit = 0;
311   my $dbh = dbh;
312
313   my $pay_batch = qsearchs('pay_batch',{'batchnum'=> $paybatch});
314   unless ($pay_batch && $pay_batch->status eq 'I') {
315     $dbh->rollback if $oldAutoCommit;
316     return "batch $paybatch is not in transit";
317   };
318
319   my %batchhash = $pay_batch->hash;
320   $batchhash{'status'} = 'R';   # Resolved
321   my $newbatch = new FS::pay_batch ( \%batchhash );
322   my $error = $newbatch->replace($paybatch);
323   if ( $error ) {
324     $dbh->rollback if $oldAutoCommit;
325     return $error
326   }
327
328   my $total = 0;
329   my $line;
330   while ( defined($line=<$fh>) ) {
331
332     next if $line =~ /^\s*$/; #skip blank lines
333
334     $csv->parse($line) or do {
335       $dbh->rollback if $oldAutoCommit;
336       return "can't parse: ". $csv->error_input();
337     };
338
339     my @values = $csv->fields();
340     my %hash;
341     foreach my $field ( @fields ) {
342       my $value = shift @values;
343       next unless $field;
344       $hash{$field} = $value;
345     }
346
347     if ( &{$end_condition}(\%hash) ) {
348       my $error = &{$end_hook}(\%hash, $total);
349       if ( $error ) {
350         $dbh->rollback if $oldAutoCommit;
351         return $error;
352       }
353       last;
354     }
355
356     my $cust_pay_batch =
357       qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'} } );
358     unless ( $cust_pay_batch ) {
359       $dbh->rollback if $oldAutoCommit;
360       return "unknown paybatchnum $hash{'paybatchnum'}\n";
361     }
362     my $custnum = $cust_pay_batch->custnum,
363
364     my $error = $cust_pay_batch->delete;
365     if ( $error ) {
366       $dbh->rollback if $oldAutoCommit;
367       return "error removing paybatchnum $hash{'paybatchnum'}: $error\n";
368     }
369
370     &{$hook}(\%hash);
371
372     if ( &{$approved_condition}(\%hash) ) {
373
374       my $cust_pay = new FS::cust_pay ( {
375         'custnum'  => $custnum,
376         'payby'    => 'CARD',
377         'paybatch' => $paybatch,
378         map { $_ => $hash{$_} } (qw( paid _date payinfo )),
379       } );
380       $error = $cust_pay->insert;
381       if ( $error ) {
382         $dbh->rollback if $oldAutoCommit;
383         return "error adding payment paybatchnum $hash{'paybatchnum'}: $error\n";
384       }
385       $total += $hash{'paid'};
386   
387       $cust_pay->cust_main->apply_payments;
388
389     } elsif ( &{$declined_condition}(\%hash) ) {
390
391       #this should be configurable... if anybody else ever uses batches
392       $cust_pay_batch->cust_main->suspend;
393
394     }
395
396   }
397   
398   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
399   '';
400
401 }
402
403 =back
404
405 =head1 BUGS
406
407 There should probably be a configuration file with a list of allowed credit
408 card types.
409
410 =head1 SEE ALSO
411
412 L<FS::cust_main>, L<FS::Record>
413
414 =cut
415
416 1;
417