+sub update_payby {
+ my $p = shift;
+
+ my($context, $session, $custnum) = _custoragent_session_custnum($p);
+ return { 'error' => $session } if $context eq 'error';
+
+ if ($p->{'payby'} eq 'CHEK') {
+ $p->{'payinfo1'} =~ /^([\dx]+)$/
+ or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
+ my $payinfo1 = $1;
+ $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
+ or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
+ my $payinfo2 = $1;
+ $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
+ }
+ elsif ($p->{'payby'} eq 'CARD') {
+ $p->{paydate} = $p->{year} . '-' . $p->{month} . '-01' unless $p->{paydate};
+ }
+
+ my $cust_payby = qsearchs('cust_payby', {
+ 'custnum' => $custnum,
+ 'custpaybynum' => $p->{'custpaybynum'},
+ })
+ or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
+
+ my $cust_main = qsearchs( 'cust_main', {custnum => $cust_payby->custnum} )
+ or return { 'error' => 'unknown custnum '.$cust_payby->custnum };
+
+ foreach my $field (
+ qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
+ ) {
+ next unless exists($p->{$field});
+ $cust_payby->set($field,$p->{$field});
+ }
+ $cust_payby->set( 'paymask' => $cust_payby->mask_payinfo );
+
+ # Update column if given a value, and the given value wasn't
+ # the value generated by $cust_main->masked($column);
+ $cust_main->set( $_, $p->{$_} )
+ for grep{ $p->{$_} !~ /^x/i; }
+ grep{ exists $p->{$_} }
+ qw/ss stateid/;
+
+ # Perform updates within a transaction
+ local $FS::UID::AutoCommit = 0;
+
+ if ( my $error = $cust_payby->replace || $cust_main->replace ) {
+ dbh->rollback;
+ return { error => $error };
+ }
+
+ dbh->commit;
+ return { custpaybynum => $cust_payby->custpaybynum };
+}
+