RT#33582: RBC return batch processing failure [added comments]
[freeside.git] / FS / FS / pay_batch / RBC.pm
index 6ee5771..f3f8170 100644 (file)
@@ -11,10 +11,22 @@ my ($client_num, $shortname, $longname, $trans_code, $i);
 $name = 'RBC';
 # Royal Bank of Canada ACH Direct Payments Service
 
+# Meaning of initial characters in records:
+# 0 - header row, skipped by begin_condition
+# 1 - Debit Detail Record (only when subtype is 0)
+# 2 - Credit Detail Record, we die with a parse error (shouldn't appear in freeside-generated batches)
+# 3 - Account Trailer Record (appears after Returned items, we skip)
+# 4 - Client Trailer Record, indicates end of batch in end_condition
+#
+# Subtypes (27th char) indicate different kinds of Debit/Credit records
+# 0 - Credit/Debit Detail Record
+# 3 - Error Message Record
+# 4 - Foreign Currency Information Records
+# We skip all subtypes except 0
 %import_info = (
   'filetype'    => 'fixed',
   'formatre'    => 
-  '^(.).{18}(.{4}).{3}(.).{11}(.{19}).{6}(.{30}).{17}(.{9})(.{18}).{6}(.{14}).{23}(.).{9}\r?$',
+  '^([0134]).{18}(.{4}).{3}(.).{11}(.{19}).{6}(.{30}).{17}(.{9})(.{18}).{6}(.{14}).{23}(.).{9}\r?$',
   'fields' => [ qw(
     recordtype
     batchnum
@@ -61,7 +73,8 @@ $name = 'RBC';
   },
   'skip_condition' => sub {
       my $hash = shift;
-      $hash->{'subtype'} ne '0';
+      $hash->{'recordtype'} eq '3' ||
+        $hash->{'subtype'} ne '0';
   },
 );
 
@@ -93,6 +106,15 @@ $name = 'RBC';
   row => sub {
     my ($cust_pay_batch, $pay_batch) = @_;
     my ($account, $aba) = split('@', $cust_pay_batch->payinfo);
+    my($bankno, $branch);
+    if ( $aba =~ /^0(\d{3})(\d{5})$/ ) { # standard format for Canadian bank ID
+      ($bankno, $branch) = ( $1, $2 );
+    } elsif ( $aba =~ /^(\d{5})\.(\d{3})$/ ) { #how we store branches
+      ($branch, $bankno) = ( $1, $2 );
+    } else {
+      die "invalid branch/routing number '$aba'\n";
+    }
+
     $i++;
     sprintf("%06u", $i).
     'D'.
@@ -101,7 +123,8 @@ $name = 'RBC';
     ' '.
     sprintf("%-19s", $cust_pay_batch->paybatchnum).
     '00'.
-    sprintf("%09u", $aba).
+    sprintf("%04s", $bankno).
+    sprintf("%05s", $branch).
     sprintf("%-18s", $account).
     ' '.
     sprintf("%010.0f",$cust_pay_batch->amount*100).
@@ -129,7 +152,7 @@ $name = 'RBC';
     'Z'.
     'TRL'.
     sprintf("%10s", $client_num).
-    ' ' x 20 .
+    '0' x 20 .
     sprintf("%06u", $batchcount).
     sprintf("%014.0f", $batchtotal*100).
     '00' .