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