default to a session cookie instead of setting an explicit timeout, weird timezone...
[freeside.git] / FS / FS / pay_batch / RBC.pm
1 package FS::pay_batch::RBC;
2
3 use strict;
4 use vars qw(@ISA %import_info %export_info $name);
5 use Date::Format 'time2str';
6 use Date::Parse;
7 use FS::Conf;
8 use Encode 'encode';
9 use feature 'state';
10
11 my $conf;
12 my ($client_num, $shortname, $longname, $trans_code, $testmode, $i, $declined, $totaloffset);
13
14 $name = 'RBC';
15 # Royal Bank of Canada ACH Direct Payments Service
16
17 # Meaning of initial characters in records:
18 # 0 - header row, skipped by begin_condition
19 # 1 - Debit Detail Record (only when subtype is 0)
20 # 2 - Credit Detail Record, we die with a parse error (shouldn't appear in freeside-generated batches)
21 # 3 - Account Trailer Record (appears after Returned items, we skip)
22 # 4 - Client Trailer Record, indicates end of batch in end_condition
23 #
24 # Subtypes (27th char) indicate different kinds of Debit/Credit records
25 # 0 - Credit/Debit Detail Record
26 # 3 - Error Message Record
27 # 4 - Foreign Currency Information Records
28 # We skip all subtypes except 0
29 #
30 # additional info available at https://www.rbcroyalbank.com/ach/cid-213166.html
31 %import_info = (
32   'filetype'    => 'fixed',
33   #this only really applies to Debit Detail, but we otherwise only need first char
34   'formatre'    => 
35   '^(.).{3}(.{10}).{5}(.{4}).{3}(.).{11}(.{19}).{6}(.{30})(.{2})(.{2})(.{4}).{9}(.{9})(.{18}).{6}(.{14}).{23}(.).{9}\r?$',
36   'fields' => [ qw(
37     recordtype
38     clientnum
39     batchnum
40     subtype
41     paybatchnum
42     custname
43     paydate_month
44     paydate_day
45     paydate_year
46     bank
47     payinfo
48     paid
49     status
50     ) ],
51   'hook' => sub {
52     # pull client_num from config and check it against what's in the batch
53     state $clientnum ||= do {
54       my $conf = FS::Conf->new;
55       my @config = $conf->config("batchconfig-RBC");
56       $config[0];
57     };
58
59     my $hash = shift;
60     $hash->{'paid'} = sprintf("%.2f", $hash->{'paid'} / 100 );
61     my $paydate = $hash->{'paydate_year'} . $hash->{'paydate_month'} . $hash->{'paydate_day'};
62     $hash->{'_date'} = str2time($paydate, 'local');
63     $hash->{'payinfo'} =~ s/^(\S+).*/$1/; # these often have trailing spaces
64     $hash->{'payinfo'} = $hash->{'payinfo'} . '@' . $hash->{'bank'};
65
66     if ( $clientnum and $hash->{clientnum} ne $clientnum ) {
67       die "RBC client number in batch (".$hash->{clientnum}.") does not ".
68         "match configuration.\n";
69     }
70     '';
71   },
72   'approved'    => sub { 
73       my $hash = shift;
74       ($hash->{'status'} eq ' ') || ($hash->{'status'} eq 'W');
75   },
76   'declined'    => sub {
77       my $hash = shift;
78       my $status = $hash->{'status'};
79       my $message = '';
80       if ($status eq 'E') {
81         $message = 'Reversed payment';
82       } elsif ($status eq 'R') {
83         $message = 'Rejected payment';
84       } elsif ($status eq 'U') {
85         $message = 'Returned payment';
86       } elsif ($status eq 'T') {
87         $message = 'Error';
88       } else {
89         return 0;
90       }
91       $hash->{'error_message'} = $message;
92       $declined->{$hash->{'paybatchnum'}} = 1;
93       return 1;
94   },
95   'begin_condition' => sub {
96       my $hash = shift;
97       # Detail Record
98       if ($hash->{recordtype} eq '1' || $hash->{recordtype} eq '2') {
99         $declined = {};
100         $totaloffset = 0;
101         return 1;
102       } else {
103         return 0;
104       }
105   },
106   'end_hook'    => sub {
107       my( $hash, $total, $line ) = @_;
108       $total += $totaloffset;
109       $total = sprintf("%.2f", $total);
110       # We assume here that this is an 'All Records' or 'Input Records' report.
111       my $batch_total = sprintf("%.2f", substr($line, 59, 18) / 100);
112       return "Our total $total does not match bank total $batch_total!"
113         if $total != $batch_total;
114       return '';
115   },
116   'end_condition' => sub {
117       my $hash = shift;
118       return ($hash->{recordtype} eq '4');  # Client Trailer Record
119   },
120   'skip_condition' => sub {
121       my $hash = shift;
122       #we already declined it this run, no takebacks
123       if ($declined->{$hash->{'paybatchnum'}}) {
124         #file counts this as part of total, but we skip
125         $totaloffset += sprintf("%.2f", $hash->{'paid'} / 100 )
126           if $hash->{'status'} eq ' '; #false laziness with 'approved' above
127         return 1;
128       }
129       return 
130         ($hash->{'recordtype'} eq '3') || #Account Trailer Record, concludes returned items
131         ($hash->{'subtype'} ne '0'); #error messages, etc, too late to apply to previous entry
132   },
133 );
134
135 %export_info = (
136   init => sub {
137     $conf = shift;
138     ($client_num,
139      $shortname,
140      $longname,
141      $trans_code, 
142      $testmode
143      ) = $conf->config("batchconfig-RBC");
144     $testmode = '' unless $testmode eq 'TEST';
145     $i = 1;
146   },
147   header => sub { 
148     my $pay_batch = shift;
149     my $mode = $testmode ? 'TEST' : 'PROD';
150     my $filenum = $testmode ? 'TEST' : sprintf("%04u", $pay_batch->batchnum);
151     my $qualifier = $pay_batch->type eq 'CREDIT' ? 'D' : 'A';
152     '$$AAP'.$qualifier.'STD0152['.$mode.'[NL$$'."\n".
153     '000001'.
154     'A'.
155     'HDR'.
156     sprintf("%10s", $client_num).
157     sprintf("%-30s", $longname).
158     $filenum.
159     time2str("%Y%j", $pay_batch->download).
160     'CAD'.
161     '1'.
162     ' ' x 87  # filler/reserved fields
163     ;
164   },
165   row => sub {
166     my ($cust_pay_batch, $pay_batch) = @_;
167     my ($account, $aba) = split('@', $cust_pay_batch->payinfo);
168     my($bankno, $branch);
169     if ( $aba =~ /^0(\d{3})(\d{5})$/ ) { # standard format for Canadian bank ID
170       ($bankno, $branch) = ( $1, $2 );
171     } elsif ( $aba =~ /^(\d{5})\.(\d{3})$/ ) { #how we store branches
172       ($branch, $bankno) = ( $1, $2 );
173     } else {
174       die "invalid branch/routing number '$aba'\n";
175     }
176
177     ## set custname to business name if business checking or savings account is used otherwise leave as first and last name.
178     my $custname = $cust_pay_batch->cust_main->batch_payment_payname($cust_pay_batch);
179
180     $i++;
181
182     ## set to D for debit by default, then override to what cust_pay_batch has as payments may not have paycode.
183     my $debitorcredit = 'D';
184     $debitorcredit = $cust_pay_batch->paycode unless !$cust_pay_batch->paycode;
185
186     sprintf("%06u", $i).
187     $debitorcredit.
188     sprintf("%3s",$trans_code).
189     sprintf("%10s",$client_num).
190     ' '.
191     sprintf("%-19s", $cust_pay_batch->paybatchnum).
192     '00'.
193     sprintf("%04s", $bankno).
194     sprintf("%05s", $branch).
195     sprintf("%-18s", $account).
196     ' '.
197     sprintf("%010.0f",$cust_pay_batch->amount*100).
198     '      '.
199     time2str("%Y%j", time + 86400).
200     sprintf("%-30.30s", encode('utf8', $custname)).
201     'E'. # English
202     ' '.
203     sprintf("%-15s", $shortname).
204     'CAD'.
205     ' '.
206     'CAN'.
207     '    '.
208     'N' # no customer optional information follows
209     ;
210 # Note: IAT Address Information and Remittance records are not 
211 # supported. This means you probably can't process payments 
212 # destined to U.S. bank accounts.  If you need this feature, contact 
213 # Freeside Internet Services.
214   },
215   footer => sub {
216     my ($pay_batch, $batchcount, $batchtotal) = @_;
217
218     my $batch_info = '0' x 20 . sprintf("%06u", $batchcount) . sprintf("%014.0f", $batchtotal*100);
219     $batch_info = sprintf("%06u", $batchcount) . sprintf("%014.0f", $batchtotal*100) . '0' x 20 if ($pay_batch->type eq 'CREDIT');
220
221     sprintf("%06u", $i + 1).
222     'Z'.
223     'TRL'.
224     sprintf("%10s", $client_num).
225     $batch_info.
226     '00' .
227     '000000' . # total number of customer information records
228     ' ' x 84
229     ;
230   },
231 );
232
233 ## this format can handle credit transactions
234 sub can_handle_credits {
235   1;
236 }
237
238 1;
239