+ return () if $self->closed;
+ qsearch({
+ 'table' => 'cust_pay_refund',
+ 'hashref' => { 'paynum' => $self->paynum },
+ 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
+ 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
+ });
+}
+
+=item unapply_refund
+
+Deletes all objects returned by L</refund_to_unapply>.
+
+=cut
+
+sub unapply_refund {
+ my $self = shift;
+
+ local $SIG{HUP} = 'IGNORE';
+ local $SIG{INT} = 'IGNORE';
+ local $SIG{QUIT} = 'IGNORE';
+ local $SIG{TERM} = 'IGNORE';
+ local $SIG{TSTP} = 'IGNORE';
+ local $SIG{PIPE} = 'IGNORE';
+
+ my $oldAutoCommit = $FS::UID::AutoCommit;
+ local $FS::UID::AutoCommit = 0;
+
+ foreach my $cust_pay_refund ($self->refund_to_unapply) {
+ my $error = $cust_pay_refund->delete;
+ if ($error) {
+ dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+ }
+
+ dbh->commit or die dbh->errstr if $oldAutoCommit;
+ return '';
+}
+
+=back
+
+=head1 CLASS METHODS
+
+=over 4
+
+=item batch_insert CUST_PAY_OBJECT, ...
+
+Class method which inserts multiple payments. Takes a list of FS::cust_pay
+objects. Returns a list, each element representing the status of inserting the
+corresponding payment - empty. If there is an error inserting any payment, the
+entire transaction is rolled back, i.e. all payments are inserted or none are.
+
+FS::cust_pay objects may have the pseudo-field 'apply_to', containing a
+reference to an array of (uninserted) FS::cust_bill_pay objects. If so,
+those objects will be inserted with the paynum of the payment, and for
+each one, an error message or an empty string will be inserted into the
+list of errors.
+
+For example:
+
+ my @errors = FS::cust_pay->batch_insert(@cust_pay);
+ my $num_errors = scalar(grep $_, @errors);
+ if ( $num_errors == 0 ) {
+ #success; all payments were inserted
+ } else {
+ #failure; no payments were inserted.
+ }
+
+=cut
+
+sub batch_insert {
+ my $self = shift; #class method
+
+ local $SIG{HUP} = 'IGNORE';
+ local $SIG{INT} = 'IGNORE';
+ local $SIG{QUIT} = 'IGNORE';
+ local $SIG{TERM} = 'IGNORE';
+ local $SIG{TSTP} = 'IGNORE';
+ local $SIG{PIPE} = 'IGNORE';
+
+ my $oldAutoCommit = $FS::UID::AutoCommit;
+ local $FS::UID::AutoCommit = 0;
+ my $dbh = dbh;
+
+ my $num_errors = 0;
+
+ my @errors;
+ foreach my $cust_pay (@_) {
+ my $error = $cust_pay->insert( 'manual' => 1 );
+ push @errors, $error;
+ $num_errors++ if $error;
+
+ if ( ref($cust_pay->get('apply_to')) eq 'ARRAY' ) {
+
+ foreach my $cust_bill_pay ( @{ $cust_pay->apply_to } ) {
+ if ( $error ) { # insert placeholders if cust_pay wasn't inserted
+ push @errors, '';
+ }
+ else {
+ $cust_bill_pay->set('paynum', $cust_pay->paynum);
+ my $apply_error = $cust_bill_pay->insert;
+ push @errors, $apply_error || '';
+ $num_errors++ if $apply_error;
+ }
+ }
+
+ } elsif ( !$error ) { #normal case: apply payments as usual
+ $cust_pay->cust_main->apply_payments( 'manual'=>1 );
+ }
+
+ }
+
+ if ( $num_errors ) {
+ $dbh->rollback if $oldAutoCommit;
+ } else {
+ $dbh->commit or die $dbh->errstr if $oldAutoCommit;
+ }
+
+ @errors;
+
+}
+
+=item unapplied_sql
+
+Returns an SQL fragment to retreive the unapplied amount.
+
+=cut
+
+sub unapplied_sql {
+ my ($class, $start, $end) = @_;
+ my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
+ my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
+ my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
+ my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
+
+ "paid
+ - COALESCE(
+ ( SELECT SUM(amount) FROM cust_bill_pay
+ WHERE cust_pay.paynum = cust_bill_pay.paynum
+ $bill_start $bill_end )
+ ,0
+ )
+ - COALESCE(
+ ( SELECT SUM(amount) FROM cust_pay_refund
+ WHERE cust_pay.paynum = cust_pay_refund.paynum
+ $refund_start $refund_end )
+ ,0
+ )
+ ";
+
+}
+
+sub API_getinfo {
+ my $self = shift;
+ my @fields = grep { $_ ne 'payinfo' } $self->fields;
+ +{ ( map { $_=>$self->$_ } @fields ),
+ };
+}
+
+=item SSAPI_getinfo
+
+=cut
+
+sub SSAPI_getinfo {
+ #my( $self, %opt ) = @_;
+ my $self = shift;
+
+ +{ 'paynum' => $self->paynum,
+ '_date' => $self->_date,
+ 'date' => time2str("%b %o, %Y", $self->_date),
+ 'date_short' => time2str("%m-%d-%Y", $self->_date),
+ 'paid' => sprintf('%.2f', $self->paid),
+ 'payby' => $self->payby,
+ 'paycardtype' => $self->paycardtype,
+ 'paymask' => $self->paymask,
+ 'processor' => $self->processor,
+ 'auth' => $self->auth,
+ 'order_number' => $self->order_number,
+ };
+
+}
+
+
+# _upgrade_data
+#
+# Used by FS::Upgrade to migrate to a new database.
+
+use FS::h_cust_pay;
+
+sub _upgrade_data { #class method
+ my ($class, %opt) = @_;
+
+ warn "$me upgrading $class\n" if $DEBUG;
+
+ $class->_upgrade_reasonnum(%opt);
+
+ local $FS::payinfo_Mixin::ignore_masked_payinfo = 1;
+
+ ##
+ # otaker/ivan upgrade
+ ##
+
+ unless ( FS::upgrade_journal->is_done('cust_pay__otaker_ivan') ) {
+
+ #not the most efficient, but hey, it only has to run once
+
+ my $where = " WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' )
+ AND usernum IS NULL
+ AND EXISTS ( SELECT 1 FROM cust_main
+ WHERE cust_main.custnum = cust_pay.custnum )
+ ";
+
+ my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
+
+ my $sth = dbh->prepare($count_sql) or die dbh->errstr;
+ $sth->execute or die $sth->errstr;
+ my $total = $sth->fetchrow_arrayref->[0];
+ #warn "$total cust_pay records to update\n"
+ # if $DEBUG;
+ local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
+
+ my $count = 0;
+ my $lastprog = 0;
+
+ my @cust_pay = qsearch( {
+ 'table' => 'cust_pay',
+ 'hashref' => {},
+ 'extra_sql' => $where,
+ 'order_by' => 'ORDER BY paynum',
+ } );
+
+ foreach my $cust_pay (@cust_pay) {
+
+ my $h_cust_pay = $cust_pay->h_search('insert');
+ if ( $h_cust_pay ) {
+ next if $cust_pay->otaker eq $h_cust_pay->history_user;
+ #$cust_pay->otaker($h_cust_pay->history_user);
+ $cust_pay->set('otaker', $h_cust_pay->history_user);
+ } else {
+ $cust_pay->set('otaker', 'legacy');
+ }
+
+ my $error = $cust_pay->replace;
+
+ if ( $error ) {
+ warn " *** WARNING: Error updating order taker for payment paynum ".
+ $cust_pay->paynun. ": $error\n";
+ next;
+ }
+
+ $count++;
+ if ( $DEBUG > 1 && $lastprog + 30 < time ) {
+ warn "$me $count/$total (".sprintf('%.2f',100*$count/$total). '%)'."\n";
+ $lastprog = time;
+ }
+
+ }
+
+ FS::upgrade_journal->set_done('cust_pay__otaker_ivan');
+ }
+
+ ###
+ # payinfo N/A upgrade
+ ###
+
+ unless ( FS::upgrade_journal->is_done('cust_pay__payinfo_na') ) {
+
+ #XXX remove the 'N/A (tokenized)' part (or just this entire thing)
+
+ my @na_cust_pay = qsearch( {
+ 'table' => 'cust_pay',
+ 'hashref' => {}, #could be encrypted# { 'payinfo' => 'N/A' },
+ 'extra_sql' => "WHERE ( payinfo = 'N/A' OR paymask = 'N/AA' OR paymask = 'N/A (tokenized)' ) AND payby IN ( 'CARD', 'CHEK' )",
+ } );
+
+ foreach my $na ( @na_cust_pay ) {
+
+ next unless $na->payinfo eq 'N/A';
+
+ my $cust_pay_pending =
+ qsearchs('cust_pay_pending', { 'paynum' => $na->paynum } );
+ unless ( $cust_pay_pending ) {
+ warn " *** WARNING: not-yet recoverable N/A card for payment ".
+ $na->paynum. " (no cust_pay_pending)\n";
+ next;
+ }
+ $na->$_($cust_pay_pending->$_) for qw( payinfo paymask );
+ my $error = $na->replace;
+ if ( $error ) {
+ warn " *** WARNING: Error updating payinfo for payment paynum ".
+ $na->paynun. ": $error\n";
+ next;
+ }
+
+ }
+
+ FS::upgrade_journal->set_done('cust_pay__payinfo_na');
+ }
+
+ ###
+ # otaker->usernum upgrade
+ ###
+
+ $class->_upgrade_otaker(%opt);
+
+ # if we do this anywhere else, it should become an FS::Upgrade method
+ my $num_to_upgrade = $class->count('paybatch is not null');
+ my $num_jobs = FS::queue->count('job = \'FS::cust_pay::process_upgrade_paybatch\' and status != \'failed\'');
+ if ( $num_to_upgrade > 0 ) {
+ warn "Need to migrate paybatch field in $num_to_upgrade payments.\n";
+ if ( $opt{queue} ) {
+ if ( $num_jobs > 0 ) {
+ warn "Upgrade already queued.\n";
+ } else {
+ warn "Scheduling upgrade.\n";
+ my $job = FS::queue->new({ job => 'FS::cust_pay::process_upgrade_paybatch' });
+ $job->insert;
+ }
+ } else {
+ process_upgrade_paybatch();
+ }
+ }
+
+ ###
+ # set paycardtype
+ ###
+ $class->upgrade_set_cardtype;
+
+ # for batch payments, make sure paymask is set
+ do {
+ local $FS::payinfo_Mixin::allow_closed_replace = 1;
+ local $FS::payinfo_Mixin::ignore_masked_payinfo = 1;
+
+ my $cursor = FS::Cursor->new({
+ table => 'cust_pay',
+ extra_sql => ' WHERE paymask IS NULL AND payinfo IS NOT NULL
+ AND payby IN(\'CARD\', \'CHEK\')
+ AND batchnum IS NOT NULL',
+ });
+
+ # records from cursors for some reason don't decrypt payinfo, so
+ # call replace_old to fetch the record "normally"
+ while (my $cust_pay = $cursor->fetch) {
+ $cust_pay = $cust_pay->replace_old;
+ $cust_pay->set('paymask', $cust_pay->mask_payinfo);
+ my $error = $cust_pay->replace;
+ if ($error) {
+ die "$error (setting masked payinfo on payment#". $cust_pay->paynum.
+ ")\n"
+ }
+ }
+ };
+}
+
+sub process_upgrade_paybatch {
+ my $dbh = dbh;
+ local $FS::payinfo_Mixin::ignore_masked_payinfo = 1;
+ local $FS::UID::AutoCommit = 1;
+
+ ###
+ # migrate batchnums from the misused 'paybatch' field to 'batchnum'
+ ###
+ my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
+ my $search = FS::Cursor->new( {
+ 'table' => 'cust_pay',
+ 'addl_from' => " JOIN pay_batch ON cust_pay.paybatch = CAST(pay_batch.batchnum AS $text) ",
+ } );
+ while (my $cust_pay = $search->fetch) {
+ $cust_pay->set('batchnum' => $cust_pay->paybatch);
+ $cust_pay->set('paybatch' => '');
+ my $error = $cust_pay->replace;
+ warn "error setting batchnum on cust_pay #".$cust_pay->paynum.":\n $error"
+ if $error;
+ }
+
+ ###
+ # migrate gateway info from the misused 'paybatch' field
+ ###
+
+ # not only cust_pay, but also voided and refunded payments
+ if (!FS::upgrade_journal->is_done('cust_pay__parse_paybatch_1')) {
+ local $FS::Record::nowarn_classload=1;
+ # really inefficient, but again, only has to run once
+ foreach my $table (qw(cust_pay cust_pay_void cust_refund)) {
+ my $and_batchnum_is_null =
+ ( $table =~ /^cust_pay/ ? ' AND batchnum IS NULL' : '' );
+ my $pkey = ($table =~ /^cust_pay/ ? 'paynum' : 'refundnum');
+ my $search = FS::Cursor->new({
+ table => $table,
+ extra_sql => "WHERE payby IN('CARD','CHEK') ".
+ "AND (paybatch IS NOT NULL ".
+ "OR (paybatch IS NULL AND auth IS NULL
+ $and_batchnum_is_null ) )
+ ORDER BY $pkey DESC"
+ });
+ while ( my $object = $search->fetch ) {
+ if ( $object->paybatch eq '' ) {
+ # repair for a previous upgrade that didn't save 'auth'
+ my $pkey = $object->primary_key;
+ # find the last history record that had a paybatch value
+ my $h = qsearchs({
+ table => "h_$table",
+ hashref => {
+ $pkey => $object->$pkey,
+ paybatch => { op=>'!=', value=>''},
+ history_action => 'replace_old',
+ },
+ order_by => 'ORDER BY history_date DESC LIMIT 1',
+ });
+ if (!$h) {
+ warn "couldn't find paybatch history record for $table ".$object->$pkey."\n";
+ next;
+ }
+ # if the paybatch didn't have an auth string, then it's fine
+ $h->paybatch =~ /:(\w+):/ or next;
+ # set paybatch to what it was in that record
+ $object->set('paybatch', $h->paybatch)
+ # and then upgrade it like the old records
+ }
+
+ my $parsed = $object->_parse_paybatch;
+ if (keys %$parsed) {
+ $object->set($_ => $parsed->{$_}) foreach keys %$parsed;
+ $object->set('auth' => $parsed->{authorization});
+ $object->set('paybatch', '');
+ my $error = $object->replace;
+ warn "error parsing CARD/CHEK paybatch fields on $object #".
+ $object->get($object->primary_key).":\n $error\n"
+ if $error;
+ }
+ } #$object
+ } #$table
+ FS::upgrade_journal->set_done('cust_pay__parse_paybatch_1');
+ }
+}
+
+=back
+
+=head1 SUBROUTINES
+
+=over 4
+
+=item process_batch_import
+
+=cut
+
+sub process_batch_import {
+ my $job = shift;
+
+ my $hashcb = sub {
+ my %hash = @_;
+ my $custnum = $hash{'custnum'};
+ my $agentnum = $hash{'agentnum'};
+ my $agent_custid = $hash{'agent_custid'};
+ #standardize date
+ $hash{'_date'} = parse_datetime($hash{'_date'})
+ if $hash{'_date'} && $hash{'_date'} =~ /\D/;
+ #remove custnum_prefix
+ my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
+ my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
+ if (
+ $custnum_prefix
+ && $custnum =~ /^$custnum_prefix(0*([1-9]\d*))$/
+ && length($1) == $custnum_length
+ ) {
+ $custnum = $2;
+ }
+ # check agentnum against custnum and
+ # translate agent_custid into regular custnum
+ if ($custnum && $agent_custid) {
+ die "can't specify both custnum and agent_custid\n";
+ } elsif ($agentnum || $agent_custid) {
+ # here is the agent virtualization
+ my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
+ my %search;
+ $search{'agentnum'} = $agentnum
+ if $agentnum;
+ $search{'agent_custid'} = $agent_custid
+ if $agent_custid;
+ $search{'custnum'} = $custnum
+ if $custnum;
+ my $cust_main = qsearchs({
+ 'table' => 'cust_main',
+ 'hashref' => \%search,
+ 'extra_sql' => $extra_sql,
+ });
+ die "can't find customer with" .
+ ($agentnum ? " agentnum $agentnum" : '') .
+ ($custnum ? " custnum $custnum" : '') .
+ ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
+ unless $cust_main;
+ die "mismatched customer number\n"
+ if $custnum && ($custnum ne $cust_main->custnum);
+ $custnum = $cust_main->custnum;
+ }
+ $hash{'custnum'} = $custnum;
+ delete($hash{'agent_custid'});
+ return %hash;
+ };
+
+ my $opt = {
+ 'table' => 'cust_pay',
+ 'params' => [ '_date', 'agentnum', 'payby', 'paybatch' ],
+ #agent_custid isn't a cust_pay field, see hash callback
+ 'formats' => { 'simple' =>
+ [ qw(custnum agent_custid paid payinfo invnum) ] },
+ 'format_types' => { 'simple' => '' }, #force infer from file extension
+ 'default_csv' => 1, #if not .xls, will read as csv, regardless of extension
+ 'format_hash_callbacks' => { 'simple' => $hashcb },
+ 'insert_args_callback' => sub { ( 'manual'=>1 ); },
+ 'postinsert_callback' => sub {
+ my $cust_pay = shift;
+ my $cust_main = $cust_pay->cust_main
+ or return "can't find customer to which payments apply";
+ my $error = $cust_main->apply_payments_and_credits( 'manual'=>1 );
+ return $error
+ ? "can't apply payments to customer ".$cust_pay->custnum."$error"
+ : '';
+ },
+ };
+
+ FS::Record::process_batch_import( $job, $opt, @_ );
+
+}
+
+=item batch_import HASHREF
+
+Inserts new payments.
+
+=cut
+
+sub batch_import {
+ my $param = shift;
+
+ my $fh = $param->{filehandle};
+ my $format = $param->{'format'};
+
+ my $agentnum = $param->{agentnum};
+ my $_date = $param->{_date};
+ $_date = parse_datetime($_date) if $_date && $_date =~ /\D/;
+ my $paybatch = $param->{'paybatch'};
+
+ my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
+ my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
+
+ # here is the agent virtualization
+ my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
+
+ my @fields;
+ my $payby;
+ if ( $format eq 'simple' ) {
+ @fields = qw( custnum agent_custid paid payinfo invnum );
+ $payby = 'BILL';
+ } elsif ( $format eq 'extended' ) {
+ die "unimplemented\n";
+ @fields = qw( );
+ $payby = 'BILL';
+ } else {
+ die "unknown format $format";
+ }
+
+ eval "use Text::CSV_XS;";
+ die $@ if $@;
+
+ my $csv = new Text::CSV_XS;
+
+ my $imported = 0;
+
+ local $SIG{HUP} = 'IGNORE';
+ local $SIG{INT} = 'IGNORE';
+ local $SIG{QUIT} = 'IGNORE';
+ local $SIG{TERM} = 'IGNORE';
+ local $SIG{TSTP} = 'IGNORE';
+ local $SIG{PIPE} = 'IGNORE';
+
+ my $oldAutoCommit = $FS::UID::AutoCommit;
+ local $FS::UID::AutoCommit = 0;
+ my $dbh = dbh;
+
+ my $line;
+ while ( defined($line=<$fh>) ) {
+
+ $csv->parse($line) or do {
+ $dbh->rollback if $oldAutoCommit;
+ return "can't parse: ". $csv->error_input();
+ };
+
+ my @columns = $csv->fields();
+
+ my %cust_pay = (
+ payby => $payby,
+ paybatch => $paybatch,
+ );
+ $cust_pay{_date} = $_date if $_date;
+
+ my $cust_main;
+ foreach my $field ( @fields ) {
+
+ if ( $field eq 'agent_custid'
+ && $agentnum
+ && $columns[0] =~ /\S+/ )
+ {
+
+ my $agent_custid = $columns[0];
+ my %hash = ( 'agent_custid' => $agent_custid,
+ 'agentnum' => $agentnum,
+ );
+
+ if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
+ $dbh->rollback if $oldAutoCommit;
+ return "can't specify custnum with agent_custid $agent_custid";
+ }
+
+ $cust_main = qsearchs({
+ 'table' => 'cust_main',
+ 'hashref' => \%hash,
+ 'extra_sql' => $extra_sql,
+ });
+
+ unless ( $cust_main ) {
+ $dbh->rollback if $oldAutoCommit;
+ return "can't find customer with agent_custid $agent_custid";
+ }
+
+ $field = 'custnum';
+ $columns[0] = $cust_main->custnum;
+ }
+
+ $cust_pay{$field} = shift @columns;
+ }
+
+ if ( $custnum_prefix && $cust_pay{custnum} =~ /^$custnum_prefix(0*([1-9]\d*))$/
+ && length($1) == $custnum_length ) {
+ $cust_pay{custnum} = $2;
+ }
+
+ my $custnum = $cust_pay{custnum};
+
+ my $cust_pay = new FS::cust_pay( \%cust_pay );
+ my $error = $cust_pay->insert;
+
+ if ( ! $error && $cust_pay->custnum != $custnum ) {
+ #invnum was defined, and ->insert set custnum to the customer for that
+ #invoice, but it wasn't the one the import specified.
+ $dbh->rollback if $oldAutoCommit;
+ $error = "specified invoice #". $cust_pay{invnum}.
+ " is for custnum ". $cust_pay->custnum.
+ ", not specified custnum $custnum";
+ }
+
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return "can't insert payment for $line: $error";
+ }
+
+ if ( $format eq 'simple' ) {
+ # include agentnum for less surprise?
+ $cust_main = qsearchs({
+ 'table' => 'cust_main',
+ 'hashref' => { 'custnum' => $cust_pay->custnum },
+ 'extra_sql' => $extra_sql,
+ })
+ unless $cust_main;
+
+ unless ( $cust_main ) {
+ $dbh->rollback if $oldAutoCommit;
+ return "can't find customer to which payments apply at line: $line";
+ }
+
+ $error = $cust_main->apply_payments_and_credits;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return "can't apply payments to customer for $line: $error";
+ }
+
+ }
+
+ $imported++;
+ }
+
+ $dbh->commit or die $dbh->errstr if $oldAutoCommit;
+
+ return "Empty file!" unless $imported;
+
+ ''; #no error
+