5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 use Scalar::Util qw( blessed );
12 use List::Util qw( min );
13 use Time::Local qw(timelocal);
16 use Digest::MD5 qw(md5_base64);
19 use File::Temp qw( tempfile );
20 use String::Approx qw(amatch);
21 use Business::CreditCard 0.28;
23 use FS::UID qw( getotaker dbh driver_name );
24 use FS::Record qw( qsearchs qsearch dbdef );
25 use FS::Misc qw( generate_email send_email generate_ps do_print );
26 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
32 use FS::cust_bill_pkg_display;
33 use FS::cust_bill_pkg_tax_location;
34 use FS::cust_bill_pkg_tax_rate_location;
36 use FS::cust_pay_pending;
37 use FS::cust_pay_void;
38 use FS::cust_pay_batch;
41 use FS::part_referral;
42 use FS::cust_main_county;
43 use FS::cust_location;
44 use FS::cust_main_exemption;
45 use FS::cust_tax_adjustment;
47 use FS::tax_rate_location;
48 use FS::cust_tax_location;
49 use FS::part_pkg_taxrate;
51 use FS::cust_main_invoice;
52 use FS::cust_credit_bill;
53 use FS::cust_bill_pay;
54 use FS::prepay_credit;
58 use FS::part_event_condition;
61 use FS::payment_gateway;
62 use FS::agent_payment_gateway;
64 use FS::payinfo_Mixin;
67 @ISA = qw( FS::payinfo_Mixin FS::Record );
69 @EXPORT_OK = qw( smart_search );
71 $realtime_bop_decline_quiet = 0;
73 # 1 is mostly method/subroutine entry and options
74 # 2 traces progress of some operations
75 # 3 is even more information including possibly sensitive data
77 $me = '[FS::cust_main]';
81 $ignore_expired_card = 0;
83 @encrypted_fields = ('payinfo', 'paycvv');
84 sub nohistory_fields { ('paycvv'); }
86 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
88 #ask FS::UID to run this stuff for us later
89 #$FS::UID::callback{'FS::cust_main'} = sub {
90 install_callback FS::UID sub {
92 #yes, need it for stuff below (prolly should be cached)
97 my ( $hashref, $cache ) = @_;
98 if ( exists $hashref->{'pkgnum'} ) {
99 #@{ $self->{'_pkgnum'} } = ();
100 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
101 $self->{'_pkgnum'} = $subcache;
102 #push @{ $self->{'_pkgnum'} },
103 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
109 FS::cust_main - Object methods for cust_main records
115 $record = new FS::cust_main \%hash;
116 $record = new FS::cust_main { 'column' => 'value' };
118 $error = $record->insert;
120 $error = $new_record->replace($old_record);
122 $error = $record->delete;
124 $error = $record->check;
126 @cust_pkg = $record->all_pkgs;
128 @cust_pkg = $record->ncancelled_pkgs;
130 @cust_pkg = $record->suspended_pkgs;
132 $error = $record->bill;
133 $error = $record->bill %options;
134 $error = $record->bill 'time' => $time;
136 $error = $record->collect;
137 $error = $record->collect %options;
138 $error = $record->collect 'invoice_time' => $time,
143 An FS::cust_main object represents a customer. FS::cust_main inherits from
144 FS::Record. The following fields are currently supported:
150 Primary key (assigned automatically for new customers)
154 Agent (see L<FS::agent>)
158 Advertising source (see L<FS::part_referral>)
170 Cocial security number (optional)
186 (optional, see L<FS::cust_main_county>)
190 (see L<FS::cust_main_county>)
196 (see L<FS::cust_main_county>)
232 (optional, see L<FS::cust_main_county>)
236 (see L<FS::cust_main_county>)
242 (see L<FS::cust_main_county>)
258 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
262 Payment Information (See L<FS::payinfo_Mixin> for data format)
266 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
270 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
274 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
278 Start date month (maestro/solo cards only)
282 Start date year (maestro/solo cards only)
286 Issue number (maestro/solo cards only)
290 Name on card or billing name
294 IP address from which payment information was received
298 Tax exempt, empty or `Y'
302 Order taker (assigned automatically, see L<FS::UID>)
308 =item referral_custnum
310 Referring customer number
314 Enable individual CDR spooling, empty or `Y'
318 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
322 Discourage individual CDR printing, empty or `Y'
332 Creates a new customer. To add the customer to the database, see L<"insert">.
334 Note that this stores the hash reference, not a distinct copy of the hash it
335 points to. You can ask the object for a copy with the I<hash> method.
339 sub table { 'cust_main'; }
341 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
343 Adds this customer to the database. If there is an error, returns the error,
344 otherwise returns false.
346 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
347 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
348 are inserted atomicly, or the transaction is rolled back. Passing an empty
349 hash reference is equivalent to not supplying this parameter. There should be
350 a better explanation of this, but until then, here's an example:
353 tie %hash, 'Tie::RefHash'; #this part is important
355 $cust_pkg => [ $svc_acct ],
358 $cust_main->insert( \%hash );
360 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
361 be set as the invoicing list (see L<"invoicing_list">). Errors return as
362 expected and rollback the entire transaction; it is not necessary to call
363 check_invoicing_list first. The invoicing_list is set after the records in the
364 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
365 invoicing_list destination to the newly-created svc_acct. Here's an example:
367 $cust_main->insert( {}, [ $email, 'POST' ] );
369 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
371 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
372 on the supplied jobnum (they will not run until the specific job completes).
373 This can be used to defer provisioning until some action completes (such
374 as running the customer's credit card successfully).
376 The I<noexport> option is deprecated. If I<noexport> is set true, no
377 provisioning jobs (exports) are scheduled. (You can schedule them later with
378 the B<reexport> method.)
380 The I<tax_exemption> option can be set to an arrayref of tax names.
381 FS::cust_main_exemption records will be created and inserted.
387 my $cust_pkgs = @_ ? shift : {};
388 my $invoicing_list = @_ ? shift : '';
390 warn "$me insert called with options ".
391 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
394 local $SIG{HUP} = 'IGNORE';
395 local $SIG{INT} = 'IGNORE';
396 local $SIG{QUIT} = 'IGNORE';
397 local $SIG{TERM} = 'IGNORE';
398 local $SIG{TSTP} = 'IGNORE';
399 local $SIG{PIPE} = 'IGNORE';
401 my $oldAutoCommit = $FS::UID::AutoCommit;
402 local $FS::UID::AutoCommit = 0;
405 my $prepay_identifier = '';
406 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
408 if ( $self->payby eq 'PREPAY' ) {
410 $self->payby('BILL');
411 $prepay_identifier = $self->payinfo;
414 warn " looking up prepaid card $prepay_identifier\n"
417 my $error = $self->get_prepay( $prepay_identifier,
418 'amount_ref' => \$amount,
419 'seconds_ref' => \$seconds,
420 'upbytes_ref' => \$upbytes,
421 'downbytes_ref' => \$downbytes,
422 'totalbytes_ref' => \$totalbytes,
425 $dbh->rollback if $oldAutoCommit;
426 #return "error applying prepaid card (transaction rolled back): $error";
430 $payby = 'PREP' if $amount;
432 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
435 $self->payby('BILL');
436 $amount = $self->paid;
440 warn " inserting $self\n"
443 $self->signupdate(time) unless $self->signupdate;
445 $self->auto_agent_custid()
446 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
448 my $error = $self->SUPER::insert;
450 $dbh->rollback if $oldAutoCommit;
451 #return "inserting cust_main record (transaction rolled back): $error";
455 warn " setting invoicing list\n"
458 if ( $invoicing_list ) {
459 $error = $self->check_invoicing_list( $invoicing_list );
461 $dbh->rollback if $oldAutoCommit;
462 #return "checking invoicing_list (transaction rolled back): $error";
465 $self->invoicing_list( $invoicing_list );
468 warn " setting cust_main_exemption\n"
471 my $tax_exemption = delete $options{'tax_exemption'};
472 if ( $tax_exemption ) {
473 foreach my $taxname ( @$tax_exemption ) {
474 my $cust_main_exemption = new FS::cust_main_exemption {
475 'custnum' => $self->custnum,
476 'taxname' => $taxname,
478 my $error = $cust_main_exemption->insert;
480 $dbh->rollback if $oldAutoCommit;
481 return "inserting cust_main_exemption (transaction rolled back): $error";
486 if ( $conf->config('cust_main-skeleton_tables')
487 && $conf->config('cust_main-skeleton_custnum') ) {
489 warn " inserting skeleton records\n"
492 my $error = $self->start_copy_skel;
494 $dbh->rollback if $oldAutoCommit;
500 warn " ordering packages\n"
503 $error = $self->order_pkgs( $cust_pkgs,
505 'seconds_ref' => \$seconds,
506 'upbytes_ref' => \$upbytes,
507 'downbytes_ref' => \$downbytes,
508 'totalbytes_ref' => \$totalbytes,
511 $dbh->rollback if $oldAutoCommit;
516 $dbh->rollback if $oldAutoCommit;
517 return "No svc_acct record to apply pre-paid time";
519 if ( $upbytes || $downbytes || $totalbytes ) {
520 $dbh->rollback if $oldAutoCommit;
521 return "No svc_acct record to apply pre-paid data";
525 warn " inserting initial $payby payment of $amount\n"
527 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
529 $dbh->rollback if $oldAutoCommit;
530 return "inserting payment (transaction rolled back): $error";
534 unless ( $import || $skip_fuzzyfiles ) {
535 warn " queueing fuzzyfiles update\n"
537 $error = $self->queue_fuzzyfiles_update;
539 $dbh->rollback if $oldAutoCommit;
540 return "updating fuzzy search cache: $error";
544 warn " insert complete; committing transaction\n"
547 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
552 use File::CounterFile;
553 sub auto_agent_custid {
556 my $format = $conf->config('cust_main-auto_agent_custid');
558 if ( $format eq '1YMMXXXXXXXX' ) {
560 my $counter = new File::CounterFile 'cust_main.agent_custid';
563 my $ym = 100000000000 + time2str('%y%m00000000', time);
564 if ( $ym > $counter->value ) {
565 $counter->{'value'} = $agent_custid = $ym;
566 $counter->{'updated'} = 1;
568 $agent_custid = $counter->inc;
574 die "Unknown cust_main-auto_agent_custid format: $format";
577 $self->agent_custid($agent_custid);
581 sub start_copy_skel {
584 #'mg_user_preference' => {},
585 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
586 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
587 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
588 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
589 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
592 _copy_skel( 'cust_main', #tablename
593 $conf->config('cust_main-skeleton_custnum'), #sourceid
594 $self->custnum, #destid
595 @tables, #child tables
599 #recursive subroutine, not a method
601 my( $table, $sourceid, $destid, %child_tables ) = @_;
604 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
605 ( $table, $primary_key ) = ( $1, $2 );
607 my $dbdef_table = dbdef->table($table);
608 $primary_key = $dbdef_table->primary_key
609 or return "$table has no primary key".
610 " (or do you need to run dbdef-create?)";
613 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
614 join (', ', keys %child_tables). "\n"
617 foreach my $child_table_def ( keys %child_tables ) {
621 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
622 ( $child_table, $child_pkey ) = ( $1, $2 );
624 $child_table = $child_table_def;
626 $child_pkey = dbdef->table($child_table)->primary_key;
627 # or return "$table has no primary key".
628 # " (or do you need to run dbdef-create?)\n";
632 if ( keys %{ $child_tables{$child_table_def} } ) {
634 return "$child_table has no primary key".
635 " (run dbdef-create or try specifying it?)\n"
638 #false laziness w/Record::insert and only works on Pg
639 #refactor the proper last-inserted-id stuff out of Record::insert if this
640 # ever gets use for anything besides a quick kludge for one customer
641 my $default = dbdef->table($child_table)->column($child_pkey)->default;
642 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
643 or return "can't parse $child_table.$child_pkey default value ".
644 " for sequence name: $default";
649 my @sel_columns = grep { $_ ne $primary_key }
650 dbdef->table($child_table)->columns;
651 my $sel_columns = join(', ', @sel_columns );
653 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
654 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
655 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
657 my $sel_st = "SELECT $sel_columns FROM $child_table".
658 " WHERE $primary_key = $sourceid";
661 my $sel_sth = dbh->prepare( $sel_st )
662 or return dbh->errstr;
664 $sel_sth->execute or return $sel_sth->errstr;
666 while ( my $row = $sel_sth->fetchrow_hashref ) {
668 warn " selected row: ".
669 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
673 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
674 my $ins_sth =dbh->prepare($statement)
675 or return dbh->errstr;
676 my @param = ( $destid, map $row->{$_}, @ins_columns );
677 warn " $statement: [ ". join(', ', @param). " ]\n"
679 $ins_sth->execute( @param )
680 or return $ins_sth->errstr;
682 #next unless keys %{ $child_tables{$child_table} };
683 next unless $sequence;
685 #another section of that laziness
686 my $seq_sql = "SELECT currval('$sequence')";
687 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
688 $seq_sth->execute or return $seq_sth->errstr;
689 my $insertid = $seq_sth->fetchrow_arrayref->[0];
691 # don't drink soap! recurse! recurse! okay!
693 _copy_skel( $child_table_def,
694 $row->{$child_pkey}, #sourceid
696 %{ $child_tables{$child_table_def} },
698 return $error if $error;
708 =item order_pkg HASHREF | OPTION => VALUE ...
710 Orders a single package.
712 Options may be passed as a list of key/value pairs or as a hash reference.
723 Optional FS::cust_location object
727 Optional arryaref of FS::svc_* service objects.
731 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
732 jobs will have a dependancy on the supplied job (they will not run until the
733 specific job completes). This can be used to defer provisioning until some
734 action completes (such as running the customer's credit card successfully).
738 Optional subject for a ticket created and attached to this customer
742 Optional queue name for ticket additions
750 my $opt = ref($_[0]) ? shift : { @_ };
752 warn "$me order_pkg called with options ".
753 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
756 my $cust_pkg = $opt->{'cust_pkg'};
757 my $svcs = $opt->{'svcs'} || [];
759 my %svc_options = ();
760 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
761 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
763 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
764 qw( ticket_subject ticket_queue );
766 local $SIG{HUP} = 'IGNORE';
767 local $SIG{INT} = 'IGNORE';
768 local $SIG{QUIT} = 'IGNORE';
769 local $SIG{TERM} = 'IGNORE';
770 local $SIG{TSTP} = 'IGNORE';
771 local $SIG{PIPE} = 'IGNORE';
773 my $oldAutoCommit = $FS::UID::AutoCommit;
774 local $FS::UID::AutoCommit = 0;
777 if ( $opt->{'cust_location'} &&
778 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
779 my $error = $opt->{'cust_location'}->insert;
781 $dbh->rollback if $oldAutoCommit;
782 return "inserting cust_location (transaction rolled back): $error";
784 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
787 $cust_pkg->custnum( $self->custnum );
789 my $error = $cust_pkg->insert( %insert_params );
791 $dbh->rollback if $oldAutoCommit;
792 return "inserting cust_pkg (transaction rolled back): $error";
795 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
796 if ( $svc_something->svcnum ) {
797 my $old_cust_svc = $svc_something->cust_svc;
798 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
799 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
800 $error = $new_cust_svc->replace($old_cust_svc);
802 $svc_something->pkgnum( $cust_pkg->pkgnum );
803 if ( $svc_something->isa('FS::svc_acct') ) {
804 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
805 qw( seconds upbytes downbytes totalbytes ) ) {
806 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
807 ${ $opt->{$_.'_ref'} } = 0;
810 $error = $svc_something->insert(%svc_options);
813 $dbh->rollback if $oldAutoCommit;
814 return "inserting svc_ (transaction rolled back): $error";
818 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
823 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
824 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
826 Like the insert method on an existing record, this method orders multiple
827 packages and included services atomicaly. Pass a Tie::RefHash data structure
828 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
829 There should be a better explanation of this, but until then, here's an
833 tie %hash, 'Tie::RefHash'; #this part is important
835 $cust_pkg => [ $svc_acct ],
838 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
840 Services can be new, in which case they are inserted, or existing unaudited
841 services, in which case they are linked to the newly-created package.
843 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
844 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
846 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
847 on the supplied jobnum (they will not run until the specific job completes).
848 This can be used to defer provisioning until some action completes (such
849 as running the customer's credit card successfully).
851 The I<noexport> option is deprecated. If I<noexport> is set true, no
852 provisioning jobs (exports) are scheduled. (You can schedule them later with
853 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
854 on the cust_main object is not recommended, as existing services will also be
857 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
858 provided, the scalars (provided by references) will be incremented by the
859 values of the prepaid card.`
865 my $cust_pkgs = shift;
866 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
868 $seconds_ref ||= $options{'seconds_ref'};
870 warn "$me order_pkgs called with options ".
871 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
874 local $SIG{HUP} = 'IGNORE';
875 local $SIG{INT} = 'IGNORE';
876 local $SIG{QUIT} = 'IGNORE';
877 local $SIG{TERM} = 'IGNORE';
878 local $SIG{TSTP} = 'IGNORE';
879 local $SIG{PIPE} = 'IGNORE';
881 my $oldAutoCommit = $FS::UID::AutoCommit;
882 local $FS::UID::AutoCommit = 0;
885 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
887 foreach my $cust_pkg ( keys %$cust_pkgs ) {
889 my $error = $self->order_pkg(
890 'cust_pkg' => $cust_pkg,
891 'svcs' => $cust_pkgs->{$cust_pkg},
892 'seconds_ref' => $seconds_ref,
893 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
898 $dbh->rollback if $oldAutoCommit;
904 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
908 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
910 Recharges this (existing) customer with the specified prepaid card (see
911 L<FS::prepay_credit>), specified either by I<identifier> or as an
912 FS::prepay_credit object. If there is an error, returns the error, otherwise
915 Optionally, five scalar references can be passed as well. They will have their
916 values filled in with the amount, number of seconds, and number of upload,
917 download, and total bytes applied by this prepaid card.
921 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
922 #the only place that uses these args
923 sub recharge_prepay {
924 my( $self, $prepay_credit, $amountref, $secondsref,
925 $upbytesref, $downbytesref, $totalbytesref ) = @_;
927 local $SIG{HUP} = 'IGNORE';
928 local $SIG{INT} = 'IGNORE';
929 local $SIG{QUIT} = 'IGNORE';
930 local $SIG{TERM} = 'IGNORE';
931 local $SIG{TSTP} = 'IGNORE';
932 local $SIG{PIPE} = 'IGNORE';
934 my $oldAutoCommit = $FS::UID::AutoCommit;
935 local $FS::UID::AutoCommit = 0;
938 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
940 my $error = $self->get_prepay( $prepay_credit,
941 'amount_ref' => \$amount,
942 'seconds_ref' => \$seconds,
943 'upbytes_ref' => \$upbytes,
944 'downbytes_ref' => \$downbytes,
945 'totalbytes_ref' => \$totalbytes,
947 || $self->increment_seconds($seconds)
948 || $self->increment_upbytes($upbytes)
949 || $self->increment_downbytes($downbytes)
950 || $self->increment_totalbytes($totalbytes)
951 || $self->insert_cust_pay_prepay( $amount,
953 ? $prepay_credit->identifier
958 $dbh->rollback if $oldAutoCommit;
962 if ( defined($amountref) ) { $$amountref = $amount; }
963 if ( defined($secondsref) ) { $$secondsref = $seconds; }
964 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
965 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
966 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
968 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
973 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
975 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
976 specified either by I<identifier> or as an FS::prepay_credit object.
978 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>. The scalars (provided by references) will be
979 incremented by the values of the prepaid card.
981 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
982 check or set this customer's I<agentnum>.
984 If there is an error, returns the error, otherwise returns false.
990 my( $self, $prepay_credit, %opt ) = @_;
992 local $SIG{HUP} = 'IGNORE';
993 local $SIG{INT} = 'IGNORE';
994 local $SIG{QUIT} = 'IGNORE';
995 local $SIG{TERM} = 'IGNORE';
996 local $SIG{TSTP} = 'IGNORE';
997 local $SIG{PIPE} = 'IGNORE';
999 my $oldAutoCommit = $FS::UID::AutoCommit;
1000 local $FS::UID::AutoCommit = 0;
1003 unless ( ref($prepay_credit) ) {
1005 my $identifier = $prepay_credit;
1007 $prepay_credit = qsearchs(
1009 { 'identifier' => $prepay_credit },
1014 unless ( $prepay_credit ) {
1015 $dbh->rollback if $oldAutoCommit;
1016 return "Invalid prepaid card: ". $identifier;
1021 if ( $prepay_credit->agentnum ) {
1022 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1023 $dbh->rollback if $oldAutoCommit;
1024 return "prepaid card not valid for agent ". $self->agentnum;
1026 $self->agentnum($prepay_credit->agentnum);
1029 my $error = $prepay_credit->delete;
1031 $dbh->rollback if $oldAutoCommit;
1032 return "removing prepay_credit (transaction rolled back): $error";
1035 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1036 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1038 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1043 =item increment_upbytes SECONDS
1045 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1046 the specified number of upbytes. If there is an error, returns the error,
1047 otherwise returns false.
1051 sub increment_upbytes {
1052 _increment_column( shift, 'upbytes', @_);
1055 =item increment_downbytes SECONDS
1057 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1058 the specified number of downbytes. If there is an error, returns the error,
1059 otherwise returns false.
1063 sub increment_downbytes {
1064 _increment_column( shift, 'downbytes', @_);
1067 =item increment_totalbytes SECONDS
1069 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1070 the specified number of totalbytes. If there is an error, returns the error,
1071 otherwise returns false.
1075 sub increment_totalbytes {
1076 _increment_column( shift, 'totalbytes', @_);
1079 =item increment_seconds SECONDS
1081 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1082 the specified number of seconds. If there is an error, returns the error,
1083 otherwise returns false.
1087 sub increment_seconds {
1088 _increment_column( shift, 'seconds', @_);
1091 =item _increment_column AMOUNT
1093 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1094 the specified number of seconds or bytes. If there is an error, returns
1095 the error, otherwise returns false.
1099 sub _increment_column {
1100 my( $self, $column, $amount ) = @_;
1101 warn "$me increment_column called: $column, $amount\n"
1104 return '' unless $amount;
1106 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1107 $self->ncancelled_pkgs;
1109 if ( ! @cust_pkg ) {
1110 return 'No packages with primary or single services found'.
1111 ' to apply pre-paid time';
1112 } elsif ( scalar(@cust_pkg) > 1 ) {
1113 #maybe have a way to specify the package/account?
1114 return 'Multiple packages found to apply pre-paid time';
1117 my $cust_pkg = $cust_pkg[0];
1118 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1122 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1124 if ( ! @cust_svc ) {
1125 return 'No account found to apply pre-paid time';
1126 } elsif ( scalar(@cust_svc) > 1 ) {
1127 return 'Multiple accounts found to apply pre-paid time';
1130 my $svc_acct = $cust_svc[0]->svc_x;
1131 warn " found service svcnum ". $svc_acct->pkgnum.
1132 ' ('. $svc_acct->email. ")\n"
1135 $column = "increment_$column";
1136 $svc_acct->$column($amount);
1140 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1142 Inserts a prepayment in the specified amount for this customer. An optional
1143 second argument can specify the prepayment identifier for tracking purposes.
1144 If there is an error, returns the error, otherwise returns false.
1148 sub insert_cust_pay_prepay {
1149 shift->insert_cust_pay('PREP', @_);
1152 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1154 Inserts a cash payment in the specified amount for this customer. An optional
1155 second argument can specify the payment identifier for tracking purposes.
1156 If there is an error, returns the error, otherwise returns false.
1160 sub insert_cust_pay_cash {
1161 shift->insert_cust_pay('CASH', @_);
1164 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1166 Inserts a Western Union payment in the specified amount for this customer. An
1167 optional second argument can specify the prepayment identifier for tracking
1168 purposes. If there is an error, returns the error, otherwise returns false.
1172 sub insert_cust_pay_west {
1173 shift->insert_cust_pay('WEST', @_);
1176 sub insert_cust_pay {
1177 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1178 my $payinfo = scalar(@_) ? shift : '';
1180 my $cust_pay = new FS::cust_pay {
1181 'custnum' => $self->custnum,
1182 'paid' => sprintf('%.2f', $amount),
1183 #'_date' => #date the prepaid card was purchased???
1185 'payinfo' => $payinfo,
1193 This method is deprecated. See the I<depend_jobnum> option to the insert and
1194 order_pkgs methods for a better way to defer provisioning.
1196 Re-schedules all exports by calling the B<reexport> method of all associated
1197 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1198 otherwise returns false.
1205 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1206 "use the depend_jobnum option to insert or order_pkgs to delay export";
1208 local $SIG{HUP} = 'IGNORE';
1209 local $SIG{INT} = 'IGNORE';
1210 local $SIG{QUIT} = 'IGNORE';
1211 local $SIG{TERM} = 'IGNORE';
1212 local $SIG{TSTP} = 'IGNORE';
1213 local $SIG{PIPE} = 'IGNORE';
1215 my $oldAutoCommit = $FS::UID::AutoCommit;
1216 local $FS::UID::AutoCommit = 0;
1219 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1220 my $error = $cust_pkg->reexport;
1222 $dbh->rollback if $oldAutoCommit;
1227 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1232 =item delete NEW_CUSTNUM
1234 This deletes the customer. If there is an error, returns the error, otherwise
1237 This will completely remove all traces of the customer record. This is not
1238 what you want when a customer cancels service; for that, cancel all of the
1239 customer's packages (see L</cancel>).
1241 If the customer has any uncancelled packages, you need to pass a new (valid)
1242 customer number for those packages to be transferred to. Cancelled packages
1243 will be deleted. Did I mention that this is NOT what you want when a customer
1244 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1246 You can't delete a customer with invoices (see L<FS::cust_bill>),
1247 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1248 refunds (see L<FS::cust_refund>).
1255 local $SIG{HUP} = 'IGNORE';
1256 local $SIG{INT} = 'IGNORE';
1257 local $SIG{QUIT} = 'IGNORE';
1258 local $SIG{TERM} = 'IGNORE';
1259 local $SIG{TSTP} = 'IGNORE';
1260 local $SIG{PIPE} = 'IGNORE';
1262 my $oldAutoCommit = $FS::UID::AutoCommit;
1263 local $FS::UID::AutoCommit = 0;
1266 if ( $self->cust_bill ) {
1267 $dbh->rollback if $oldAutoCommit;
1268 return "Can't delete a customer with invoices";
1270 if ( $self->cust_credit ) {
1271 $dbh->rollback if $oldAutoCommit;
1272 return "Can't delete a customer with credits";
1274 if ( $self->cust_pay ) {
1275 $dbh->rollback if $oldAutoCommit;
1276 return "Can't delete a customer with payments";
1278 if ( $self->cust_refund ) {
1279 $dbh->rollback if $oldAutoCommit;
1280 return "Can't delete a customer with refunds";
1283 my @cust_pkg = $self->ncancelled_pkgs;
1285 my $new_custnum = shift;
1286 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1287 $dbh->rollback if $oldAutoCommit;
1288 return "Invalid new customer number: $new_custnum";
1290 foreach my $cust_pkg ( @cust_pkg ) {
1291 my %hash = $cust_pkg->hash;
1292 $hash{'custnum'} = $new_custnum;
1293 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1294 my $error = $new_cust_pkg->replace($cust_pkg,
1295 options => { $cust_pkg->options },
1298 $dbh->rollback if $oldAutoCommit;
1303 my @cancelled_cust_pkg = $self->all_pkgs;
1304 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1305 my $error = $cust_pkg->delete;
1307 $dbh->rollback if $oldAutoCommit;
1312 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1313 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1315 my $error = $cust_main_invoice->delete;
1317 $dbh->rollback if $oldAutoCommit;
1322 foreach my $cust_main_exemption (
1323 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } )
1325 my $error = $cust_main_exemption->delete;
1327 $dbh->rollback if $oldAutoCommit;
1332 my $error = $self->SUPER::delete;
1334 $dbh->rollback if $oldAutoCommit;
1338 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1343 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1346 Replaces the OLD_RECORD with this one in the database. If there is an error,
1347 returns the error, otherwise returns false.
1349 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1350 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1351 expected and rollback the entire transaction; it is not necessary to call
1352 check_invoicing_list first. Here's an example:
1354 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1356 Currently available options are: I<tax_exemption>.
1358 The I<tax_exemption> option can be set to an arrayref of tax names.
1359 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1366 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1368 : $self->replace_old;
1372 warn "$me replace called\n"
1375 my $curuser = $FS::CurrentUser::CurrentUser;
1376 if ( $self->payby eq 'COMP'
1377 && $self->payby ne $old->payby
1378 && ! $curuser->access_right('Complimentary customer')
1381 return "You are not permitted to create complimentary accounts.";
1384 local($ignore_expired_card) = 1
1385 if $old->payby =~ /^(CARD|DCRD)$/
1386 && $self->payby =~ /^(CARD|DCRD)$/
1387 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1389 local $SIG{HUP} = 'IGNORE';
1390 local $SIG{INT} = 'IGNORE';
1391 local $SIG{QUIT} = 'IGNORE';
1392 local $SIG{TERM} = 'IGNORE';
1393 local $SIG{TSTP} = 'IGNORE';
1394 local $SIG{PIPE} = 'IGNORE';
1396 my $oldAutoCommit = $FS::UID::AutoCommit;
1397 local $FS::UID::AutoCommit = 0;
1400 my $error = $self->SUPER::replace($old);
1403 $dbh->rollback if $oldAutoCommit;
1407 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1408 my $invoicing_list = shift @param;
1409 $error = $self->check_invoicing_list( $invoicing_list );
1411 $dbh->rollback if $oldAutoCommit;
1414 $self->invoicing_list( $invoicing_list );
1417 my %options = @param;
1419 my $tax_exemption = delete $options{'tax_exemption'};
1420 if ( $tax_exemption ) {
1422 my %cust_main_exemption =
1423 map { $_->taxname => $_ }
1424 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1426 foreach my $taxname ( @$tax_exemption ) {
1428 next if delete $cust_main_exemption{$taxname};
1430 my $cust_main_exemption = new FS::cust_main_exemption {
1431 'custnum' => $self->custnum,
1432 'taxname' => $taxname,
1434 my $error = $cust_main_exemption->insert;
1436 $dbh->rollback if $oldAutoCommit;
1437 return "inserting cust_main_exemption (transaction rolled back): $error";
1441 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1442 my $error = $cust_main_exemption->delete;
1444 $dbh->rollback if $oldAutoCommit;
1445 return "deleting cust_main_exemption (transaction rolled back): $error";
1451 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1452 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1453 # card/check/lec info has changed, want to retry realtime_ invoice events
1454 my $error = $self->retry_realtime;
1456 $dbh->rollback if $oldAutoCommit;
1461 unless ( $import || $skip_fuzzyfiles ) {
1462 $error = $self->queue_fuzzyfiles_update;
1464 $dbh->rollback if $oldAutoCommit;
1465 return "updating fuzzy search cache: $error";
1469 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1474 =item queue_fuzzyfiles_update
1476 Used by insert & replace to update the fuzzy search cache
1480 sub queue_fuzzyfiles_update {
1483 local $SIG{HUP} = 'IGNORE';
1484 local $SIG{INT} = 'IGNORE';
1485 local $SIG{QUIT} = 'IGNORE';
1486 local $SIG{TERM} = 'IGNORE';
1487 local $SIG{TSTP} = 'IGNORE';
1488 local $SIG{PIPE} = 'IGNORE';
1490 my $oldAutoCommit = $FS::UID::AutoCommit;
1491 local $FS::UID::AutoCommit = 0;
1494 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1495 my $error = $queue->insert( map $self->getfield($_),
1496 qw(first last company)
1499 $dbh->rollback if $oldAutoCommit;
1500 return "queueing job (transaction rolled back): $error";
1503 if ( $self->ship_last ) {
1504 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1505 $error = $queue->insert( map $self->getfield("ship_$_"),
1506 qw(first last company)
1509 $dbh->rollback if $oldAutoCommit;
1510 return "queueing job (transaction rolled back): $error";
1514 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1521 Checks all fields to make sure this is a valid customer record. If there is
1522 an error, returns the error, otherwise returns false. Called by the insert
1523 and replace methods.
1530 warn "$me check BEFORE: \n". $self->_dump
1534 $self->ut_numbern('custnum')
1535 || $self->ut_number('agentnum')
1536 || $self->ut_textn('agent_custid')
1537 || $self->ut_number('refnum')
1538 || $self->ut_textn('custbatch')
1539 || $self->ut_name('last')
1540 || $self->ut_name('first')
1541 || $self->ut_snumbern('birthdate')
1542 || $self->ut_snumbern('signupdate')
1543 || $self->ut_textn('company')
1544 || $self->ut_text('address1')
1545 || $self->ut_textn('address2')
1546 || $self->ut_text('city')
1547 || $self->ut_textn('county')
1548 || $self->ut_textn('state')
1549 || $self->ut_country('country')
1550 || $self->ut_anything('comments')
1551 || $self->ut_numbern('referral_custnum')
1552 || $self->ut_textn('stateid')
1553 || $self->ut_textn('stateid_state')
1554 || $self->ut_textn('invoice_terms')
1555 || $self->ut_alphan('geocode')
1556 || $self->ut_floatn('cdr_termination_percentage')
1559 #barf. need message catalogs. i18n. etc.
1560 $error .= "Please select an advertising source."
1561 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1562 return $error if $error;
1564 return "Unknown agent"
1565 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1567 return "Unknown refnum"
1568 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1570 return "Unknown referring custnum: ". $self->referral_custnum
1571 unless ! $self->referral_custnum
1572 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1574 if ( $self->censustract ne '' ) {
1575 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1576 or return "Illegal census tract: ". $self->censustract;
1578 $self->censustract("$1.$2");
1581 if ( $self->ss eq '' ) {
1586 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1587 or return "Illegal social security number: ". $self->ss;
1588 $self->ss("$1-$2-$3");
1592 # bad idea to disable, causes billing to fail because of no tax rates later
1593 # unless ( $import ) {
1594 unless ( qsearch('cust_main_county', {
1595 'country' => $self->country,
1598 return "Unknown state/county/country: ".
1599 $self->state. "/". $self->county. "/". $self->country
1600 unless qsearch('cust_main_county',{
1601 'state' => $self->state,
1602 'county' => $self->county,
1603 'country' => $self->country,
1609 $self->ut_phonen('daytime', $self->country)
1610 || $self->ut_phonen('night', $self->country)
1611 || $self->ut_phonen('fax', $self->country)
1612 || $self->ut_zip('zip', $self->country)
1614 return $error if $error;
1616 if ( $conf->exists('cust_main-require_phone')
1617 && ! length($self->daytime) && ! length($self->night)
1620 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1622 : FS::Msgcat::_gettext('daytime');
1623 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1625 : FS::Msgcat::_gettext('night');
1627 return "$daytime_label or $night_label is required"
1631 if ( $self->has_ship_address
1632 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1633 $self->addr_fields )
1637 $self->ut_name('ship_last')
1638 || $self->ut_name('ship_first')
1639 || $self->ut_textn('ship_company')
1640 || $self->ut_text('ship_address1')
1641 || $self->ut_textn('ship_address2')
1642 || $self->ut_text('ship_city')
1643 || $self->ut_textn('ship_county')
1644 || $self->ut_textn('ship_state')
1645 || $self->ut_country('ship_country')
1647 return $error if $error;
1649 #false laziness with above
1650 unless ( qsearchs('cust_main_county', {
1651 'country' => $self->ship_country,
1654 return "Unknown ship_state/ship_county/ship_country: ".
1655 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1656 unless qsearch('cust_main_county',{
1657 'state' => $self->ship_state,
1658 'county' => $self->ship_county,
1659 'country' => $self->ship_country,
1665 $self->ut_phonen('ship_daytime', $self->ship_country)
1666 || $self->ut_phonen('ship_night', $self->ship_country)
1667 || $self->ut_phonen('ship_fax', $self->ship_country)
1668 || $self->ut_zip('ship_zip', $self->ship_country)
1670 return $error if $error;
1672 return "Unit # is required."
1673 if $self->ship_address2 =~ /^\s*$/
1674 && $conf->exists('cust_main-require_address2');
1676 } else { # ship_ info eq billing info, so don't store dup info in database
1678 $self->setfield("ship_$_", '')
1679 foreach $self->addr_fields;
1681 return "Unit # is required."
1682 if $self->address2 =~ /^\s*$/
1683 && $conf->exists('cust_main-require_address2');
1687 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1688 # or return "Illegal payby: ". $self->payby;
1690 FS::payby->can_payby($self->table, $self->payby)
1691 or return "Illegal payby: ". $self->payby;
1693 $error = $self->ut_numbern('paystart_month')
1694 || $self->ut_numbern('paystart_year')
1695 || $self->ut_numbern('payissue')
1696 || $self->ut_textn('paytype')
1698 return $error if $error;
1700 if ( $self->payip eq '' ) {
1703 $error = $self->ut_ip('payip');
1704 return $error if $error;
1707 # If it is encrypted and the private key is not availaible then we can't
1708 # check the credit card.
1710 my $check_payinfo = 1;
1712 if ($self->is_encrypted($self->payinfo)) {
1716 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1718 my $payinfo = $self->payinfo;
1719 $payinfo =~ s/\D//g;
1720 $payinfo =~ /^(\d{13,16})$/
1721 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1723 $self->payinfo($payinfo);
1725 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1727 return gettext('unknown_card_type')
1728 if cardtype($self->payinfo) eq "Unknown";
1730 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1732 return 'Banned credit card: banned on '.
1733 time2str('%a %h %o at %r', $ban->_date).
1734 ' by '. $ban->otaker.
1735 ' (ban# '. $ban->bannum. ')';
1738 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1739 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1740 $self->paycvv =~ /^(\d{4})$/
1741 or return "CVV2 (CID) for American Express cards is four digits.";
1744 $self->paycvv =~ /^(\d{3})$/
1745 or return "CVV2 (CVC2/CID) is three digits.";
1752 my $cardtype = cardtype($payinfo);
1753 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1755 return "Start date or issue number is required for $cardtype cards"
1756 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1758 return "Start month must be between 1 and 12"
1759 if $self->paystart_month
1760 and $self->paystart_month < 1 || $self->paystart_month > 12;
1762 return "Start year must be 1990 or later"
1763 if $self->paystart_year
1764 and $self->paystart_year < 1990;
1766 return "Issue number must be beween 1 and 99"
1768 and $self->payissue < 1 || $self->payissue > 99;
1771 $self->paystart_month('');
1772 $self->paystart_year('');
1773 $self->payissue('');
1776 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1778 my $payinfo = $self->payinfo;
1779 $payinfo =~ s/[^\d\@]//g;
1780 if ( $conf->exists('echeck-nonus') ) {
1781 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1782 $payinfo = "$1\@$2";
1784 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1785 $payinfo = "$1\@$2";
1787 $self->payinfo($payinfo);
1790 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1792 return 'Banned ACH account: banned on '.
1793 time2str('%a %h %o at %r', $ban->_date).
1794 ' by '. $ban->otaker.
1795 ' (ban# '. $ban->bannum. ')';
1798 } elsif ( $self->payby eq 'LECB' ) {
1800 my $payinfo = $self->payinfo;
1801 $payinfo =~ s/\D//g;
1802 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1804 $self->payinfo($payinfo);
1807 } elsif ( $self->payby eq 'BILL' ) {
1809 $error = $self->ut_textn('payinfo');
1810 return "Illegal P.O. number: ". $self->payinfo if $error;
1813 } elsif ( $self->payby eq 'COMP' ) {
1815 my $curuser = $FS::CurrentUser::CurrentUser;
1816 if ( ! $self->custnum
1817 && ! $curuser->access_right('Complimentary customer')
1820 return "You are not permitted to create complimentary accounts."
1823 $error = $self->ut_textn('payinfo');
1824 return "Illegal comp account issuer: ". $self->payinfo if $error;
1827 } elsif ( $self->payby eq 'PREPAY' ) {
1829 my $payinfo = $self->payinfo;
1830 $payinfo =~ s/\W//g; #anything else would just confuse things
1831 $self->payinfo($payinfo);
1832 $error = $self->ut_alpha('payinfo');
1833 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1834 return "Unknown prepayment identifier"
1835 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1840 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1841 return "Expiration date required"
1842 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1846 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1847 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1848 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1849 ( $m, $y ) = ( $2, "19$1" );
1850 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1851 ( $m, $y ) = ( $3, "20$2" );
1853 return "Illegal expiration date: ". $self->paydate;
1855 $self->paydate("$y-$m-01");
1856 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1857 return gettext('expired_card')
1859 && !$ignore_expired_card
1860 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1863 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1864 ( ! $conf->exists('require_cardname')
1865 || $self->payby !~ /^(CARD|DCRD)$/ )
1867 $self->payname( $self->first. " ". $self->getfield('last') );
1869 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1870 or return gettext('illegal_name'). " payname: ". $self->payname;
1874 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1875 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1879 $self->otaker(getotaker) unless $self->otaker;
1881 warn "$me check AFTER: \n". $self->_dump
1884 $self->SUPER::check;
1889 Returns a list of fields which have ship_ duplicates.
1894 qw( last first company
1895 address1 address2 city county state zip country
1900 =item has_ship_address
1902 Returns true if this customer record has a separate shipping address.
1906 sub has_ship_address {
1908 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1911 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
1913 Returns all packages (see L<FS::cust_pkg>) for this customer.
1919 my $extra_qsearch = ref($_[0]) ? shift : {};
1921 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
1924 if ( $self->{'_pkgnum'} ) {
1925 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1927 @cust_pkg = $self->_cust_pkg($extra_qsearch);
1930 sort sort_packages @cust_pkg;
1935 Synonym for B<all_pkgs>.
1940 shift->all_pkgs(@_);
1945 Returns all locations (see L<FS::cust_location>) for this customer.
1951 qsearch('cust_location', { 'custnum' => $self->custnum } );
1954 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
1956 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1960 sub ncancelled_pkgs {
1962 my $extra_qsearch = ref($_[0]) ? shift : {};
1964 return $self->num_ncancelled_pkgs unless wantarray;
1967 if ( $self->{'_pkgnum'} ) {
1969 warn "$me ncancelled_pkgs: returning cached objects"
1972 @cust_pkg = grep { ! $_->getfield('cancel') }
1973 values %{ $self->{'_pkgnum'}->cache };
1977 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1978 $self->custnum. "\n"
1981 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
1983 @cust_pkg = $self->_cust_pkg($extra_qsearch);
1987 sort sort_packages @cust_pkg;
1993 my $extra_qsearch = ref($_[0]) ? shift : {};
1995 $extra_qsearch->{'select'} ||= '*';
1996 $extra_qsearch->{'select'} .=
1997 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2001 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2006 'table' => 'cust_pkg',
2007 'hashref' => { 'custnum' => $self->custnum },
2012 # This should be generalized to use config options to determine order.
2015 if ( $a->get('cancel') xor $b->get('cancel') ) {
2016 return -1 if $b->get('cancel');
2017 return 1 if $a->get('cancel');
2018 #shouldn't get here...
2021 my $a_num_cust_svc = $a->num_cust_svc;
2022 my $b_num_cust_svc = $b->num_cust_svc;
2023 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2024 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2025 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2026 my @a_cust_svc = $a->cust_svc;
2027 my @b_cust_svc = $b->cust_svc;
2028 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2033 =item suspended_pkgs
2035 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2039 sub suspended_pkgs {
2041 grep { $_->susp } $self->ncancelled_pkgs;
2044 =item unflagged_suspended_pkgs
2046 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2047 customer (thouse packages without the `manual_flag' set).
2051 sub unflagged_suspended_pkgs {
2053 return $self->suspended_pkgs
2054 unless dbdef->table('cust_pkg')->column('manual_flag');
2055 grep { ! $_->manual_flag } $self->suspended_pkgs;
2058 =item unsuspended_pkgs
2060 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2065 sub unsuspended_pkgs {
2067 grep { ! $_->susp } $self->ncancelled_pkgs;
2070 =item next_bill_date
2072 Returns the next date this customer will be billed, as a UNIX timestamp, or
2073 undef if no active package has a next bill date.
2077 sub next_bill_date {
2079 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2082 =item num_cancelled_pkgs
2084 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2089 sub num_cancelled_pkgs {
2090 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2093 sub num_ncancelled_pkgs {
2094 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2098 my( $self ) = shift;
2099 my $sql = scalar(@_) ? shift : '';
2100 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2101 my $sth = dbh->prepare(
2102 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2103 ) or die dbh->errstr;
2104 $sth->execute($self->custnum) or die $sth->errstr;
2105 $sth->fetchrow_arrayref->[0];
2110 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2111 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2112 on success or a list of errors.
2118 grep { $_->unsuspend } $self->suspended_pkgs;
2123 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2125 Returns a list: an empty list on success or a list of errors.
2131 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2134 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2136 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2137 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2138 of a list of pkgparts; the hashref has the following keys:
2142 =item pkgparts - listref of pkgparts
2144 =item (other options are passed to the suspend method)
2149 Returns a list: an empty list on success or a list of errors.
2153 sub suspend_if_pkgpart {
2155 my (@pkgparts, %opt);
2156 if (ref($_[0]) eq 'HASH'){
2157 @pkgparts = @{$_[0]{pkgparts}};
2162 grep { $_->suspend(%opt) }
2163 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2164 $self->unsuspended_pkgs;
2167 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2169 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2170 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2171 instead of a list of pkgparts; the hashref has the following keys:
2175 =item pkgparts - listref of pkgparts
2177 =item (other options are passed to the suspend method)
2181 Returns a list: an empty list on success or a list of errors.
2185 sub suspend_unless_pkgpart {
2187 my (@pkgparts, %opt);
2188 if (ref($_[0]) eq 'HASH'){
2189 @pkgparts = @{$_[0]{pkgparts}};
2194 grep { $_->suspend(%opt) }
2195 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2196 $self->unsuspended_pkgs;
2199 =item cancel [ OPTION => VALUE ... ]
2201 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2203 Available options are:
2207 =item quiet - can be set true to supress email cancellation notices.
2209 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
2211 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2213 =item nobill - can be set true to skip billing if it might otherwise be done.
2217 Always returns a list: an empty list on success or a list of errors.
2221 # nb that dates are not specified as valid options to this method
2224 my( $self, %opt ) = @_;
2226 warn "$me cancel called on customer ". $self->custnum. " with options ".
2227 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2230 return ( 'access denied' )
2231 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2233 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2235 #should try decryption (we might have the private key)
2236 # and if not maybe queue a job for the server that does?
2237 return ( "Can't (yet) ban encrypted credit cards" )
2238 if $self->is_encrypted($self->payinfo);
2240 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2241 my $error = $ban->insert;
2242 return ( $error ) if $error;
2246 my @pkgs = $self->ncancelled_pkgs;
2248 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2250 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2251 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2255 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2256 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2259 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2262 sub _banned_pay_hashref {
2273 'payby' => $payby2ban{$self->payby},
2274 'payinfo' => md5_base64($self->payinfo),
2275 #don't ever *search* on reason! #'reason' =>
2281 Returns all notes (see L<FS::cust_main_note>) for this customer.
2288 qsearch( 'cust_main_note',
2289 { 'custnum' => $self->custnum },
2291 'ORDER BY _DATE DESC'
2297 Returns the agent (see L<FS::agent>) for this customer.
2303 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2306 =item bill_and_collect
2308 Cancels and suspends any packages due, generates bills, applies payments and
2311 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
2313 Options are passed as name-value pairs. Currently available options are:
2319 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
2323 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2327 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
2331 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2335 If set true, re-charges setup fees.
2339 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2343 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2344 options of those methods are also available.
2348 sub bill_and_collect {
2349 my( $self, %options ) = @_;
2351 #$options{actual_time} not $options{time} because freeside-daily -d is for
2352 #pre-printing invoices
2353 $self->cancel_expired_pkgs( $options{actual_time} );
2354 $self->suspend_adjourned_pkgs( $options{actual_time} );
2356 my $error = $self->bill( %options );
2357 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
2359 $self->apply_payments_and_credits;
2361 unless ( $conf->exists('cancelled_cust-noevents')
2362 && ! $self->num_ncancelled_pkgs
2365 $error = $self->collect( %options );
2366 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2372 sub cancel_expired_pkgs {
2373 my ( $self, $time ) = @_;
2375 my @cancel_pkgs = $self->ncancelled_pkgs( {
2376 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2379 foreach my $cust_pkg ( @cancel_pkgs ) {
2380 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2381 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2382 'reason_otaker' => $cpr->otaker
2386 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
2387 " for custnum ". $self->custnum. ": $error"
2393 sub suspend_adjourned_pkgs {
2394 my ( $self, $time ) = @_;
2396 my @susp_pkgs = $self->ncancelled_pkgs( {
2398 " AND ( susp IS NULL OR susp = 0 )
2399 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
2400 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2405 #only because there's no SQL test for is_prepaid :/
2407 grep { ( $_->part_pkg->is_prepaid
2412 && $_->adjourn <= $time
2418 foreach my $cust_pkg ( @susp_pkgs ) {
2419 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2420 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2421 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2422 'reason_otaker' => $cpr->otaker
2427 warn "Error suspending package ". $cust_pkg->pkgnum.
2428 " for custnum ". $self->custnum. ": $error"
2436 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2437 conjunction with the collect method by calling B<bill_and_collect>.
2439 If there is an error, returns the error, otherwise returns false.
2441 Options are passed as name-value pairs. Currently available options are:
2447 If set true, re-charges setup fees.
2451 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
2455 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2459 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2461 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2465 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2469 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
2473 This boolean value informs the us that the package is being cancelled. This
2474 typically might mean not charging the normal recurring fee but only usage
2475 fees since the last billing. Setup charges may be charged. Not all package
2476 plans support this feature (they tend to charge 0).
2480 Options terms to be printed on this invocice. Otherwise, customer-specific
2481 terms or the default terms are used.
2488 my( $self, %options ) = @_;
2489 return '' if $self->payby eq 'COMP';
2490 warn "$me bill customer ". $self->custnum. "\n"
2493 my $time = $options{'time'} || time;
2494 my $invoice_time = $options{'invoice_time'} || $time;
2496 $options{'not_pkgpart'} ||= {};
2497 $options{'not_pkgpart'} = { map { $_ => 1 }
2498 split(/\s*,\s*/, $options{'not_pkgpart'})
2500 unless ref($options{'not_pkgpart'});
2502 local $SIG{HUP} = 'IGNORE';
2503 local $SIG{INT} = 'IGNORE';
2504 local $SIG{QUIT} = 'IGNORE';
2505 local $SIG{TERM} = 'IGNORE';
2506 local $SIG{TSTP} = 'IGNORE';
2507 local $SIG{PIPE} = 'IGNORE';
2509 my $oldAutoCommit = $FS::UID::AutoCommit;
2510 local $FS::UID::AutoCommit = 0;
2513 $self->select_for_update; #mutex
2515 my $error = $self->do_cust_event(
2516 'debug' => ( $options{'debug'} || 0 ),
2517 'time' => $invoice_time,
2518 'check_freq' => $options{'check_freq'},
2519 'stage' => 'pre-bill',
2522 $dbh->rollback if $oldAutoCommit;
2526 my @cust_bill_pkg = ();
2529 # find the packages which are due for billing, find out how much they are
2530 # & generate invoice database.
2533 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2535 my @precommit_hooks = ();
2537 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
2538 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2540 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2542 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2544 #? to avoid use of uninitialized value errors... ?
2545 $cust_pkg->setfield('bill', '')
2546 unless defined($cust_pkg->bill);
2548 #my $part_pkg = $cust_pkg->part_pkg;
2550 my $real_pkgpart = $cust_pkg->pkgpart;
2551 my %hash = $cust_pkg->hash;
2553 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2555 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2558 $self->_make_lines( 'part_pkg' => $part_pkg,
2559 'cust_pkg' => $cust_pkg,
2560 'precommit_hooks' => \@precommit_hooks,
2561 'line_items' => \@cust_bill_pkg,
2562 'setup' => \$total_setup,
2563 'recur' => \$total_recur,
2564 'tax_matrix' => \%taxlisthash,
2566 'real_pkgpart' => $real_pkgpart,
2567 'options' => \%options,
2570 $dbh->rollback if $oldAutoCommit;
2574 } #foreach my $part_pkg
2576 } #foreach my $cust_pkg
2578 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2579 #but do commit any package date cycling that happened
2580 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2584 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2585 !$conf->exists('postal_invoice-recurring_only')
2589 my $postal_pkg = $self->charge_postal_fee();
2590 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2592 $dbh->rollback if $oldAutoCommit;
2593 return "can't charge postal invoice fee for customer ".
2594 $self->custnum. ": $postal_pkg";
2596 } elsif ( $postal_pkg ) {
2598 my $real_pkgpart = $postal_pkg->pkgpart;
2599 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2600 my %postal_options = %options;
2601 delete $postal_options{cancel};
2603 $self->_make_lines( 'part_pkg' => $part_pkg,
2604 'cust_pkg' => $postal_pkg,
2605 'precommit_hooks' => \@precommit_hooks,
2606 'line_items' => \@cust_bill_pkg,
2607 'setup' => \$total_setup,
2608 'recur' => \$total_recur,
2609 'tax_matrix' => \%taxlisthash,
2611 'real_pkgpart' => $real_pkgpart,
2612 'options' => \%postal_options,
2615 $dbh->rollback if $oldAutoCommit;
2624 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2626 # keys are tax names (as printed on invoices / itemdesc )
2627 # values are listrefs of taxlisthash keys (internal identifiers)
2630 # keys are taxlisthash keys (internal identifiers)
2631 # values are (cumulative) amounts
2634 # keys are taxlisthash keys (internal identifiers)
2635 # values are listrefs of cust_bill_pkg_tax_location hashrefs
2636 my %tax_location = ();
2638 # keys are taxlisthash keys (internal identifiers)
2639 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
2640 my %tax_rate_location = ();
2642 foreach my $tax ( keys %taxlisthash ) {
2643 my $tax_object = shift @{ $taxlisthash{$tax} };
2644 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2645 warn " ". join('/', @{ $taxlisthash{$tax} } ). "\n" if $DEBUG > 2;
2646 my $hashref_or_error =
2647 $tax_object->taxline( $taxlisthash{$tax},
2648 'custnum' => $self->custnum,
2649 'invoice_time' => $invoice_time
2651 unless ( ref($hashref_or_error) ) {
2652 $dbh->rollback if $oldAutoCommit;
2653 return $hashref_or_error;
2655 unshift @{ $taxlisthash{$tax} }, $tax_object;
2657 my $name = $hashref_or_error->{'name'};
2658 my $amount = $hashref_or_error->{'amount'};
2660 #warn "adding $amount as $name\n";
2661 $taxname{ $name } ||= [];
2662 push @{ $taxname{ $name } }, $tax;
2664 $tax{ $tax } += $amount;
2666 $tax_location{ $tax } ||= [];
2667 if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
2668 push @{ $tax_location{ $tax } },
2670 'taxnum' => $tax_object->taxnum,
2671 'taxtype' => ref($tax_object),
2672 'pkgnum' => $tax_object->get('pkgnum'),
2673 'locationnum' => $tax_object->get('locationnum'),
2674 'amount' => sprintf('%.2f', $amount ),
2678 $tax_rate_location{ $tax } ||= [];
2679 if ( ref($tax_object) eq 'FS::tax_rate' ) {
2680 my $taxratelocationnum =
2681 $tax_object->tax_rate_location->taxratelocationnum;
2682 push @{ $tax_rate_location{ $tax } },
2684 'taxnum' => $tax_object->taxnum,
2685 'taxtype' => ref($tax_object),
2686 'amount' => sprintf('%.2f', $amount ),
2687 'locationtaxid' => $tax_object->location,
2688 'taxratelocationnum' => $taxratelocationnum,
2694 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
2695 my %packagemap = map { $_->pkgnum => $_ } @cust_bill_pkg;
2696 foreach my $tax ( keys %taxlisthash ) {
2697 foreach ( @{ $taxlisthash{$tax} }[1 ... scalar(@{ $taxlisthash{$tax} })] ) {
2698 next unless ref($_) eq 'FS::cust_bill_pkg';
2700 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
2701 splice( @{ $_->_cust_tax_exempt_pkg } );
2705 #consolidate and create tax line items
2706 warn "consolidating and generating...\n" if $DEBUG > 2;
2707 foreach my $taxname ( keys %taxname ) {
2710 my @cust_bill_pkg_tax_location = ();
2711 my @cust_bill_pkg_tax_rate_location = ();
2712 warn "adding $taxname\n" if $DEBUG > 1;
2713 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2714 next if $seen{$taxitem}++;
2715 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2716 $tax += $tax{$taxitem};
2717 push @cust_bill_pkg_tax_location,
2718 map { new FS::cust_bill_pkg_tax_location $_ }
2719 @{ $tax_location{ $taxitem } };
2720 push @cust_bill_pkg_tax_rate_location,
2721 map { new FS::cust_bill_pkg_tax_rate_location $_ }
2722 @{ $tax_rate_location{ $taxitem } };
2726 $tax = sprintf('%.2f', $tax );
2727 $total_setup = sprintf('%.2f', $total_setup+$tax );
2729 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
2735 if ( $pkg_category and
2736 $conf->config('invoice_latexsummary') ||
2737 $conf->config('invoice_htmlsummary')
2741 my %hash = ( 'section' => $pkg_category->categoryname );
2742 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
2746 push @cust_bill_pkg, new FS::cust_bill_pkg {
2752 'itemdesc' => $taxname,
2753 'display' => \@display,
2754 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
2755 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
2760 #add tax adjustments
2761 warn "adding tax adjustments...\n" if $DEBUG > 2;
2762 foreach my $cust_tax_adjustment (
2763 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
2769 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
2770 $total_setup = sprintf('%.2f', $total_setup+$tax );
2772 my $itemdesc = $cust_tax_adjustment->taxname;
2773 $itemdesc = '' if $itemdesc eq 'Tax';
2775 push @cust_bill_pkg, new FS::cust_bill_pkg {
2781 'itemdesc' => $itemdesc,
2782 'itemcomment' => $cust_tax_adjustment->comment,
2783 'cust_tax_adjustment' => $cust_tax_adjustment,
2784 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
2789 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2791 my @cust_bill = $self->cust_bill;
2792 my $balance = $self->balance;
2793 my $previous_balance = scalar(@cust_bill)
2794 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
2797 $previous_balance += $cust_bill[$#cust_bill]->charged
2798 if scalar(@cust_bill);
2799 #my $balance_adjustments =
2800 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
2802 #create the new invoice
2803 my $cust_bill = new FS::cust_bill ( {
2804 'custnum' => $self->custnum,
2805 '_date' => ( $invoice_time ),
2806 'charged' => $charged,
2807 'billing_balance' => $balance,
2808 'previous_balance' => $previous_balance,
2809 'invoice_terms' => $options{'invoice_terms'},
2811 $error = $cust_bill->insert;
2813 $dbh->rollback if $oldAutoCommit;
2814 return "can't create invoice for customer #". $self->custnum. ": $error";
2817 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2818 $cust_bill_pkg->invnum($cust_bill->invnum);
2819 my $error = $cust_bill_pkg->insert;
2821 $dbh->rollback if $oldAutoCommit;
2822 return "can't create invoice line item: $error";
2827 foreach my $hook ( @precommit_hooks ) {
2829 &{$hook}; #($self) ?
2832 $dbh->rollback if $oldAutoCommit;
2833 return "$@ running precommit hook $hook\n";
2837 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2843 my ($self, %params) = @_;
2845 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2846 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2847 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2848 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2849 my $total_setup = $params{setup} or die "no setup accumulator specified";
2850 my $total_recur = $params{recur} or die "no recur accumulator specified";
2851 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2852 my $time = $params{'time'} or die "no time specified";
2853 my (%options) = %{$params{options}};
2856 my $real_pkgpart = $params{real_pkgpart};
2857 my %hash = $cust_pkg->hash;
2858 my $old_cust_pkg = new FS::cust_pkg \%hash;
2864 $cust_pkg->pkgpart($part_pkg->pkgpart);
2872 if ( $options{'resetup'}
2873 || ( ! $cust_pkg->setup
2874 && ( ! $cust_pkg->start_date
2875 || $cust_pkg->start_date <= $time
2877 && ( ! $conf->exists('disable_setup_suspended_pkgs')
2878 || ( $conf->exists('disable_setup_suspended_pkgs') &&
2879 ! $cust_pkg->getfield('susp')
2886 warn " bill setup\n" if $DEBUG > 1;
2889 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2890 return "$@ running calc_setup for $cust_pkg\n"
2893 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2895 $cust_pkg->setfield('setup', $time)
2896 unless $cust_pkg->setup;
2897 #do need it, but it won't get written to the db
2898 #|| $cust_pkg->pkgpart != $real_pkgpart;
2900 $cust_pkg->setfield('start_date', '')
2901 if $cust_pkg->start_date;
2906 # bill recurring fee
2909 #XXX unit stuff here too
2913 if ( ! $cust_pkg->get('susp')
2914 and ! $cust_pkg->get('start_date')
2915 and ( $part_pkg->getfield('freq') ne '0'
2916 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
2918 || ( $part_pkg->plan eq 'voip_cdr'
2919 && $part_pkg->option('bill_every_call')
2921 || ( $options{cancel} )
2924 # XXX should this be a package event? probably. events are called
2925 # at collection time at the moment, though...
2926 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2927 if $part_pkg->can('reset_usage');
2928 #don't want to reset usage just cause we want a line item??
2929 #&& $part_pkg->pkgpart == $real_pkgpart;
2931 warn " bill recur\n" if $DEBUG > 1;
2934 # XXX shared with $recur_prog
2935 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
2939 #over two params! lets at least switch to a hashref for the rest...
2940 my $increment_next_bill = ( $part_pkg->freq ne '0'
2941 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
2942 && !$options{cancel}
2944 my %param = ( 'precommit_hooks' => $precommit_hooks,
2945 'increment_next_bill' => $increment_next_bill,
2948 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
2949 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
2950 return "$@ running $method for $cust_pkg\n"
2953 if ( $increment_next_bill ) {
2955 my $next_bill = $part_pkg->add_freq($sdate);
2956 return "unparsable frequency: ". $part_pkg->freq
2957 if $next_bill == -1;
2959 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
2960 # only for figuring next bill date, nothing else, so, reset $sdate again
2962 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2963 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2964 $cust_pkg->last_bill($sdate);
2966 $cust_pkg->setfield('bill', $next_bill );
2972 warn "\$setup is undefined" unless defined($setup);
2973 warn "\$recur is undefined" unless defined($recur);
2974 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2977 # If there's line items, create em cust_bill_pkg records
2978 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2983 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2984 # hmm.. and if just the options are modified in some weird price plan?
2986 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2989 my $error = $cust_pkg->replace( $old_cust_pkg,
2990 'options' => { $cust_pkg->options },
2992 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2993 if $error; #just in case
2996 $setup = sprintf( "%.2f", $setup );
2997 $recur = sprintf( "%.2f", $recur );
2998 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2999 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3001 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3002 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3005 if ( $setup != 0 || $recur != 0 ) {
3007 warn " charges (setup=$setup, recur=$recur); adding line items\n"
3010 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3012 warn " adding customer package invoice detail: $_\n"
3013 foreach @cust_pkg_detail;
3015 push @details, @cust_pkg_detail;
3017 my $cust_bill_pkg = new FS::cust_bill_pkg {
3018 'pkgnum' => $cust_pkg->pkgnum,
3020 'unitsetup' => $unitsetup,
3022 'unitrecur' => $unitrecur,
3023 'quantity' => $cust_pkg->quantity,
3024 'details' => \@details,
3025 'hidden' => $part_pkg->hidden,
3028 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3029 $cust_bill_pkg->sdate( $hash{last_bill} );
3030 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
3031 $cust_bill_pkg->edate( $time ) if $options{cancel};
3032 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3033 $cust_bill_pkg->sdate( $sdate );
3034 $cust_bill_pkg->edate( $cust_pkg->bill );
3035 #$cust_bill_pkg->edate( $time ) if $options{cancel};
3038 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3039 unless $part_pkg->pkgpart == $real_pkgpart;
3041 $$total_setup += $setup;
3042 $$total_recur += $recur;
3049 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3050 return $error if $error;
3052 push @$cust_bill_pkgs, $cust_bill_pkg;
3054 } #if $setup != 0 || $recur != 0
3064 my $part_pkg = shift;
3065 my $taxlisthash = shift;
3066 my $cust_bill_pkg = shift;
3067 my $cust_pkg = shift;
3068 my $invoice_time = shift;
3069 my $real_pkgpart = shift;
3070 my $options = shift;
3072 my %cust_bill_pkg = ();
3076 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3077 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3078 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3079 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3081 if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3083 if ( $conf->exists('enable_taxproducts')
3084 && ( scalar($part_pkg->part_pkg_taxoverride)
3085 || $part_pkg->has_taxproduct
3090 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3091 return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3094 foreach my $class (@classes) {
3095 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3096 return $err_or_ref unless ref($err_or_ref);
3097 $taxes{$class} = $err_or_ref;
3100 unless (exists $taxes{''}) {
3101 my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3102 return $err_or_ref unless ref($err_or_ref);
3103 $taxes{''} = $err_or_ref;
3108 my @loc_keys = qw( state county country );
3110 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3111 my $cust_location = $cust_pkg->cust_location;
3112 %taxhash = map { $_ => $cust_location->$_() } @loc_keys;
3115 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3118 %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3121 $taxhash{'taxclass'} = $part_pkg->taxclass;
3123 my @taxes = qsearch( 'cust_main_county', \%taxhash );
3125 my %taxhash_elim = %taxhash;
3127 my @elim = qw( taxclass county state );
3128 while ( !scalar(@taxes) && scalar(@elim) ) {
3129 $taxhash_elim{ shift(@elim) } = '';
3130 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3133 @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3135 if $self->cust_main_exemption; #just to be safe
3137 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3139 $_->set('pkgnum', $cust_pkg->pkgnum );
3140 $_->set('locationnum', $cust_pkg->locationnum );
3144 $taxes{''} = [ @taxes ];
3145 $taxes{'setup'} = [ @taxes ];
3146 $taxes{'recur'} = [ @taxes ];
3147 $taxes{$_} = [ @taxes ] foreach (@classes);
3149 # # maybe eliminate this entirely, along with all the 0% records
3150 # unless ( @taxes ) {
3152 # "fatal: can't find tax rate for state/county/country/taxclass ".
3153 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
3156 } #if $conf->exists('enable_taxproducts') ...
3161 my $separate = $conf->exists('separate_usage');
3162 my $usage_mandate = $cust_pkg->part_pkg->option('usage_mandate', 'Hush!');
3163 if ( $separate || $cust_bill_pkg->hidden || $usage_mandate ) {
3165 my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3166 my %hash = $cust_bill_pkg->hidden # maybe for all bill linked?
3167 ? ( 'section' => $temp_pkg->part_pkg->categoryname )
3170 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
3171 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
3173 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3174 push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3176 push @display, new FS::cust_bill_pkg_display
3179 ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3183 if ($separate && $section && $summary) {
3184 push @display, new FS::cust_bill_pkg_display { type => 'U',
3189 if ($usage_mandate || $section && $summary) {
3190 $hash{post_total} = 'Y';
3193 $hash{section} = $section if ($separate || $usage_mandate);
3194 push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3197 $cust_bill_pkg->set('display', \@display);
3199 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3200 foreach my $key (keys %tax_cust_bill_pkg) {
3201 my @taxes = @{ $taxes{$key} || [] };
3202 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3204 my %localtaxlisthash = ();
3205 foreach my $tax ( @taxes ) {
3207 my $taxname = ref( $tax ). ' '. $tax->taxnum;
3208 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3209 # ' locationnum'. $cust_pkg->locationnum
3210 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3212 $taxlisthash->{ $taxname } ||= [ $tax ];
3213 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
3215 $localtaxlisthash{ $taxname } ||= [ $tax ];
3216 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
3220 warn "finding taxed taxes...\n" if $DEBUG > 2;
3221 foreach my $tax ( keys %localtaxlisthash ) {
3222 my $tax_object = shift @{ $localtaxlisthash{$tax} };
3223 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3225 next unless $tax_object->can('tax_on_tax');
3227 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3228 my $totname = ref( $tot ). ' '. $tot->taxnum;
3230 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3232 next unless exists( $localtaxlisthash{ $totname } ); # only increase
3234 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3235 my $hashref_or_error =
3236 $tax_object->taxline( $localtaxlisthash{$tax},
3237 'custnum' => $self->custnum,
3238 'invoice_time' => $invoice_time,
3240 return $hashref_or_error
3241 unless ref($hashref_or_error);
3243 $taxlisthash->{ $totname } ||= [ $tot ];
3244 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
3256 my $part_pkg = shift;
3260 my $geocode = $self->geocode('cch');
3262 my @taxclassnums = map { $_->taxclassnum }
3263 $part_pkg->part_pkg_taxoverride($class);
3265 unless (@taxclassnums) {
3266 @taxclassnums = map { $_->taxclassnum }
3267 grep { $_->taxable eq 'Y' }
3268 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3270 warn "Found taxclassnum values of ". join(',', @taxclassnums)
3275 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3277 @taxes = qsearch({ 'table' => 'tax_rate',
3278 'hashref' => { 'geocode' => $geocode, },
3279 'extra_sql' => $extra_sql,
3281 if scalar(@taxclassnums);
3283 warn "Found taxes ".
3284 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
3291 =item collect [ HASHREF | OPTION => VALUE ... ]
3293 (Attempt to) collect money for this customer's outstanding invoices (see
3294 L<FS::cust_bill>). Usually used after the bill method.
3296 Actions are now triggered by billing events; see L<FS::part_event> and the
3297 billing events web interface. Old-style invoice events (see
3298 L<FS::part_bill_event>) have been deprecated.
3300 If there is an error, returns the error, otherwise returns false.
3302 Options are passed as name-value pairs.
3304 Currently available options are:
3310 Use this time when deciding when to print invoices and late notices on those invoices. The default is now. It is specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions.
3314 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3318 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3322 set true to surpress email card/ACH decline notices.
3326 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
3332 # allows for one time override of normal customer billing method
3337 my( $self, %options ) = @_;
3338 my $invoice_time = $options{'invoice_time'} || time;
3341 local $SIG{HUP} = 'IGNORE';
3342 local $SIG{INT} = 'IGNORE';
3343 local $SIG{QUIT} = 'IGNORE';
3344 local $SIG{TERM} = 'IGNORE';
3345 local $SIG{TSTP} = 'IGNORE';
3346 local $SIG{PIPE} = 'IGNORE';
3348 my $oldAutoCommit = $FS::UID::AutoCommit;
3349 local $FS::UID::AutoCommit = 0;
3352 $self->select_for_update; #mutex
3355 my $balance = $self->balance;
3356 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3359 if ( exists($options{'retry_card'}) ) {
3360 carp 'retry_card option passed to collect is deprecated; use retry';
3361 $options{'retry'} ||= $options{'retry_card'};
3363 if ( exists($options{'retry'}) && $options{'retry'} ) {
3364 my $error = $self->retry_realtime;
3366 $dbh->rollback if $oldAutoCommit;
3371 my $error = $self->do_cust_event(
3372 'debug' => ( $options{'debug'} || 0 ),
3373 'time' => $invoice_time,
3374 'check_freq' => $options{'check_freq'},
3375 'stage' => 'collect',
3378 $dbh->rollback if $oldAutoCommit;
3382 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3387 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3389 Runs billing events; see L<FS::part_event> and the billing events web
3392 If there is an error, returns the error, otherwise returns false.
3394 Options are passed as name-value pairs.
3396 Currently available options are:
3402 Use this time when deciding when to print invoices and late notices on those invoices. The default is now. It is specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions.
3406 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3410 "collect" (the default) or "pre-bill"
3414 set true to surpress email card/ACH decline notices.
3418 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
3424 # allows for one time override of normal customer billing method
3428 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3431 my( $self, %options ) = @_;
3432 my $time = $options{'time'} || time;
3435 local $SIG{HUP} = 'IGNORE';
3436 local $SIG{INT} = 'IGNORE';
3437 local $SIG{QUIT} = 'IGNORE';
3438 local $SIG{TERM} = 'IGNORE';
3439 local $SIG{TSTP} = 'IGNORE';
3440 local $SIG{PIPE} = 'IGNORE';
3442 my $oldAutoCommit = $FS::UID::AutoCommit;
3443 local $FS::UID::AutoCommit = 0;
3446 $self->select_for_update; #mutex
3449 my $balance = $self->balance;
3450 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
3453 # if ( exists($options{'retry_card'}) ) {
3454 # carp 'retry_card option passed to collect is deprecated; use retry';
3455 # $options{'retry'} ||= $options{'retry_card'};
3457 # if ( exists($options{'retry'}) && $options{'retry'} ) {
3458 # my $error = $self->retry_realtime;
3460 # $dbh->rollback if $oldAutoCommit;
3465 # false laziness w/pay_batch::import_results
3467 my $due_cust_event = $self->due_cust_event(
3468 'debug' => ( $options{'debug'} || 0 ),
3470 'check_freq' => $options{'check_freq'},
3471 'stage' => ( $options{'stage'} || 'collect' ),
3473 unless( ref($due_cust_event) ) {
3474 $dbh->rollback if $oldAutoCommit;
3475 return $due_cust_event;
3478 foreach my $cust_event ( @$due_cust_event ) {
3482 #re-eval event conditions (a previous event could have changed things)
3483 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
3484 #don't leave stray "new/locked" records around
3485 my $error = $cust_event->delete;
3487 #gah, even with transactions
3488 $dbh->commit if $oldAutoCommit; #well.
3495 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
3496 warn " running cust_event ". $cust_event->eventnum. "\n"
3500 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
3501 if ( my $error = $cust_event->do_event() ) {
3502 #XXX wtf is this? figure out a proper dealio with return value
3504 # gah, even with transactions.
3505 $dbh->commit if $oldAutoCommit; #well.
3512 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3517 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
3519 Inserts database records for and returns an ordered listref of new events due
3520 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
3521 events are due, an empty listref is returned. If there is an error, returns a
3522 scalar error message.
3524 To actually run the events, call each event's test_condition method, and if
3525 still true, call the event's do_event method.
3527 Options are passed as a hashref or as a list of name-value pairs. Available
3534 Search only for events of this check frequency (how often events of this type are checked); currently "1d" (daily, the default) and "1m" (monthly) are recognized.
3538 "collect" (the default) or "pre-bill"
3542 "Current time" for the events.
3546 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
3550 Only return events for the specified eventtable (by default, events of all eventtables are returned)
3554 Explicitly pass the objects to be tested (typically used with eventtable).
3558 Set to true to return the objects, but not actually insert them into the
3565 sub due_cust_event {
3567 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
3570 #my $DEBUG = $opt{'debug'}
3571 local($DEBUG) = $opt{'debug'}
3572 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
3574 warn "$me due_cust_event called with options ".
3575 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
3578 $opt{'time'} ||= time;
3580 local $SIG{HUP} = 'IGNORE';
3581 local $SIG{INT} = 'IGNORE';
3582 local $SIG{QUIT} = 'IGNORE';
3583 local $SIG{TERM} = 'IGNORE';
3584 local $SIG{TSTP} = 'IGNORE';
3585 local $SIG{PIPE} = 'IGNORE';
3587 my $oldAutoCommit = $FS::UID::AutoCommit;
3588 local $FS::UID::AutoCommit = 0;
3591 $self->select_for_update #mutex
3592 unless $opt{testonly};
3595 # find possible events (initial search)
3598 my @cust_event = ();
3600 my @eventtable = $opt{'eventtable'}
3601 ? ( $opt{'eventtable'} )
3602 : FS::part_event->eventtables_runorder;
3604 foreach my $eventtable ( @eventtable ) {
3607 if ( $opt{'objects'} ) {
3609 @objects = @{ $opt{'objects'} };
3613 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
3614 @objects = ( $eventtable eq 'cust_main' )
3616 : ( $self->$eventtable() );
3620 my @e_cust_event = ();
3622 my $cross = "CROSS JOIN $eventtable";
3623 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
3624 unless $eventtable eq 'cust_main';
3626 foreach my $object ( @objects ) {
3628 #this first search uses the condition_sql magic for optimization.
3629 #the more possible events we can eliminate in this step the better
3631 my $cross_where = '';
3632 my $pkey = $object->primary_key;
3633 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
3635 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
3637 FS::part_event_condition->where_conditions_sql( $eventtable,
3638 'time'=>$opt{'time'}
3640 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
3642 $extra_sql = "AND $extra_sql" if $extra_sql;
3644 #here is the agent virtualization
3645 $extra_sql .= " AND ( part_event.agentnum IS NULL
3646 OR part_event.agentnum = ". $self->agentnum. ' )';
3648 $extra_sql .= " $order";
3650 warn "searching for events for $eventtable ". $object->$pkey. "\n"
3651 if $opt{'debug'} > 2;
3652 my @part_event = qsearch( {
3653 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
3654 'select' => 'part_event.*',
3655 'table' => 'part_event',
3656 'addl_from' => "$cross $join",
3657 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
3658 'eventtable' => $eventtable,
3661 'extra_sql' => "AND $cross_where $extra_sql",
3665 my $pkey = $object->primary_key;
3666 warn " ". scalar(@part_event).
3667 " possible events found for $eventtable ". $object->$pkey(). "\n";
3670 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
3674 warn " ". scalar(@e_cust_event).
3675 " subtotal possible cust events found for $eventtable\n"
3678 push @cust_event, @e_cust_event;
3682 warn " ". scalar(@cust_event).
3683 " total possible cust events found in initial search\n"
3691 $opt{stage} ||= 'collect';
3693 grep { my $stage = $_->part_event->event_stage;
3694 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
3704 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
3705 'stats_hashref' => \%unsat ),
3708 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
3711 warn " invalid conditions not eliminated with condition_sql:\n".
3712 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
3719 unless( $opt{testonly} ) {
3720 foreach my $cust_event ( @cust_event ) {
3722 my $error = $cust_event->insert();
3724 $dbh->rollback if $oldAutoCommit;
3731 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3737 warn " returning events: ". Dumper(@cust_event). "\n"
3744 =item retry_realtime
3746 Schedules realtime / batch credit card / electronic check / LEC billing
3747 events for for retry. Useful if card information has changed or manual
3748 retry is desired. The 'collect' method must be called to actually retry
3751 Implementation details: For either this customer, or for each of this
3752 customer's open invoices, changes the status of the first "done" (with
3753 statustext error) realtime processing event to "failed".
3757 sub retry_realtime {
3760 local $SIG{HUP} = 'IGNORE';
3761 local $SIG{INT} = 'IGNORE';
3762 local $SIG{QUIT} = 'IGNORE';
3763 local $SIG{TERM} = 'IGNORE';
3764 local $SIG{TSTP} = 'IGNORE';
3765 local $SIG{PIPE} = 'IGNORE';
3767 my $oldAutoCommit = $FS::UID::AutoCommit;
3768 local $FS::UID::AutoCommit = 0;
3771 #a little false laziness w/due_cust_event (not too bad, really)
3773 my $join = FS::part_event_condition->join_conditions_sql;
3774 my $order = FS::part_event_condition->order_conditions_sql;
3777 . join ( ' OR ' , map {
3778 "( part_event.eventtable = " . dbh->quote($_)
3779 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3780 } FS::part_event->eventtables)
3783 #here is the agent virtualization
3784 my $agent_virt = " ( part_event.agentnum IS NULL
3785 OR part_event.agentnum = ". $self->agentnum. ' )';
3787 #XXX this shouldn't be hardcoded, actions should declare it...
3788 my @realtime_events = qw(
3789 cust_bill_realtime_card
3790 cust_bill_realtime_check
3791 cust_bill_realtime_lec
3795 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3800 my @cust_event = qsearchs({
3801 'table' => 'cust_event',
3802 'select' => 'cust_event.*',
3803 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3804 'hashref' => { 'status' => 'done' },
3805 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3806 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3809 my %seen_invnum = ();
3810 foreach my $cust_event (@cust_event) {
3812 #max one for the customer, one for each open invoice
3813 my $cust_X = $cust_event->cust_X;
3814 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3818 or $cust_event->part_event->eventtable eq 'cust_bill'
3821 my $error = $cust_event->retry;
3823 $dbh->rollback if $oldAutoCommit;
3824 return "error scheduling event for retry: $error";
3829 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3834 # some horrid false laziness here to avoid refactor fallout
3835 # eventually realtime realtime_bop and realtime_refund_bop should go
3836 # away and be replaced by _new_realtime_bop and _new_realtime_refund_bop
3838 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3840 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3841 via a Business::OnlinePayment realtime gateway. See
3842 L<http://420.am/business-onlinepayment> for supported gateways.
3844 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3846 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3848 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3849 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3850 if set, will override the value from the customer record.
3852 I<description> is a free-text field passed to the gateway. It defaults to
3853 "Internet services".
3855 If an I<invnum> is specified, this payment (if successful) is applied to the
3856 specified invoice. If you don't specify an I<invnum> you might want to
3857 call the B<apply_payments> method.
3859 I<quiet> can be set true to surpress email decline notices.
3861 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3862 resulting paynum, if any.
3864 I<payunique> is a unique identifier for this payment.
3866 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3873 return $self->_new_realtime_bop(@_)
3874 if $self->_new_bop_required();
3876 my( $method, $amount, %options ) = @_;
3878 warn "$me realtime_bop: $method $amount\n";
3879 warn " $_ => $options{$_}\n" foreach keys %options;
3882 $options{'description'} ||= 'Internet services';
3884 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3886 eval "use Business::OnlinePayment";
3889 my $payinfo = exists($options{'payinfo'})
3890 ? $options{'payinfo'}
3893 my %method2payby = (
3900 # check for banned credit card/ACH
3903 my $ban = qsearchs('banned_pay', {
3904 'payby' => $method2payby{$method},
3905 'payinfo' => md5_base64($payinfo),
3907 return "Banned credit card" if $ban;
3910 # set taxclass and trans_is_recur based on invnum if there is one
3914 my $trans_is_recur = 0;
3915 if ( $options{'invnum'} ) {
3917 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3918 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3921 map { $_->part_pkg }
3923 map { $_->cust_pkg }
3924 $cust_bill->cust_bill_pkg;
3926 my @taxclasses = map $_->taxclass, @part_pkg;
3927 $taxclass = $taxclasses[0]
3928 unless grep { $taxclasses[0] ne $_ } @taxclasses; #unless there are
3929 #different taxclasses
3931 if grep { $_->freq ne '0' } @part_pkg;
3939 #look for an agent gateway override first
3941 if ( $method eq 'CC' ) {
3942 $cardtype = cardtype($payinfo);
3943 } elsif ( $method eq 'ECHECK' ) {
3946 $cardtype = $method;
3950 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3951 cardtype => $cardtype,
3952 taxclass => $taxclass, } )
3953 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3955 taxclass => $taxclass, } )
3956 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3957 cardtype => $cardtype,
3959 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3961 taxclass => '', } );
3963 my $payment_gateway = '';
3964 my( $processor, $login, $password, $action, @bop_options );
3965 if ( $override ) { #use a payment gateway override
3967 $payment_gateway = $override->payment_gateway;
3969 $processor = $payment_gateway->gateway_module;
3970 $login = $payment_gateway->gateway_username;
3971 $password = $payment_gateway->gateway_password;
3972 $action = $payment_gateway->gateway_action;
3973 @bop_options = $payment_gateway->options;
3975 } else { #use the standard settings from the config
3977 ( $processor, $login, $password, $action, @bop_options ) =
3978 $self->default_payment_gateway($method);
3986 my $address = exists($options{'address1'})
3987 ? $options{'address1'}
3989 my $address2 = exists($options{'address2'})
3990 ? $options{'address2'}
3992 $address .= ", ". $address2 if length($address2);
3994 my $o_payname = exists($options{'payname'})
3995 ? $options{'payname'}
3997 my($payname, $payfirst, $paylast);
3998 if ( $o_payname && $method ne 'ECHECK' ) {
3999 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4000 or return "Illegal payname $payname";
4001 ($payfirst, $paylast) = ($1, $2);
4003 $payfirst = $self->getfield('first');
4004 $paylast = $self->getfield('last');
4005 $payname = "$payfirst $paylast";
4008 my @invoicing_list = $self->invoicing_list_emailonly;
4009 if ( $conf->exists('emailinvoiceautoalways')
4010 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4011 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4012 push @invoicing_list, $self->all_emails;
4015 my $email = ($conf->exists('business-onlinepayment-email-override'))
4016 ? $conf->config('business-onlinepayment-email-override')
4017 : $invoicing_list[0];
4021 my $payip = exists($options{'payip'})
4024 $content{customer_ip} = $payip
4027 $content{invoice_number} = $options{'invnum'}
4028 if exists($options{'invnum'}) && length($options{'invnum'});
4030 $content{email_customer} =
4031 ( $conf->exists('business-onlinepayment-email_customer')
4032 || $conf->exists('business-onlinepayment-email-override') );
4035 if ( $method eq 'CC' ) {
4037 $content{card_number} = $payinfo;
4038 $paydate = exists($options{'paydate'})
4039 ? $options{'paydate'}
4041 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4042 $content{expiration} = "$2/$1";
4044 my $paycvv = exists($options{'paycvv'})
4045 ? $options{'paycvv'}
4047 $content{cvv2} = $paycvv
4050 my $paystart_month = exists($options{'paystart_month'})
4051 ? $options{'paystart_month'}
4052 : $self->paystart_month;
4054 my $paystart_year = exists($options{'paystart_year'})
4055 ? $options{'paystart_year'}
4056 : $self->paystart_year;
4058 $content{card_start} = "$paystart_month/$paystart_year"
4059 if $paystart_month && $paystart_year;
4061 my $payissue = exists($options{'payissue'})
4062 ? $options{'payissue'}
4064 $content{issue_number} = $payissue if $payissue;
4066 if ( $self->_bop_recurring_billing( 'payinfo' => $payinfo,
4067 'trans_is_recur' => $trans_is_recur,
4071 $content{recurring_billing} = 'YES';
4072 $content{acct_code} = 'rebill'
4073 if $conf->exists('credit_card-recurring_billing_acct_code');
4076 } elsif ( $method eq 'ECHECK' ) {
4077 ( $content{account_number}, $content{routing_code} ) =
4078 split('@', $payinfo);
4079 $content{bank_name} = $o_payname;
4080 $content{bank_state} = exists($options{'paystate'})
4081 ? $options{'paystate'}
4082 : $self->getfield('paystate');
4083 $content{account_type} = exists($options{'paytype'})
4084 ? uc($options{'paytype'}) || 'CHECKING'
4085 : uc($self->getfield('paytype')) || 'CHECKING';
4086 $content{account_name} = $payname;
4087 $content{customer_org} = $self->company ? 'B' : 'I';
4088 $content{state_id} = exists($options{'stateid'})
4089 ? $options{'stateid'}
4090 : $self->getfield('stateid');
4091 $content{state_id_state} = exists($options{'stateid_state'})
4092 ? $options{'stateid_state'}
4093 : $self->getfield('stateid_state');
4094 $content{customer_ssn} = exists($options{'ss'})
4097 } elsif ( $method eq 'LEC' ) {
4098 $content{phone} = $payinfo;
4102 # run transaction(s)
4105 my $balance = exists( $options{'balance'} )
4106 ? $options{'balance'}
4109 $self->select_for_update; #mutex ... just until we get our pending record in
4111 #the checks here are intended to catch concurrent payments
4112 #double-form-submission prevention is taken care of in cust_pay_pending::check
4115 return "The customer's balance has changed; $method transaction aborted."
4116 if $self->balance < $balance;
4117 #&& $self->balance < $amount; #might as well anyway?
4119 #also check and make sure there aren't *other* pending payments for this cust
4121 my @pending = qsearch('cust_pay_pending', {
4122 'custnum' => $self->custnum,
4123 'status' => { op=>'!=', value=>'done' }
4125 return "A payment is already being processed for this customer (".
4126 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4127 "); $method transaction aborted."
4128 if scalar(@pending);
4130 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4132 my $cust_pay_pending = new FS::cust_pay_pending {
4133 'custnum' => $self->custnum,
4134 #'invnum' => $options{'invnum'},
4137 'payby' => $method2payby{$method},
4138 'payinfo' => $payinfo,
4139 'paydate' => $paydate,
4140 'recurring_billing' => $content{recurring_billing},
4141 'pkgnum' => $options{'pkgnum'},
4143 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
4145 $cust_pay_pending->payunique( $options{payunique} )
4146 if defined($options{payunique}) && length($options{payunique});
4147 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4148 return $cpp_new_err if $cpp_new_err;
4150 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
4152 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
4153 $transaction->content(
4156 'password' => $password,
4157 'action' => $action1,
4158 'description' => $options{'description'},
4159 'amount' => $amount,
4160 #'invoice_number' => $options{'invnum'},
4161 'customer_id' => $self->custnum,
4162 'last_name' => $paylast,
4163 'first_name' => $payfirst,
4165 'address' => $address,
4166 'city' => ( exists($options{'city'})
4169 'state' => ( exists($options{'state'})
4172 'zip' => ( exists($options{'zip'})
4175 'country' => ( exists($options{'country'})
4176 ? $options{'country'}
4178 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
4180 'phone' => $self->daytime || $self->night,
4184 $cust_pay_pending->status('pending');
4185 my $cpp_pending_err = $cust_pay_pending->replace;
4186 return $cpp_pending_err if $cpp_pending_err;
4189 my $BOP_TESTING = 0;
4190 my $BOP_TESTING_SUCCESS = 1;
4192 unless ( $BOP_TESTING ) {
4193 $transaction->submit();
4195 if ( $BOP_TESTING_SUCCESS ) {
4196 $transaction->is_success(1);
4197 $transaction->authorization('fake auth');
4199 $transaction->is_success(0);
4200 $transaction->error_message('fake failure');
4204 if ( $transaction->is_success() && $action2 ) {
4206 $cust_pay_pending->status('authorized');
4207 my $cpp_authorized_err = $cust_pay_pending->replace;
4208 return $cpp_authorized_err if $cpp_authorized_err;
4210 my $auth = $transaction->authorization;
4211 my $ordernum = $transaction->can('order_number')
4212 ? $transaction->order_number
4216 new Business::OnlinePayment( $processor, @bop_options );
4223 password => $password,
4224 order_number => $ordernum,
4226 authorization => $auth,
4227 description => $options{'description'},
4230 foreach my $field (qw( authorization_source_code returned_ACI
4231 transaction_identifier validation_code
4232 transaction_sequence_num local_transaction_date
4233 local_transaction_time AVS_result_code )) {
4234 $capture{$field} = $transaction->$field() if $transaction->can($field);
4237 $capture->content( %capture );
4241 unless ( $capture->is_success ) {
4242 my $e = "Authorization successful but capture failed, custnum #".
4243 $self->custnum. ': '. $capture->result_code.
4244 ": ". $capture->error_message;
4251 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
4252 my $cpp_captured_err = $cust_pay_pending->replace;
4253 return $cpp_captured_err if $cpp_captured_err;
4256 # remove paycvv after initial transaction
4259 #false laziness w/misc/process/payment.cgi - check both to make sure working
4261 if ( defined $self->dbdef_table->column('paycvv')
4262 && length($self->paycvv)
4263 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
4265 my $error = $self->remove_cvv;
4267 warn "WARNING: error removing cvv: $error\n";
4275 if ( $transaction->is_success() ) {
4278 if ( $payment_gateway ) { # agent override
4279 $paybatch = $payment_gateway->gatewaynum. '-';
4282 $paybatch .= "$processor:". $transaction->authorization;
4284 $paybatch .= ':'. $transaction->order_number
4285 if $transaction->can('order_number')
4286 && length($transaction->order_number);
4288 my $cust_pay = new FS::cust_pay ( {
4289 'custnum' => $self->custnum,
4290 'invnum' => $options{'invnum'},
4293 'payby' => $method2payby{$method},
4294 'payinfo' => $payinfo,
4295 'paybatch' => $paybatch,
4296 'paydate' => $paydate,
4297 'pkgnum' => $options{'pkgnum'},
4299 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
4300 $cust_pay->payunique( $options{payunique} )
4301 if defined($options{payunique}) && length($options{payunique});
4303 my $oldAutoCommit = $FS::UID::AutoCommit;
4304 local $FS::UID::AutoCommit = 0;
4307 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
4309 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4312 $cust_pay->invnum(''); #try again with no specific invnum
4313 my $error2 = $cust_pay->insert( $options{'manual'} ?
4314 ( 'manual' => 1 ) : ()
4317 # gah. but at least we have a record of the state we had to abort in
4318 # from cust_pay_pending now.
4319 my $e = "WARNING: $method captured but payment not recorded - ".
4320 "error inserting payment ($processor): $error2".
4321 " (previously tried insert with invnum #$options{'invnum'}" .
4322 ": $error ) - pending payment saved as paypendingnum ".
4323 $cust_pay_pending->paypendingnum. "\n";
4329 if ( $options{'paynum_ref'} ) {
4330 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4333 $cust_pay_pending->status('done');
4334 $cust_pay_pending->statustext('captured');
4335 $cust_pay_pending->paynum($cust_pay->paynum);
4336 my $cpp_done_err = $cust_pay_pending->replace;
4338 if ( $cpp_done_err ) {
4340 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4341 my $e = "WARNING: $method captured but payment not recorded - ".
4342 "error updating status for paypendingnum ".
4343 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
4349 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4350 return ''; #no error
4356 my $perror = "$processor error: ". $transaction->error_message;
4358 unless ( $transaction->error_message ) {
4361 if ( $transaction->can('response_page') ) {
4363 'page' => ( $transaction->can('response_page')
4364 ? $transaction->response_page
4367 'code' => ( $transaction->can('response_code')
4368 ? $transaction->response_code
4371 'headers' => ( $transaction->can('response_headers')
4372 ? $transaction->response_headers
4378 "No additional debugging information available for $processor";
4381 $perror .= "No error_message returned from $processor -- ".
4382 ( ref($t_response) ? Dumper($t_response) : $t_response );
4386 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
4387 && $conf->exists('emaildecline')
4388 && grep { $_ ne 'POST' } $self->invoicing_list
4389 && ! grep { $transaction->error_message =~ /$_/ }
4390 $conf->config('emaildecline-exclude')
4392 my @templ = $conf->config('declinetemplate');
4393 my $template = new Text::Template (
4395 SOURCE => [ map "$_\n", @templ ],
4396 ) or return "($perror) can't create template: $Text::Template::ERROR";
4397 $template->compile()
4398 or return "($perror) can't compile template: $Text::Template::ERROR";
4402 scalar( $conf->config('company_name', $self->agentnum ) ),
4403 'company_address' =>
4404 join("\n", $conf->config('company_address', $self->agentnum ) ),
4405 'error' => $transaction->error_message,
4408 my $error = send_email(
4409 'from' => $conf->config('invoice_from', $self->agentnum ),
4410 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
4411 'subject' => 'Your payment could not be processed',
4412 'body' => [ $template->fill_in(HASH => $templ_hash) ],
4415 $perror .= " (also received error sending decline notification: $error)"
4420 $cust_pay_pending->status('done');
4421 $cust_pay_pending->statustext("declined: $perror");
4422 my $cpp_done_err = $cust_pay_pending->replace;
4423 if ( $cpp_done_err ) {
4424 my $e = "WARNING: $method declined but pending payment not resolved - ".
4425 "error updating status for paypendingnum ".
4426 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
4428 $perror = "$e ($perror)";
4436 sub _bop_recurring_billing {
4437 my( $self, %opt ) = @_;
4439 my $method = $conf->config('credit_card-recurring_billing_flag');
4441 if ( $method eq 'transaction_is_recur' ) {
4443 return 1 if $opt{'trans_is_recur'};
4447 my %hash = ( 'custnum' => $self->custnum,
4452 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4453 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4464 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
4466 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
4467 via a Business::OnlinePayment realtime gateway. See
4468 L<http://420.am/business-onlinepayment> for supported gateways.
4470 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4472 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
4474 Most gateways require a reference to an original payment transaction to refund,
4475 so you probably need to specify a I<paynum>.
4477 I<amount> defaults to the original amount of the payment if not specified.
4479 I<reason> specifies a reason for the refund.
4481 I<paydate> specifies the expiration date for a credit card overriding the
4482 value from the customer record or the payment record. Specified as yyyy-mm-dd
4484 Implementation note: If I<amount> is unspecified or equal to the amount of the
4485 orignal payment, first an attempt is made to "void" the transaction via
4486 the gateway (to cancel a not-yet settled transaction) and then if that fails,
4487 the normal attempt is made to "refund" ("credit") the transaction via the
4488 gateway is attempted.
4490 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4491 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4492 #if set, will override the value from the customer record.
4494 #If an I<invnum> is specified, this payment (if successful) is applied to the
4495 #specified invoice. If you don't specify an I<invnum> you might want to
4496 #call the B<apply_payments> method.
4500 #some false laziness w/realtime_bop, not enough to make it worth merging
4501 #but some useful small subs should be pulled out
4502 sub realtime_refund_bop {
4505 return $self->_new_realtime_refund_bop(@_)
4506 if $self->_new_bop_required();
4508 my( $method, %options ) = @_;
4510 warn "$me realtime_refund_bop: $method refund\n";
4511 warn " $_ => $options{$_}\n" foreach keys %options;
4514 eval "use Business::OnlinePayment";
4518 # look up the original payment and optionally a gateway for that payment
4522 my $amount = $options{'amount'};
4524 my( $processor, $login, $password, @bop_options ) ;
4525 my( $auth, $order_number ) = ( '', '', '' );
4527 if ( $options{'paynum'} ) {
4529 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
4530 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
4531 or return "Unknown paynum $options{'paynum'}";
4532 $amount ||= $cust_pay->paid;
4534 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
4535 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
4536 $cust_pay->paybatch;
4537 my $gatewaynum = '';
4538 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
4540 if ( $gatewaynum ) { #gateway for the payment to be refunded
4542 my $payment_gateway =
4543 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
4544 die "payment gateway $gatewaynum not found"
4545 unless $payment_gateway;
4547 $processor = $payment_gateway->gateway_module;
4548 $login = $payment_gateway->gateway_username;
4549 $password = $payment_gateway->gateway_password;
4550 @bop_options = $payment_gateway->options;
4552 } else { #try the default gateway
4554 my( $conf_processor, $unused_action );
4555 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
4556 $self->default_payment_gateway($method);
4558 return "processor of payment $options{'paynum'} $processor does not".
4559 " match default processor $conf_processor"
4560 unless $processor eq $conf_processor;
4565 } else { # didn't specify a paynum, so look for agent gateway overrides
4566 # like a normal transaction
4569 if ( $method eq 'CC' ) {
4570 $cardtype = cardtype($self->payinfo);
4571 } elsif ( $method eq 'ECHECK' ) {
4574 $cardtype = $method;
4577 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
4578 cardtype => $cardtype,
4580 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
4582 taxclass => '', } );
4584 if ( $override ) { #use a payment gateway override
4586 my $payment_gateway = $override->payment_gateway;
4588 $processor = $payment_gateway->gateway_module;
4589 $login = $payment_gateway->gateway_username;
4590 $password = $payment_gateway->gateway_password;
4591 #$action = $payment_gateway->gateway_action;
4592 @bop_options = $payment_gateway->options;
4594 } else { #use the standard settings from the config
4597 ( $processor, $login, $password, $unused_action, @bop_options ) =
4598 $self->default_payment_gateway($method);
4603 return "neither amount nor paynum specified" unless $amount;
4608 'password' => $password,
4609 'order_number' => $order_number,
4610 'amount' => $amount,
4611 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
4613 $content{authorization} = $auth
4614 if length($auth); #echeck/ACH transactions have an order # but no auth
4615 #(at least with authorize.net)
4617 my $disable_void_after;
4618 if ($conf->exists('disable_void_after')
4619 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
4620 $disable_void_after = $1;
4623 #first try void if applicable
4624 if ( $cust_pay && $cust_pay->paid == $amount
4626 ( not defined($disable_void_after) )
4627 || ( time < ($cust_pay->_date + $disable_void_after ) )
4630 warn " attempting void\n" if $DEBUG > 1;
4631 my $void = new Business::OnlinePayment( $processor, @bop_options );
4632 $void->content( 'action' => 'void', %content );
4634 if ( $void->is_success ) {
4635 my $error = $cust_pay->void($options{'reason'});
4637 # gah, even with transactions.
4638 my $e = 'WARNING: Card/ACH voided but database not updated - '.
4639 "error voiding payment: $error";
4643 warn " void successful\n" if $DEBUG > 1;
4648 warn " void unsuccessful, trying refund\n"
4652 my $address = $self->address1;
4653 $address .= ", ". $self->address2 if $self->address2;
4655 my($payname, $payfirst, $paylast);
4656 if ( $self->payname && $method ne 'ECHECK' ) {
4657 $payname = $self->payname;
4658 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4659 or return "Illegal payname $payname";
4660 ($payfirst, $paylast) = ($1, $2);
4662 $payfirst = $self->getfield('first');
4663 $paylast = $self->getfield('last');
4664 $payname = "$payfirst $paylast";
4667 my @invoicing_list = $self->invoicing_list_emailonly;
4668 if ( $conf->exists('emailinvoiceautoalways')
4669 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4670 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4671 push @invoicing_list, $self->all_emails;
4674 my $email = ($conf->exists('business-onlinepayment-email-override'))
4675 ? $conf->config('business-onlinepayment-email-override')
4676 : $invoicing_list[0];
4678 my $payip = exists($options{'payip'})
4681 $content{customer_ip} = $payip
4685 if ( $method eq 'CC' ) {
4688 $content{card_number} = $payinfo = $cust_pay->payinfo;
4689 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
4690 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
4691 ($content{expiration} = "$2/$1"); # where available
4693 $content{card_number} = $payinfo = $self->payinfo;
4694 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
4695 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4696 $content{expiration} = "$2/$1";
4699 } elsif ( $method eq 'ECHECK' ) {
4702 $payinfo = $cust_pay->payinfo;
4704 $payinfo = $self->payinfo;
4706 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
4707 $content{bank_name} = $self->payname;
4708 $content{account_type} = 'CHECKING';
4709 $content{account_name} = $payname;
4710 $content{customer_org} = $self->company ? 'B' : 'I';
4711 $content{customer_ssn} = $self->ss;
4712 } elsif ( $method eq 'LEC' ) {
4713 $content{phone} = $payinfo = $self->payinfo;
4717 my $refund = new Business::OnlinePayment( $processor, @bop_options );
4718 my %sub_content = $refund->content(
4719 'action' => 'credit',
4720 'customer_id' => $self->custnum,
4721 'last_name' => $paylast,
4722 'first_name' => $payfirst,
4724 'address' => $address,
4725 'city' => $self->city,
4726 'state' => $self->state,
4727 'zip' => $self->zip,
4728 'country' => $self->country,
4730 'phone' => $self->daytime || $self->night,
4733 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
4737 return "$processor error: ". $refund->error_message
4738 unless $refund->is_success();
4740 my %method2payby = (
4746 my $paybatch = "$processor:". $refund->authorization;
4747 $paybatch .= ':'. $refund->order_number
4748 if $refund->can('order_number') && $refund->order_number;
4750 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4751 my @cust_bill_pay = $cust_pay->cust_bill_pay;
4752 last unless @cust_bill_pay;
4753 my $cust_bill_pay = pop @cust_bill_pay;
4754 my $error = $cust_bill_pay->delete;
4758 my $cust_refund = new FS::cust_refund ( {
4759 'custnum' => $self->custnum,
4760 'paynum' => $options{'paynum'},
4761 'refund' => $amount,
4763 'payby' => $method2payby{$method},
4764 'payinfo' => $payinfo,
4765 'paybatch' => $paybatch,
4766 'reason' => $options{'reason'} || 'card or ACH refund',
4768 my $error = $cust_refund->insert;
4770 $cust_refund->paynum(''); #try again with no specific paynum
4771 my $error2 = $cust_refund->insert;
4773 # gah, even with transactions.
4774 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4775 "error inserting refund ($processor): $error2".
4776 " (previously tried insert with paynum #$options{'paynum'}" .
4787 # does the configuration indicate the new bop routines are required?
4789 sub _new_bop_required {
4792 my $botpp = 'Business::OnlineThirdPartyPayment';
4795 if ( $conf->config('business-onlinepayment-namespace') eq $botpp ||
4796 scalar( grep { $_->gateway_namespace eq $botpp }
4797 qsearch( 'payment_gateway', { 'disabled' => '' } )
4806 =item realtime_collect [ OPTION => VALUE ... ]
4808 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4809 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4810 gateway. See L<http://420.am/business-onlinepayment> and
4811 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4813 On failure returns an error message.
4815 Returns false or a hashref upon success. The hashref contains keys popup_url reference, and collectitems. The first is a URL to which a browser should be redirected for completion of collection. The second is a reference id for the transaction suitable for the end user. The collectitems is a reference to a list of name value pairs suitable for assigning to a html form and posted to popup_url.
4817 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4819 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
4820 then it is deduced from the customer record.
4822 If no I<amount> is specified, then the customer balance is used.
4824 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4825 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4826 if set, will override the value from the customer record.
4828 I<description> is a free-text field passed to the gateway. It defaults to
4829 "Internet services".
4831 If an I<invnum> is specified, this payment (if successful) is applied to the
4832 specified invoice. If you don't specify an I<invnum> you might want to
4833 call the B<apply_payments> method.
4835 I<quiet> can be set true to surpress email decline notices.
4837 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4838 resulting paynum, if any.
4840 I<payunique> is a unique identifier for this payment.
4842 I<session_id> is a session identifier associated with this payment.
4844 I<depend_jobnum> allows payment capture to unlock export jobs
4848 sub realtime_collect {
4849 my( $self, %options ) = @_;
4852 warn "$me realtime_collect:\n";
4853 warn " $_ => $options{$_}\n" foreach keys %options;
4856 $options{amount} = $self->balance unless exists( $options{amount} );
4857 $options{method} = FS::payby->payby2bop($self->payby)
4858 unless exists( $options{method} );
4860 return $self->realtime_bop({%options});
4864 =item _realtime_bop { [ ARG => VALUE ... ] }
4866 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4867 via a Business::OnlinePayment realtime gateway. See
4868 L<http://420.am/business-onlinepayment> for supported gateways.
4870 Required arguments in the hashref are I<method>, and I<amount>
4872 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4874 Available optional arguments are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4876 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4877 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4878 if set, will override the value from the customer record.
4880 I<description> is a free-text field passed to the gateway. It defaults to
4881 "Internet services".
4883 If an I<invnum> is specified, this payment (if successful) is applied to the
4884 specified invoice. If you don't specify an I<invnum> you might want to
4885 call the B<apply_payments> method.
4887 I<quiet> can be set true to surpress email decline notices.
4889 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4890 resulting paynum, if any.
4892 I<payunique> is a unique identifier for this payment.
4894 I<session_id> is a session identifier associated with this payment.
4896 I<depend_jobnum> allows payment capture to unlock export jobs
4898 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4902 # some helper routines
4903 sub _payment_gateway {
4904 my ($self, $options) = @_;
4906 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4907 unless exists($options->{payment_gateway});
4909 $options->{payment_gateway};
4913 my ($self, $options) = @_;
4916 'login' => $options->{payment_gateway}->gateway_username,
4917 'password' => $options->{payment_gateway}->gateway_password,
4922 my ($self, $options) = @_;
4924 $options->{payment_gateway}->gatewaynum
4925 ? $options->{payment_gateway}->options
4926 : @{ $options->{payment_gateway}->get('options') };
4930 my ($self, $options) = @_;
4932 $options->{description} ||= 'Internet services';
4933 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4934 $options->{invnum} ||= '';
4935 $options->{payname} = $self->payname unless exists( $options->{payname} );
4939 my ($self, $options) = @_;
4942 $content{address} = exists($options->{'address1'})
4943 ? $options->{'address1'}
4945 my $address2 = exists($options->{'address2'})
4946 ? $options->{'address2'}
4948 $content{address} .= ", ". $address2 if length($address2);
4950 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4951 $content{customer_ip} = $payip if length($payip);
4953 $content{invoice_number} = $options->{'invnum'}
4954 if exists($options->{'invnum'}) && length($options->{'invnum'});
4956 $content{email_customer} =
4957 ( $conf->exists('business-onlinepayment-email_customer')
4958 || $conf->exists('business-onlinepayment-email-override') );
4960 $content{payfirst} = $self->getfield('first');
4961 $content{paylast} = $self->getfield('last');
4963 $content{account_name} = "$content{payfirst} $content{paylast}"
4964 if $options->{method} eq 'ECHECK';
4966 $content{name} = $options->{payname};
4967 $content{name} = $content{account_name} if exists($content{account_name});
4969 $content{city} = exists($options->{city})
4972 $content{state} = exists($options->{state})
4975 $content{zip} = exists($options->{zip})
4978 $content{country} = exists($options->{country})
4979 ? $options->{country}
4981 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4982 $content{phone} = $self->daytime || $self->night;
4987 my %bop_method2payby = (
4993 sub _new_realtime_bop {
4997 if (ref($_[0]) eq 'HASH') {
4998 %options = %{$_[0]};
5000 my ( $method, $amount ) = ( shift, shift );
5002 $options{method} = $method;
5003 $options{amount} = $amount;
5007 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
5008 warn " $_ => $options{$_}\n" foreach keys %options;
5011 return $self->fake_bop(%options) if $options{'fake'};
5013 $self->_bop_defaults(\%options);
5016 # set trans_is_recur based on invnum if there is one
5019 my $trans_is_recur = 0;
5020 if ( $options{'invnum'} ) {
5022 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
5023 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
5026 map { $_->part_pkg }
5028 map { $_->cust_pkg }
5029 $cust_bill->cust_bill_pkg;
5032 if grep { $_->freq ne '0' } @part_pkg;
5040 my $payment_gateway = $self->_payment_gateway( \%options );
5041 my $namespace = $payment_gateway->gateway_namespace;
5043 eval "use $namespace";
5047 # check for banned credit card/ACH
5050 my $ban = qsearchs('banned_pay', {
5051 'payby' => $bop_method2payby{$options{method}},
5052 'payinfo' => md5_base64($options{payinfo}),
5054 return "Banned credit card" if $ban;
5060 my (%bop_content) = $self->_bop_content(\%options);
5062 if ( $options{method} ne 'ECHECK' ) {
5063 $options{payname} =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5064 or return "Illegal payname $options{payname}";
5065 ($bop_content{payfirst}, $bop_content{paylast}) = ($1, $2);
5068 my @invoicing_list = $self->invoicing_list_emailonly;
5069 if ( $conf->exists('emailinvoiceautoalways')
5070 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5071 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5072 push @invoicing_list, $self->all_emails;
5075 my $email = ($conf->exists('business-onlinepayment-email-override'))
5076 ? $conf->config('business-onlinepayment-email-override')
5077 : $invoicing_list[0];
5081 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
5083 $content{card_number} = $options{payinfo};
5084 $paydate = exists($options{'paydate'})
5085 ? $options{'paydate'}
5087 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5088 $content{expiration} = "$2/$1";
5090 my $paycvv = exists($options{'paycvv'})
5091 ? $options{'paycvv'}
5093 $content{cvv2} = $paycvv
5096 my $paystart_month = exists($options{'paystart_month'})
5097 ? $options{'paystart_month'}
5098 : $self->paystart_month;
5100 my $paystart_year = exists($options{'paystart_year'})
5101 ? $options{'paystart_year'}
5102 : $self->paystart_year;
5104 $content{card_start} = "$paystart_month/$paystart_year"
5105 if $paystart_month && $paystart_year;
5107 my $payissue = exists($options{'payissue'})
5108 ? $options{'payissue'}
5110 $content{issue_number} = $payissue if $payissue;
5112 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
5113 'trans_is_recur' => $trans_is_recur,
5117 $content{recurring_billing} = 'YES';
5118 $content{acct_code} = 'rebill'
5119 if $conf->exists('credit_card-recurring_billing_acct_code');
5122 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
5123 ( $content{account_number}, $content{routing_code} ) =
5124 split('@', $options{payinfo});
5125 $content{bank_name} = $options{payname};
5126 $content{bank_state} = exists($options{'paystate'})
5127 ? $options{'paystate'}
5128 : $self->getfield('paystate');
5129 $content{account_type} = exists($options{'paytype'})
5130 ? uc($options{'paytype'}) || 'CHECKING'
5131 : uc($self->getfield('paytype')) || 'CHECKING';
5132 $content{customer_org} = $self->company ? 'B' : 'I';
5133 $content{state_id} = exists($options{'stateid'})
5134 ? $options{'stateid'}
5135 : $self->getfield('stateid');
5136 $content{state_id_state} = exists($options{'stateid_state'})
5137 ? $options{'stateid_state'}
5138 : $self->getfield('stateid_state');
5139 $content{customer_ssn} = exists($options{'ss'})
5142 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
5143 $content{phone} = $options{payinfo};
5144 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
5151 # run transaction(s)
5154 my $balance = exists( $options{'balance'} )
5155 ? $options{'balance'}
5158 $self->select_for_update; #mutex ... just until we get our pending record in
5160 #the checks here are intended to catch concurrent payments
5161 #double-form-submission prevention is taken care of in cust_pay_pending::check
5164 return "The customer's balance has changed; $options{method} transaction aborted."
5165 if $self->balance < $balance;
5166 #&& $self->balance < $options{amount}; #might as well anyway?
5168 #also check and make sure there aren't *other* pending payments for this cust
5170 my @pending = qsearch('cust_pay_pending', {
5171 'custnum' => $self->custnum,
5172 'status' => { op=>'!=', value=>'done' }
5174 return "A payment is already being processed for this customer (".
5175 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
5176 "); $options{method} transaction aborted."
5177 if scalar(@pending);
5179 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
5181 my $cust_pay_pending = new FS::cust_pay_pending {
5182 'custnum' => $self->custnum,
5183 #'invnum' => $options{'invnum'},
5184 'paid' => $options{amount},
5186 'payby' => $bop_method2payby{$options{method}},
5187 'payinfo' => $options{payinfo},
5188 'paydate' => $paydate,
5189 'recurring_billing' => $content{recurring_billing},
5190 'pkgnum' => $options{'pkgnum'},
5192 'gatewaynum' => $payment_gateway->gatewaynum || '',
5193 'session_id' => $options{session_id} || '',
5194 'jobnum' => $options{depend_jobnum} || '',
5196 $cust_pay_pending->payunique( $options{payunique} )
5197 if defined($options{payunique}) && length($options{payunique});
5198 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
5199 return $cpp_new_err if $cpp_new_err;
5201 my( $action1, $action2 ) =
5202 split( /\s*\,\s*/, $payment_gateway->gateway_action );
5204 my $transaction = new $namespace( $payment_gateway->gateway_module,
5205 $self->_bop_options(\%options),
5208 $transaction->content(
5209 'type' => $options{method},
5210 $self->_bop_auth(\%options),
5211 'action' => $action1,
5212 'description' => $options{'description'},
5213 'amount' => $options{amount},
5214 #'invoice_number' => $options{'invnum'},
5215 'customer_id' => $self->custnum,
5217 'reference' => $cust_pay_pending->paypendingnum, #for now
5222 $cust_pay_pending->status('pending');
5223 my $cpp_pending_err = $cust_pay_pending->replace;
5224 return $cpp_pending_err if $cpp_pending_err;
5227 my $BOP_TESTING = 0;
5228 my $BOP_TESTING_SUCCESS = 1;
5230 unless ( $BOP_TESTING ) {
5231 $transaction->submit();
5233 if ( $BOP_TESTING_SUCCESS ) {
5234 $transaction->is_success(1);
5235 $transaction->authorization('fake auth');
5237 $transaction->is_success(0);
5238 $transaction->error_message('fake failure');
5242 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
5244 return { reference => $cust_pay_pending->paypendingnum,
5245 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
5247 } elsif ( $transaction->is_success() && $action2 ) {
5249 $cust_pay_pending->status('authorized');
5250 my $cpp_authorized_err = $cust_pay_pending->replace;
5251 return $cpp_authorized_err if $cpp_authorized_err;
5253 my $auth = $transaction->authorization;
5254 my $ordernum = $transaction->can('order_number')
5255 ? $transaction->order_number
5259 new Business::OnlinePayment( $payment_gateway->gateway_module,
5260 $self->_bop_options(\%options),
5265 type => $options{method},
5267 $self->_bop_auth(\%options),
5268 order_number => $ordernum,
5269 amount => $options{amount},
5270 authorization => $auth,
5271 description => $options{'description'},
5274 foreach my $field (qw( authorization_source_code returned_ACI
5275 transaction_identifier validation_code
5276 transaction_sequence_num local_transaction_date
5277 local_transaction_time AVS_result_code )) {
5278 $capture{$field} = $transaction->$field() if $transaction->can($field);
5281 $capture->content( %capture );
5285 unless ( $capture->is_success ) {
5286 my $e = "Authorization successful but capture failed, custnum #".
5287 $self->custnum. ': '. $capture->result_code.
5288 ": ". $capture->error_message;
5296 # remove paycvv after initial transaction
5299 #false laziness w/misc/process/payment.cgi - check both to make sure working
5301 if ( defined $self->dbdef_table->column('paycvv')
5302 && length($self->paycvv)
5303 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
5305 my $error = $self->remove_cvv;
5307 warn "WARNING: error removing cvv: $error\n";
5315 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5327 if (ref($_[0]) eq 'HASH') {
5328 %options = %{$_[0]};
5330 my ( $method, $amount ) = ( shift, shift );
5332 $options{method} = $method;
5333 $options{amount} = $amount;
5336 if ( $options{'fake_failure'} ) {
5337 return "Error: No error; test failure requested with fake_failure";
5341 #if ( $payment_gateway->gatewaynum ) { # agent override
5342 # $paybatch = $payment_gateway->gatewaynum. '-';
5345 #$paybatch .= "$processor:". $transaction->authorization;
5347 #$paybatch .= ':'. $transaction->order_number
5348 # if $transaction->can('order_number')
5349 # && length($transaction->order_number);
5351 my $paybatch = 'FakeProcessor:54:32';
5353 my $cust_pay = new FS::cust_pay ( {
5354 'custnum' => $self->custnum,
5355 'invnum' => $options{'invnum'},
5356 'paid' => $options{amount},
5358 'payby' => $bop_method2payby{$options{method}},
5359 #'payinfo' => $payinfo,
5360 'payinfo' => '4111111111111111',
5361 'paybatch' => $paybatch,
5362 #'paydate' => $paydate,
5363 'paydate' => '2012-05-01',
5365 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
5367 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
5370 $cust_pay->invnum(''); #try again with no specific invnum
5371 my $error2 = $cust_pay->insert( $options{'manual'} ?
5372 ( 'manual' => 1 ) : ()
5375 # gah, even with transactions.
5376 my $e = 'WARNING: Card/ACH debited but database not updated - '.
5377 "error inserting (fake!) payment: $error2".
5378 " (previously tried insert with invnum #$options{'invnum'}" .
5385 if ( $options{'paynum_ref'} ) {
5386 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5389 return ''; #no error
5394 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
5396 # Wraps up processing of a realtime credit card, ACH (electronic check) or
5397 # phone bill transaction.
5399 sub _realtime_bop_result {
5400 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
5402 warn "$me _realtime_bop_result: pending transaction ".
5403 $cust_pay_pending->paypendingnum. "\n";
5404 warn " $_ => $options{$_}\n" foreach keys %options;
5407 my $payment_gateway = $options{payment_gateway}
5408 or return "no payment gateway in arguments to _realtime_bop_result";
5410 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
5411 my $cpp_captured_err = $cust_pay_pending->replace;
5412 return $cpp_captured_err if $cpp_captured_err;
5414 if ( $transaction->is_success() ) {
5417 if ( $payment_gateway->gatewaynum ) { # agent override
5418 $paybatch = $payment_gateway->gatewaynum. '-';
5421 $paybatch .= $payment_gateway->gateway_module. ":".
5422 $transaction->authorization;
5424 $paybatch .= ':'. $transaction->order_number
5425 if $transaction->can('order_number')
5426 && length($transaction->order_number);
5428 my $cust_pay = new FS::cust_pay ( {
5429 'custnum' => $self->custnum,
5430 'invnum' => $options{'invnum'},
5431 'paid' => $cust_pay_pending->paid,
5433 'payby' => $cust_pay_pending->payby,
5434 #'payinfo' => $payinfo,
5435 'paybatch' => $paybatch,
5436 'paydate' => $cust_pay_pending->paydate,
5437 'pkgnum' => $cust_pay_pending->pkgnum,
5439 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
5440 $cust_pay->payunique( $options{payunique} )
5441 if defined($options{payunique}) && length($options{payunique});
5443 my $oldAutoCommit = $FS::UID::AutoCommit;
5444 local $FS::UID::AutoCommit = 0;
5447 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
5449 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
5452 $cust_pay->invnum(''); #try again with no specific invnum
5453 my $error2 = $cust_pay->insert( $options{'manual'} ?
5454 ( 'manual' => 1 ) : ()
5457 # gah. but at least we have a record of the state we had to abort in
5458 # from cust_pay_pending now.
5459 my $e = "WARNING: $options{method} captured but payment not recorded -".
5460 " error inserting payment (". $payment_gateway->gateway_module.
5462 " (previously tried insert with invnum #$options{'invnum'}" .
5463 ": $error ) - pending payment saved as paypendingnum ".
5464 $cust_pay_pending->paypendingnum. "\n";
5470 my $jobnum = $cust_pay_pending->jobnum;
5472 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5474 unless ( $placeholder ) {
5475 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5476 my $e = "WARNING: $options{method} captured but job $jobnum not ".
5477 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
5482 $error = $placeholder->delete;
5485 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5486 my $e = "WARNING: $options{method} captured but could not delete ".
5487 "job $jobnum for paypendingnum ".
5488 $cust_pay_pending->paypendingnum. ": $error\n";
5495 if ( $options{'paynum_ref'} ) {
5496 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5499 $cust_pay_pending->status('done');
5500 $cust_pay_pending->statustext('captured');
5501 $cust_pay_pending->paynum($cust_pay->paynum);
5502 my $cpp_done_err = $cust_pay_pending->replace;
5504 if ( $cpp_done_err ) {
5506 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5507 my $e = "WARNING: $options{method} captured but payment not recorded - ".
5508 "error updating status for paypendingnum ".
5509 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5515 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5516 return ''; #no error
5522 my $perror = $payment_gateway->gateway_module. " error: ".
5523 $transaction->error_message;
5525 my $jobnum = $cust_pay_pending->jobnum;
5527 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5529 if ( $placeholder ) {
5530 my $error = $placeholder->depended_delete;
5531 $error ||= $placeholder->delete;
5532 warn "error removing provisioning jobs after declined paypendingnum ".
5533 $cust_pay_pending->paypendingnum. "\n";
5535 my $e = "error finding job $jobnum for declined paypendingnum ".
5536 $cust_pay_pending->paypendingnum. "\n";
5542 unless ( $transaction->error_message ) {
5545 if ( $transaction->can('response_page') ) {
5547 'page' => ( $transaction->can('response_page')
5548 ? $transaction->response_page
5551 'code' => ( $transaction->can('response_code')
5552 ? $transaction->response_code
5555 'headers' => ( $transaction->can('response_headers')
5556 ? $transaction->response_headers
5562 "No additional debugging information available for ".
5563 $payment_gateway->gateway_module;
5566 $perror .= "No error_message returned from ".
5567 $payment_gateway->gateway_module. " -- ".
5568 ( ref($t_response) ? Dumper($t_response) : $t_response );
5572 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
5573 && $conf->exists('emaildecline')
5574 && grep { $_ ne 'POST' } $self->invoicing_list
5575 && ! grep { $transaction->error_message =~ /$_/ }
5576 $conf->config('emaildecline-exclude')
5578 my @templ = $conf->config('declinetemplate');
5579 my $template = new Text::Template (
5581 SOURCE => [ map "$_\n", @templ ],
5582 ) or return "($perror) can't create template: $Text::Template::ERROR";
5583 $template->compile()
5584 or return "($perror) can't compile template: $Text::Template::ERROR";
5588 scalar( $conf->config('company_name', $self->agentnum ) ),
5589 'company_address' =>
5590 join("\n", $conf->config('company_address', $self->agentnum ) ),
5591 'error' => $transaction->error_message,
5594 my $error = send_email(
5595 'from' => $conf->config('invoice_from', $self->agentnum ),
5596 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
5597 'subject' => 'Your payment could not be processed',
5598 'body' => [ $template->fill_in(HASH => $templ_hash) ],
5601 $perror .= " (also received error sending decline notification: $error)"
5606 $cust_pay_pending->status('done');
5607 $cust_pay_pending->statustext("declined: $perror");
5608 my $cpp_done_err = $cust_pay_pending->replace;
5609 if ( $cpp_done_err ) {
5610 my $e = "WARNING: $options{method} declined but pending payment not ".
5611 "resolved - error updating status for paypendingnum ".
5612 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5614 $perror = "$e ($perror)";
5622 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
5624 Verifies successful third party processing of a realtime credit card,
5625 ACH (electronic check) or phone bill transaction via a
5626 Business::OnlineThirdPartyPayment realtime gateway. See
5627 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
5629 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
5631 The additional options I<payname>, I<city>, I<state>,
5632 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5633 if set, will override the value from the customer record.
5635 I<description> is a free-text field passed to the gateway. It defaults to
5636 "Internet services".
5638 If an I<invnum> is specified, this payment (if successful) is applied to the
5639 specified invoice. If you don't specify an I<invnum> you might want to
5640 call the B<apply_payments> method.
5642 I<quiet> can be set true to surpress email decline notices.
5644 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
5645 resulting paynum, if any.
5647 I<payunique> is a unique identifier for this payment.
5649 Returns a hashref containing elements bill_error (which will be undefined
5650 upon success) and session_id of any associated session.
5654 sub realtime_botpp_capture {
5655 my( $self, $cust_pay_pending, %options ) = @_;
5657 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5658 warn " $_ => $options{$_}\n" foreach keys %options;
5661 eval "use Business::OnlineThirdPartyPayment";
5665 # select the gateway
5668 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5670 my $payment_gateway = $cust_pay_pending->gatewaynum
5671 ? qsearchs( 'payment_gateway',
5672 { gatewaynum => $cust_pay_pending->gatewaynum }
5674 : $self->agent->payment_gateway( 'method' => $method,
5675 # 'invnum' => $cust_pay_pending->invnum,
5676 # 'payinfo' => $cust_pay_pending->payinfo,
5679 $options{payment_gateway} = $payment_gateway; # for the helper subs
5685 my @invoicing_list = $self->invoicing_list_emailonly;
5686 if ( $conf->exists('emailinvoiceautoalways')
5687 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5688 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5689 push @invoicing_list, $self->all_emails;
5692 my $email = ($conf->exists('business-onlinepayment-email-override'))
5693 ? $conf->config('business-onlinepayment-email-override')
5694 : $invoicing_list[0];
5698 $content{email_customer} =
5699 ( $conf->exists('business-onlinepayment-email_customer')
5700 || $conf->exists('business-onlinepayment-email-override') );
5703 # run transaction(s)
5707 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5708 $self->_bop_options(\%options),
5711 $transaction->reference({ %options });
5713 $transaction->content(
5715 $self->_bop_auth(\%options),
5716 'action' => 'Post Authorization',
5717 'description' => $options{'description'},
5718 'amount' => $cust_pay_pending->paid,
5719 #'invoice_number' => $options{'invnum'},
5720 'customer_id' => $self->custnum,
5721 'referer' => 'http://cleanwhisker.420.am/',
5722 'reference' => $cust_pay_pending->paypendingnum,
5724 'phone' => $self->daytime || $self->night,
5726 # plus whatever is required for bogus capture avoidance
5729 $transaction->submit();
5732 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5735 bill_error => $error,
5736 session_id => $cust_pay_pending->session_id,
5741 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5745 sub default_payment_gateway {
5746 my( $self, $method ) = @_;
5748 die "Real-time processing not enabled\n"
5749 unless $conf->exists('business-onlinepayment');
5751 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5754 my $bop_config = 'business-onlinepayment';
5755 $bop_config .= '-ach'
5756 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5757 my ( $processor, $login, $password, $action, @bop_options ) =
5758 $conf->config($bop_config);
5759 $action ||= 'normal authorization';
5760 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5761 die "No real-time processor is enabled - ".
5762 "did you set the business-onlinepayment configuration value?\n"
5765 ( $processor, $login, $password, $action, @bop_options )
5770 Removes the I<paycvv> field from the database directly.
5772 If there is an error, returns the error, otherwise returns false.
5778 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5779 or return dbh->errstr;
5780 $sth->execute($self->custnum)
5781 or return $sth->errstr;
5786 =item _new_realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5788 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5789 via a Business::OnlinePayment realtime gateway. See
5790 L<http://420.am/business-onlinepayment> for supported gateways.
5792 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5794 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5796 Most gateways require a reference to an original payment transaction to refund,
5797 so you probably need to specify a I<paynum>.
5799 I<amount> defaults to the original amount of the payment if not specified.
5801 I<reason> specifies a reason for the refund.
5803 I<paydate> specifies the expiration date for a credit card overriding the
5804 value from the customer record or the payment record. Specified as yyyy-mm-dd
5806 Implementation note: If I<amount> is unspecified or equal to the amount of the
5807 orignal payment, first an attempt is made to "void" the transaction via
5808 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5809 the normal attempt is made to "refund" ("credit") the transaction via the
5810 gateway is attempted.
5812 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5813 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5814 #if set, will override the value from the customer record.
5816 #If an I<invnum> is specified, this payment (if successful) is applied to the
5817 #specified invoice. If you don't specify an I<invnum> you might want to
5818 #call the B<apply_payments> method.
5822 #some false laziness w/realtime_bop, not enough to make it worth merging
5823 #but some useful small subs should be pulled out
5824 sub _new_realtime_refund_bop {
5828 if (ref($_[0]) ne 'HASH') {
5829 %options = %{$_[0]};
5833 $options{method} = $method;
5837 warn "$me realtime_refund_bop (new): $options{method} refund\n";
5838 warn " $_ => $options{$_}\n" foreach keys %options;
5842 # look up the original payment and optionally a gateway for that payment
5846 my $amount = $options{'amount'};
5848 my( $processor, $login, $password, @bop_options, $namespace ) ;
5849 my( $auth, $order_number ) = ( '', '', '' );
5851 if ( $options{'paynum'} ) {
5853 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
5854 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5855 or return "Unknown paynum $options{'paynum'}";
5856 $amount ||= $cust_pay->paid;
5858 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5859 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5860 $cust_pay->paybatch;
5861 my $gatewaynum = '';
5862 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5864 if ( $gatewaynum ) { #gateway for the payment to be refunded
5866 my $payment_gateway =
5867 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5868 die "payment gateway $gatewaynum not found"
5869 unless $payment_gateway;
5871 $processor = $payment_gateway->gateway_module;
5872 $login = $payment_gateway->gateway_username;
5873 $password = $payment_gateway->gateway_password;
5874 $namespace = $payment_gateway->gateway_namespace;
5875 @bop_options = $payment_gateway->options;
5877 } else { #try the default gateway
5880 my $payment_gateway =
5881 $self->agent->payment_gateway('method' => $options{method});
5883 ( $conf_processor, $login, $password, $namespace ) =
5884 map { my $method = "gateway_$_"; $payment_gateway->$method }
5885 qw( module username password namespace );
5887 @bop_options = $payment_gateway->gatewaynum
5888 ? $payment_gateway->options
5889 : @{ $payment_gateway->get('options') };
5891 return "processor of payment $options{'paynum'} $processor does not".
5892 " match default processor $conf_processor"
5893 unless $processor eq $conf_processor;
5898 } else { # didn't specify a paynum, so look for agent gateway overrides
5899 # like a normal transaction
5901 my $payment_gateway =
5902 $self->agent->payment_gateway( 'method' => $options{method},
5903 #'payinfo' => $payinfo,
5905 my( $processor, $login, $password, $namespace ) =
5906 map { my $method = "gateway_$_"; $payment_gateway->$method }
5907 qw( module username password namespace );
5909 my @bop_options = $payment_gateway->gatewaynum
5910 ? $payment_gateway->options
5911 : @{ $payment_gateway->get('options') };
5914 return "neither amount nor paynum specified" unless $amount;
5916 eval "use $namespace";
5920 'type' => $options{method},
5922 'password' => $password,
5923 'order_number' => $order_number,
5924 'amount' => $amount,
5925 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5927 $content{authorization} = $auth
5928 if length($auth); #echeck/ACH transactions have an order # but no auth
5929 #(at least with authorize.net)
5931 my $disable_void_after;
5932 if ($conf->exists('disable_void_after')
5933 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5934 $disable_void_after = $1;
5937 #first try void if applicable
5938 if ( $cust_pay && $cust_pay->paid == $amount
5940 ( not defined($disable_void_after) )
5941 || ( time < ($cust_pay->_date + $disable_void_after ) )
5944 warn " attempting void\n" if $DEBUG > 1;
5945 my $void = new Business::OnlinePayment( $processor, @bop_options );
5946 $void->content( 'action' => 'void', %content );
5948 if ( $void->is_success ) {
5949 my $error = $cust_pay->void($options{'reason'});
5951 # gah, even with transactions.
5952 my $e = 'WARNING: Card/ACH voided but database not updated - '.
5953 "error voiding payment: $error";
5957 warn " void successful\n" if $DEBUG > 1;
5962 warn " void unsuccessful, trying refund\n"
5966 my $address = $self->address1;
5967 $address .= ", ". $self->address2 if $self->address2;
5969 my($payname, $payfirst, $paylast);
5970 if ( $self->payname && $options{method} ne 'ECHECK' ) {
5971 $payname = $self->payname;
5972 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5973 or return "Illegal payname $payname";
5974 ($payfirst, $paylast) = ($1, $2);
5976 $payfirst = $self->getfield('first');
5977 $paylast = $self->getfield('last');
5978 $payname = "$payfirst $paylast";
5981 my @invoicing_list = $self->invoicing_list_emailonly;
5982 if ( $conf->exists('emailinvoiceautoalways')
5983 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5984 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5985 push @invoicing_list, $self->all_emails;
5988 my $email = ($conf->exists('business-onlinepayment-email-override'))
5989 ? $conf->config('business-onlinepayment-email-override')
5990 : $invoicing_list[0];
5992 my $payip = exists($options{'payip'})
5995 $content{customer_ip} = $payip
5999 if ( $options{method} eq 'CC' ) {
6002 $content{card_number} = $payinfo = $cust_pay->payinfo;
6003 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
6004 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
6005 ($content{expiration} = "$2/$1"); # where available
6007 $content{card_number} = $payinfo = $self->payinfo;
6008 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
6009 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
6010 $content{expiration} = "$2/$1";
6013 } elsif ( $options{method} eq 'ECHECK' ) {
6016 $payinfo = $cust_pay->payinfo;
6018 $payinfo = $self->payinfo;
6020 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
6021 $content{bank_name} = $self->payname;
6022 $content{account_type} = 'CHECKING';
6023 $content{account_name} = $payname;
6024 $content{customer_org} = $self->company ? 'B' : 'I';
6025 $content{customer_ssn} = $self->ss;
6026 } elsif ( $options{method} eq 'LEC' ) {
6027 $content{phone} = $payinfo = $self->payinfo;
6031 my $refund = new Business::OnlinePayment( $processor, @bop_options );
6032 my %sub_content = $refund->content(
6033 'action' => 'credit',
6034 'customer_id' => $self->custnum,
6035 'last_name' => $paylast,
6036 'first_name' => $payfirst,
6038 'address' => $address,
6039 'city' => $self->city,
6040 'state' => $self->state,
6041 'zip' => $self->zip,
6042 'country' => $self->country,
6044 'phone' => $self->daytime || $self->night,
6047 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
6051 return "$processor error: ". $refund->error_message
6052 unless $refund->is_success();
6054 my $paybatch = "$processor:". $refund->authorization;
6055 $paybatch .= ':'. $refund->order_number
6056 if $refund->can('order_number') && $refund->order_number;
6058 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
6059 my @cust_bill_pay = $cust_pay->cust_bill_pay;
6060 last unless @cust_bill_pay;
6061 my $cust_bill_pay = pop @cust_bill_pay;
6062 my $error = $cust_bill_pay->delete;
6066 my $cust_refund = new FS::cust_refund ( {
6067 'custnum' => $self->custnum,
6068 'paynum' => $options{'paynum'},
6069 'refund' => $amount,
6071 'payby' => $bop_method2payby{$options{method}},
6072 'payinfo' => $payinfo,
6073 'paybatch' => $paybatch,
6074 'reason' => $options{'reason'} || 'card or ACH refund',
6076 my $error = $cust_refund->insert;
6078 $cust_refund->paynum(''); #try again with no specific paynum
6079 my $error2 = $cust_refund->insert;
6081 # gah, even with transactions.
6082 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
6083 "error inserting refund ($processor): $error2".
6084 " (previously tried insert with paynum #$options{'paynum'}" .
6095 =item batch_card OPTION => VALUE...
6097 Adds a payment for this invoice to the pending credit card batch (see
6098 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
6099 runs the payment using a realtime gateway.
6104 my ($self, %options) = @_;
6107 if (exists($options{amount})) {
6108 $amount = $options{amount};
6110 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
6112 return '' unless $amount > 0;
6114 my $invnum = delete $options{invnum};
6115 my $payby = $options{invnum} || $self->payby; #dubious
6117 if ($options{'realtime'}) {
6118 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
6124 my $oldAutoCommit = $FS::UID::AutoCommit;
6125 local $FS::UID::AutoCommit = 0;
6128 #this needs to handle mysql as well as Pg, like svc_acct.pm
6129 #(make it into a common function if folks need to do batching with mysql)
6130 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
6131 or return "Cannot lock pay_batch: " . $dbh->errstr;
6135 'payby' => FS::payby->payby2payment($payby),
6138 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
6140 unless ( $pay_batch ) {
6141 $pay_batch = new FS::pay_batch \%pay_batch;
6142 my $error = $pay_batch->insert;
6144 $dbh->rollback if $oldAutoCommit;
6145 die "error creating new batch: $error\n";
6149 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
6150 'batchnum' => $pay_batch->batchnum,
6151 'custnum' => $self->custnum,
6154 foreach (qw( address1 address2 city state zip country payby payinfo paydate
6156 $options{$_} = '' unless exists($options{$_});
6159 my $cust_pay_batch = new FS::cust_pay_batch ( {
6160 'batchnum' => $pay_batch->batchnum,
6161 'invnum' => $invnum || 0, # is there a better value?
6162 # this field should be
6164 # cust_bill_pay_batch now
6165 'custnum' => $self->custnum,
6166 'last' => $self->getfield('last'),
6167 'first' => $self->getfield('first'),
6168 'address1' => $options{address1} || $self->address1,
6169 'address2' => $options{address2} || $self->address2,
6170 'city' => $options{city} || $self->city,
6171 'state' => $options{state} || $self->state,
6172 'zip' => $options{zip} || $self->zip,
6173 'country' => $options{country} || $self->country,
6174 'payby' => $options{payby} || $self->payby,
6175 'payinfo' => $options{payinfo} || $self->payinfo,
6176 'exp' => $options{paydate} || $self->paydate,
6177 'payname' => $options{payname} || $self->payname,
6178 'amount' => $amount, # consolidating
6181 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
6182 if $old_cust_pay_batch;
6185 if ($old_cust_pay_batch) {
6186 $error = $cust_pay_batch->replace($old_cust_pay_batch)
6188 $error = $cust_pay_batch->insert;
6192 $dbh->rollback if $oldAutoCommit;
6196 my $unapplied = $self->total_unapplied_credits
6197 + $self->total_unapplied_payments
6198 + $self->in_transit_payments;
6199 foreach my $cust_bill ($self->open_cust_bill) {
6200 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
6201 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
6202 'invnum' => $cust_bill->invnum,
6203 'paybatchnum' => $cust_pay_batch->paybatchnum,
6204 'amount' => $cust_bill->owed,
6207 if ($unapplied >= $cust_bill_pay_batch->amount){
6208 $unapplied -= $cust_bill_pay_batch->amount;
6211 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
6212 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
6214 $error = $cust_bill_pay_batch->insert;
6216 $dbh->rollback if $oldAutoCommit;
6221 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6225 =item apply_payments_and_credits [ OPTION => VALUE ... ]
6227 Applies unapplied payments and credits.
6229 In most cases, this new method should be used in place of sequential
6230 apply_payments and apply_credits methods.
6232 A hash of optional arguments may be passed. Currently "manual" is supported.
6233 If true, a payment receipt is sent instead of a statement when
6234 'payment_receipt_email' configuration option is set.
6236 If there is an error, returns the error, otherwise returns false.
6240 sub apply_payments_and_credits {
6241 my( $self, %options ) = @_;
6243 local $SIG{HUP} = 'IGNORE';
6244 local $SIG{INT} = 'IGNORE';
6245 local $SIG{QUIT} = 'IGNORE';
6246 local $SIG{TERM} = 'IGNORE';
6247 local $SIG{TSTP} = 'IGNORE';
6248 local $SIG{PIPE} = 'IGNORE';
6250 my $oldAutoCommit = $FS::UID::AutoCommit;
6251 local $FS::UID::AutoCommit = 0;
6254 $self->select_for_update; #mutex
6256 foreach my $cust_bill ( $self->open_cust_bill ) {
6257 my $error = $cust_bill->apply_payments_and_credits(%options);
6259 $dbh->rollback if $oldAutoCommit;
6260 return "Error applying: $error";
6264 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6269 =item apply_credits OPTION => VALUE ...
6271 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
6272 to outstanding invoice balances in chronological order (or reverse
6273 chronological order if the I<order> option is set to B<newest>) and returns the
6274 value of any remaining unapplied credits available for refund (see
6275 L<FS::cust_refund>).
6277 Dies if there is an error.
6285 local $SIG{HUP} = 'IGNORE';
6286 local $SIG{INT} = 'IGNORE';
6287 local $SIG{QUIT} = 'IGNORE';
6288 local $SIG{TERM} = 'IGNORE';
6289 local $SIG{TSTP} = 'IGNORE';
6290 local $SIG{PIPE} = 'IGNORE';
6292 my $oldAutoCommit = $FS::UID::AutoCommit;
6293 local $FS::UID::AutoCommit = 0;
6296 $self->select_for_update; #mutex
6298 unless ( $self->total_unapplied_credits ) {
6299 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6303 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
6304 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
6306 my @invoices = $self->open_cust_bill;
6307 @invoices = sort { $b->_date <=> $a->_date } @invoices
6308 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
6310 if ( $conf->exists('pkg-balances') ) {
6311 # limit @credits to those w/ a pkgnum grepped from $self
6313 foreach my $i (@invoices) {
6314 foreach my $li ( $i->cust_bill_pkg ) {
6315 $pkgnums{$li->pkgnum} = 1;
6318 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
6323 foreach my $cust_bill ( @invoices ) {
6325 if ( !defined($credit) || $credit->credited == 0) {
6326 $credit = pop @credits or last;
6330 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
6331 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
6333 $owed = $cust_bill->owed;
6335 unless ( $owed > 0 ) {
6336 push @credits, $credit;
6340 my $amount = min( $credit->credited, $owed );
6342 my $cust_credit_bill = new FS::cust_credit_bill ( {
6343 'crednum' => $credit->crednum,
6344 'invnum' => $cust_bill->invnum,
6345 'amount' => $amount,
6347 $cust_credit_bill->pkgnum( $credit->pkgnum )
6348 if $conf->exists('pkg-balances') && $credit->pkgnum;
6349 my $error = $cust_credit_bill->insert;
6351 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6355 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6359 my $total_unapplied_credits = $self->total_unapplied_credits;
6361 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6363 return $total_unapplied_credits;
6366 =item apply_payments [ OPTION => VALUE ... ]
6368 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
6369 to outstanding invoice balances in chronological order.
6371 #and returns the value of any remaining unapplied payments.
6373 A hash of optional arguments may be passed. Currently "manual" is supported.
6374 If true, a payment receipt is sent instead of a statement when
6375 'payment_receipt_email' configuration option is set.
6378 Dies if there is an error.
6382 sub apply_payments {
6383 my( $self, %options ) = @_;
6385 local $SIG{HUP} = 'IGNORE';
6386 local $SIG{INT} = 'IGNORE';
6387 local $SIG{QUIT} = 'IGNORE';
6388 local $SIG{TERM} = 'IGNORE';
6389 local $SIG{TSTP} = 'IGNORE';
6390 local $SIG{PIPE} = 'IGNORE';
6392 my $oldAutoCommit = $FS::UID::AutoCommit;
6393 local $FS::UID::AutoCommit = 0;
6396 $self->select_for_update; #mutex
6400 my @payments = sort { $b->_date <=> $a->_date }
6401 grep { $_->unapplied > 0 }
6404 my @invoices = sort { $a->_date <=> $b->_date}
6405 grep { $_->owed > 0 }
6408 if ( $conf->exists('pkg-balances') ) {
6409 # limit @payments to those w/ a pkgnum grepped from $self
6411 foreach my $i (@invoices) {
6412 foreach my $li ( $i->cust_bill_pkg ) {
6413 $pkgnums{$li->pkgnum} = 1;
6416 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
6421 foreach my $cust_bill ( @invoices ) {
6423 if ( !defined($payment) || $payment->unapplied == 0 ) {
6424 $payment = pop @payments or last;
6428 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
6429 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
6431 $owed = $cust_bill->owed;
6433 unless ( $owed > 0 ) {
6434 push @payments, $payment;
6438 my $amount = min( $payment->unapplied, $owed );
6440 my $cust_bill_pay = new FS::cust_bill_pay ( {
6441 'paynum' => $payment->paynum,
6442 'invnum' => $cust_bill->invnum,
6443 'amount' => $amount,
6445 $cust_bill_pay->pkgnum( $payment->pkgnum )
6446 if $conf->exists('pkg-balances') && $payment->pkgnum;
6447 my $error = $cust_bill_pay->insert(%options);
6449 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6453 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6457 my $total_unapplied_payments = $self->total_unapplied_payments;
6459 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6461 return $total_unapplied_payments;
6466 Returns the total owed for this customer on all invoices
6467 (see L<FS::cust_bill/owed>).
6473 $self->total_owed_date(2145859200); #12/31/2037
6476 =item total_owed_date TIME
6478 Returns the total owed for this customer on all invoices with date earlier than
6479 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6480 see L<Time::Local> and L<Date::Parse> for conversion functions.
6484 sub total_owed_date {
6488 # my $custnum = $self->custnum;
6490 # my $owed_sql = FS::cust_bill->owed_sql;
6493 # SELECT SUM($owed_sql) FROM cust_bill
6494 # WHERE custnum = $custnum
6495 # AND _date <= $time
6498 # my $sth = dbh->prepare($sql) or die dbh->errstr;
6499 # $sth->execute() or die $sth->errstr;
6501 # return sprintf( '%.2f', $sth->fetchrow_arrayref->[0] );
6504 foreach my $cust_bill (
6505 grep { $_->_date <= $time }
6506 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6508 $total_bill += $cust_bill->owed;
6510 sprintf( "%.2f", $total_bill );
6514 =item total_owed_pkgnum PKGNUM
6516 Returns the total owed on all invoices for this customer's specific package
6517 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
6521 sub total_owed_pkgnum {
6522 my( $self, $pkgnum ) = @_;
6523 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
6526 =item total_owed_date_pkgnum TIME PKGNUM
6528 Returns the total owed for this customer's specific package when using
6529 experimental package balances on all invoices with date earlier than
6530 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6531 see L<Time::Local> and L<Date::Parse> for conversion functions.
6535 sub total_owed_date_pkgnum {
6536 my( $self, $time, $pkgnum ) = @_;
6539 foreach my $cust_bill (
6540 grep { $_->_date <= $time }
6541 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6543 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
6545 sprintf( "%.2f", $total_bill );
6551 Returns the total amount of all payments.
6558 $total += $_->paid foreach $self->cust_pay;
6559 sprintf( "%.2f", $total );
6562 =item total_unapplied_credits
6564 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6565 customer. See L<FS::cust_credit/credited>.
6567 =item total_credited
6569 Old name for total_unapplied_credits. Don't use.
6573 sub total_credited {
6574 #carp "total_credited deprecated, use total_unapplied_credits";
6575 shift->total_unapplied_credits(@_);
6578 sub total_unapplied_credits {
6580 my $total_credit = 0;
6581 $total_credit += $_->credited foreach $self->cust_credit;
6582 sprintf( "%.2f", $total_credit );
6585 =item total_unapplied_credits_pkgnum PKGNUM
6587 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6588 customer. See L<FS::cust_credit/credited>.
6592 sub total_unapplied_credits_pkgnum {
6593 my( $self, $pkgnum ) = @_;
6594 my $total_credit = 0;
6595 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
6596 sprintf( "%.2f", $total_credit );
6600 =item total_unapplied_payments
6602 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
6603 See L<FS::cust_pay/unapplied>.
6607 sub total_unapplied_payments {
6609 my $total_unapplied = 0;
6610 $total_unapplied += $_->unapplied foreach $self->cust_pay;
6611 sprintf( "%.2f", $total_unapplied );
6614 =item total_unapplied_payments_pkgnum PKGNUM
6616 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
6617 specific package when using experimental package balances. See
6618 L<FS::cust_pay/unapplied>.
6622 sub total_unapplied_payments_pkgnum {
6623 my( $self, $pkgnum ) = @_;
6624 my $total_unapplied = 0;
6625 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
6626 sprintf( "%.2f", $total_unapplied );
6630 =item total_unapplied_refunds
6632 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
6633 customer. See L<FS::cust_refund/unapplied>.
6637 sub total_unapplied_refunds {
6639 my $total_unapplied = 0;
6640 $total_unapplied += $_->unapplied foreach $self->cust_refund;
6641 sprintf( "%.2f", $total_unapplied );
6646 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6647 total_unapplied_credits minus total_unapplied_payments).
6655 + $self->total_unapplied_refunds
6656 - $self->total_unapplied_credits
6657 - $self->total_unapplied_payments
6661 =item balance_date TIME
6663 Returns the balance for this customer, only considering invoices with date
6664 earlier than TIME (total_owed_date minus total_credited minus
6665 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
6666 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
6675 $self->total_owed_date($time)
6676 + $self->total_unapplied_refunds
6677 - $self->total_unapplied_credits
6678 - $self->total_unapplied_payments
6682 =item balance_pkgnum PKGNUM
6684 Returns the balance for this customer's specific package when using
6685 experimental package balances (total_owed plus total_unrefunded, minus
6686 total_unapplied_credits minus total_unapplied_payments)
6690 sub balance_pkgnum {
6691 my( $self, $pkgnum ) = @_;
6694 $self->total_owed_pkgnum($pkgnum)
6695 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6696 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
6697 - $self->total_unapplied_credits_pkgnum($pkgnum)
6698 - $self->total_unapplied_payments_pkgnum($pkgnum)
6702 =item in_transit_payments
6704 Returns the total of requests for payments for this customer pending in
6705 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
6709 sub in_transit_payments {
6711 my $in_transit_payments = 0;
6712 foreach my $pay_batch ( qsearch('pay_batch', {
6715 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6716 'batchnum' => $pay_batch->batchnum,
6717 'custnum' => $self->custnum,
6719 $in_transit_payments += $cust_pay_batch->amount;
6722 sprintf( "%.2f", $in_transit_payments );
6727 Returns a hash of useful information for making a payment.
6737 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6738 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6739 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6743 For credit card transactions:
6755 For electronic check transactions:
6770 $return{balance} = $self->balance;
6772 $return{payname} = $self->payname
6773 || ( $self->first. ' '. $self->get('last') );
6775 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6777 $return{payby} = $self->payby;
6778 $return{stateid_state} = $self->stateid_state;
6780 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6781 $return{card_type} = cardtype($self->payinfo);
6782 $return{payinfo} = $self->paymask;
6784 @return{'month', 'year'} = $self->paydate_monthyear;
6788 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6789 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6790 $return{payinfo1} = $payinfo1;
6791 $return{payinfo2} = $payinfo2;
6792 $return{paytype} = $self->paytype;
6793 $return{paystate} = $self->paystate;
6797 #doubleclick protection
6799 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6805 =item paydate_monthyear
6807 Returns a two-element list consisting of the month and year of this customer's
6808 paydate (credit card expiration date for CARD customers)
6812 sub paydate_monthyear {
6814 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6816 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6823 =item tax_exemption TAXNAME
6828 my( $self, $taxname ) = @_;
6830 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6831 'taxname' => $taxname,
6836 =item cust_main_exemption
6840 sub cust_main_exemption {
6842 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6845 =item invoicing_list [ ARRAYREF ]
6847 If an arguement is given, sets these email addresses as invoice recipients
6848 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
6849 (except as warnings), so use check_invoicing_list first.
6851 Returns a list of email addresses (with svcnum entries expanded).
6853 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
6854 check it without disturbing anything by passing nothing.
6856 This interface may change in the future.
6860 sub invoicing_list {
6861 my( $self, $arrayref ) = @_;
6864 my @cust_main_invoice;
6865 if ( $self->custnum ) {
6866 @cust_main_invoice =
6867 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6869 @cust_main_invoice = ();
6871 foreach my $cust_main_invoice ( @cust_main_invoice ) {
6872 #warn $cust_main_invoice->destnum;
6873 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6874 #warn $cust_main_invoice->destnum;
6875 my $error = $cust_main_invoice->delete;
6876 warn $error if $error;
6879 if ( $self->custnum ) {
6880 @cust_main_invoice =
6881 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6883 @cust_main_invoice = ();
6885 my %seen = map { $_->address => 1 } @cust_main_invoice;
6886 foreach my $address ( @{$arrayref} ) {
6887 next if exists $seen{$address} && $seen{$address};
6888 $seen{$address} = 1;
6889 my $cust_main_invoice = new FS::cust_main_invoice ( {
6890 'custnum' => $self->custnum,
6893 my $error = $cust_main_invoice->insert;
6894 warn $error if $error;
6898 if ( $self->custnum ) {
6900 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6907 =item check_invoicing_list ARRAYREF
6909 Checks these arguements as valid input for the invoicing_list method. If there
6910 is an error, returns the error, otherwise returns false.
6914 sub check_invoicing_list {
6915 my( $self, $arrayref ) = @_;
6917 foreach my $address ( @$arrayref ) {
6919 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6920 return 'Can\'t add FAX invoice destination with a blank FAX number.';
6923 my $cust_main_invoice = new FS::cust_main_invoice ( {
6924 'custnum' => $self->custnum,
6927 my $error = $self->custnum
6928 ? $cust_main_invoice->check
6929 : $cust_main_invoice->checkdest
6931 return $error if $error;
6935 return "Email address required"
6936 if $conf->exists('cust_main-require_invoicing_list_email')
6937 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6942 =item set_default_invoicing_list
6944 Sets the invoicing list to all accounts associated with this customer,
6945 overwriting any previous invoicing list.
6949 sub set_default_invoicing_list {
6951 $self->invoicing_list($self->all_emails);
6956 Returns the email addresses of all accounts provisioned for this customer.
6963 foreach my $cust_pkg ( $self->all_pkgs ) {
6964 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6966 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6967 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6969 $list{$_}=1 foreach map { $_->email } @svc_acct;
6974 =item invoicing_list_addpost
6976 Adds postal invoicing to this customer. If this customer is already configured
6977 to receive postal invoices, does nothing.
6981 sub invoicing_list_addpost {
6983 return if grep { $_ eq 'POST' } $self->invoicing_list;
6984 my @invoicing_list = $self->invoicing_list;
6985 push @invoicing_list, 'POST';
6986 $self->invoicing_list(\@invoicing_list);
6989 =item invoicing_list_emailonly
6991 Returns the list of email invoice recipients (invoicing_list without non-email
6992 destinations such as POST and FAX).
6996 sub invoicing_list_emailonly {
6998 warn "$me invoicing_list_emailonly called"
7000 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
7003 =item invoicing_list_emailonly_scalar
7005 Returns the list of email invoice recipients (invoicing_list without non-email
7006 destinations such as POST and FAX) as a comma-separated scalar.
7010 sub invoicing_list_emailonly_scalar {
7012 warn "$me invoicing_list_emailonly_scalar called"
7014 join(', ', $self->invoicing_list_emailonly);
7017 =item referral_custnum_cust_main
7019 Returns the customer who referred this customer (or the empty string, if
7020 this customer was not referred).
7022 Note the difference with referral_cust_main method: This method,
7023 referral_custnum_cust_main returns the single customer (if any) who referred
7024 this customer, while referral_cust_main returns an array of customers referred
7029 sub referral_custnum_cust_main {
7031 return '' unless $self->referral_custnum;
7032 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
7035 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
7037 Returns an array of customers referred by this customer (referral_custnum set
7038 to this custnum). If DEPTH is given, recurses up to the given depth, returning
7039 customers referred by customers referred by this customer and so on, inclusive.
7040 The default behavior is DEPTH 1 (no recursion).
7042 Note the difference with referral_custnum_cust_main method: This method,
7043 referral_cust_main, returns an array of customers referred BY this customer,
7044 while referral_custnum_cust_main returns the single customer (if any) who
7045 referred this customer.
7049 sub referral_cust_main {
7051 my $depth = @_ ? shift : 1;
7052 my $exclude = @_ ? shift : {};
7055 map { $exclude->{$_->custnum}++; $_; }
7056 grep { ! $exclude->{ $_->custnum } }
7057 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
7061 map { $_->referral_cust_main($depth-1, $exclude) }
7068 =item referral_cust_main_ncancelled
7070 Same as referral_cust_main, except only returns customers with uncancelled
7075 sub referral_cust_main_ncancelled {
7077 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
7080 =item referral_cust_pkg [ DEPTH ]
7082 Like referral_cust_main, except returns a flat list of all unsuspended (and
7083 uncancelled) packages for each customer. The number of items in this list may
7084 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
7088 sub referral_cust_pkg {
7090 my $depth = @_ ? shift : 1;
7092 map { $_->unsuspended_pkgs }
7093 grep { $_->unsuspended_pkgs }
7094 $self->referral_cust_main($depth);
7097 =item referring_cust_main
7099 Returns the single cust_main record for the customer who referred this customer
7100 (referral_custnum), or false.
7104 sub referring_cust_main {
7106 return '' unless $self->referral_custnum;
7107 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
7110 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
7112 Applies a credit to this customer. If there is an error, returns the error,
7113 otherwise returns false.
7115 REASON can be a text string, an FS::reason object, or a scalar reference to
7116 a reasonnum. If a text string, it will be automatically inserted as a new
7117 reason, and a 'reason_type' option must be passed to indicate the
7118 FS::reason_type for the new reason.
7120 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
7122 Any other options are passed to FS::cust_credit::insert.
7127 my( $self, $amount, $reason, %options ) = @_;
7129 my $cust_credit = new FS::cust_credit {
7130 'custnum' => $self->custnum,
7131 'amount' => $amount,
7134 if ( ref($reason) ) {
7136 if ( ref($reason) eq 'SCALAR' ) {
7137 $cust_credit->reasonnum( $$reason );
7139 $cust_credit->reasonnum( $reason->reasonnum );
7143 $cust_credit->set('reason', $reason)
7146 $cust_credit->addlinfo( delete $options{'addlinfo'} )
7147 if exists($options{'addlinfo'});
7149 $cust_credit->insert(%options);
7153 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
7155 Creates a one-time charge for this customer. If there is an error, returns
7156 the error, otherwise returns false.
7158 New-style, with a hashref of options:
7160 my $error = $cust_main->charge(
7164 'start_date' => str2time('7/4/2009'),
7165 'pkg' => 'Description',
7166 'comment' => 'Comment',
7167 'additional' => [], #extra invoice detail
7168 'classnum' => 1, #pkg_class
7170 'setuptax' => '', # or 'Y' for tax exempt
7173 'taxclass' => 'Tax class',
7176 'taxproduct' => 2, #part_pkg_taxproduct
7177 'override' => {}, #XXX describe
7179 #will be filled in with the new object
7180 'cust_pkg_ref' => \$cust_pkg,
7182 #generate an invoice immediately
7184 'invoice_terms' => '', #with these terms
7190 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
7196 my ( $amount, $quantity, $start_date, $classnum );
7197 my ( $pkg, $comment, $additional );
7198 my ( $setuptax, $taxclass ); #internal taxes
7199 my ( $taxproduct, $override ); #vendor (CCH) taxes
7200 my $cust_pkg_ref = '';
7201 my ( $bill_now, $invoice_terms ) = ( 0, '' );
7202 if ( ref( $_[0] ) ) {
7203 $amount = $_[0]->{amount};
7204 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
7205 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
7206 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
7207 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
7208 : '$'. sprintf("%.2f",$amount);
7209 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
7210 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
7211 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
7212 $additional = $_[0]->{additional} || [];
7213 $taxproduct = $_[0]->{taxproductnum};
7214 $override = { '' => $_[0]->{tax_override} };
7215 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
7216 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
7217 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
7222 $pkg = @_ ? shift : 'One-time charge';
7223 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
7225 $taxclass = @_ ? shift : '';
7229 local $SIG{HUP} = 'IGNORE';
7230 local $SIG{INT} = 'IGNORE';
7231 local $SIG{QUIT} = 'IGNORE';
7232 local $SIG{TERM} = 'IGNORE';
7233 local $SIG{TSTP} = 'IGNORE';
7234 local $SIG{PIPE} = 'IGNORE';
7236 my $oldAutoCommit = $FS::UID::AutoCommit;
7237 local $FS::UID::AutoCommit = 0;
7240 my $part_pkg = new FS::part_pkg ( {
7242 'comment' => $comment,
7246 'classnum' => $classnum ? $classnum : '',
7247 'setuptax' => $setuptax,
7248 'taxclass' => $taxclass,
7249 'taxproductnum' => $taxproduct,
7252 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
7253 ( 0 .. @$additional - 1 )
7255 'additional_count' => scalar(@$additional),
7256 'setup_fee' => $amount,
7259 my $error = $part_pkg->insert( options => \%options,
7260 tax_overrides => $override,
7263 $dbh->rollback if $oldAutoCommit;
7267 my $pkgpart = $part_pkg->pkgpart;
7268 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
7269 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
7270 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
7271 $error = $type_pkgs->insert;
7273 $dbh->rollback if $oldAutoCommit;
7278 my $cust_pkg = new FS::cust_pkg ( {
7279 'custnum' => $self->custnum,
7280 'pkgpart' => $pkgpart,
7281 'quantity' => $quantity,
7282 'start_date' => $start_date,
7285 $error = $cust_pkg->insert;
7287 $dbh->rollback if $oldAutoCommit;
7289 } elsif ( $cust_pkg_ref ) {
7290 ${$cust_pkg_ref} = $cust_pkg;
7294 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
7295 'pkg_list' => [ $cust_pkg ],
7298 $dbh->rollback if $oldAutoCommit;
7303 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
7308 #=item charge_postal_fee
7310 #Applies a one time charge this customer. If there is an error,
7311 #returns the error, returns the cust_pkg charge object or false
7312 #if there was no charge.
7316 # This should be a customer event. For that to work requires that bill
7317 # also be a customer event.
7319 sub charge_postal_fee {
7322 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
7323 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
7325 my $cust_pkg = new FS::cust_pkg ( {
7326 'custnum' => $self->custnum,
7327 'pkgpart' => $pkgpart,
7331 my $error = $cust_pkg->insert;
7332 $error ? $error : $cust_pkg;
7337 Returns all the invoices (see L<FS::cust_bill>) for this customer.
7343 map { $_ } #return $self->num_cust_bill unless wantarray;
7344 sort { $a->_date <=> $b->_date }
7345 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
7348 =item open_cust_bill
7350 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
7355 sub open_cust_bill {
7359 'table' => 'cust_bill',
7360 'hashref' => { 'custnum' => $self->custnum, },
7361 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
7362 'order_by' => 'ORDER BY _date ASC',
7367 =item cust_statements
7369 Returns all the statements (see L<FS::cust_statement>) for this customer.
7373 sub cust_statement {
7375 map { $_ } #return $self->num_cust_statement unless wantarray;
7376 sort { $a->_date <=> $b->_date }
7377 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
7382 Returns all the credits (see L<FS::cust_credit>) for this customer.
7388 map { $_ } #return $self->num_cust_credit unless wantarray;
7389 sort { $a->_date <=> $b->_date }
7390 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
7393 =item cust_credit_pkgnum
7395 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
7396 package when using experimental package balances.
7400 sub cust_credit_pkgnum {
7401 my( $self, $pkgnum ) = @_;
7402 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
7403 sort { $a->_date <=> $b->_date }
7404 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
7405 'pkgnum' => $pkgnum,
7412 Returns all the payments (see L<FS::cust_pay>) for this customer.
7418 return $self->num_cust_pay unless wantarray;
7419 sort { $a->_date <=> $b->_date }
7420 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
7425 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
7426 called automatically when the cust_pay method is used in a scalar context.
7432 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
7433 my $sth = dbh->prepare($sql) or die dbh->errstr;
7434 $sth->execute($self->custnum) or die $sth->errstr;
7435 $sth->fetchrow_arrayref->[0];
7438 =item cust_pay_pkgnum
7440 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
7441 package when using experimental package balances.
7445 sub cust_pay_pkgnum {
7446 my( $self, $pkgnum ) = @_;
7447 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
7448 sort { $a->_date <=> $b->_date }
7449 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
7450 'pkgnum' => $pkgnum,
7457 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
7463 map { $_ } #return $self->num_cust_pay_void unless wantarray;
7464 sort { $a->_date <=> $b->_date }
7465 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
7468 =item cust_pay_batch
7470 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
7474 sub cust_pay_batch {
7476 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
7477 sort { $a->paybatchnum <=> $b->paybatchnum }
7478 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
7481 =item cust_pay_pending
7483 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
7484 (without status "done").
7488 sub cust_pay_pending {
7490 return $self->num_cust_pay_pending unless wantarray;
7491 sort { $a->_date <=> $b->_date }
7492 qsearch( 'cust_pay_pending', {
7493 'custnum' => $self->custnum,
7494 'status' => { op=>'!=', value=>'done' },
7499 =item num_cust_pay_pending
7501 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7502 customer (without status "done"). Also called automatically when the
7503 cust_pay_pending method is used in a scalar context.
7507 sub num_cust_pay_pending {
7509 my $sql = " SELECT COUNT(*) FROM cust_pay_pending ".
7510 " WHERE custnum = ? AND status != 'done' ";
7511 my $sth = dbh->prepare($sql) or die dbh->errstr;
7512 $sth->execute($self->custnum) or die $sth->errstr;
7513 $sth->fetchrow_arrayref->[0];
7518 Returns all the refunds (see L<FS::cust_refund>) for this customer.
7524 map { $_ } #return $self->num_cust_refund unless wantarray;
7525 sort { $a->_date <=> $b->_date }
7526 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
7529 =item display_custnum
7531 Returns the displayed customer number for this customer: agent_custid if
7532 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
7536 sub display_custnum {
7538 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
7539 return $self->agent_custid;
7541 return $self->custnum;
7547 Returns a name string for this customer, either "Company (Last, First)" or
7554 my $name = $self->contact;
7555 $name = $self->company. " ($name)" if $self->company;
7561 Returns a name string for this (service/shipping) contact, either
7562 "Company (Last, First)" or "Last, First".
7568 if ( $self->get('ship_last') ) {
7569 my $name = $self->ship_contact;
7570 $name = $self->ship_company. " ($name)" if $self->ship_company;
7579 Returns a name string for this customer, either "Company" or "First Last".
7585 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
7588 =item ship_name_short
7590 Returns a name string for this (service/shipping) contact, either "Company"
7595 sub ship_name_short {
7597 if ( $self->get('ship_last') ) {
7598 $self->ship_company !~ /^\s*$/
7599 ? $self->ship_company
7600 : $self->ship_contact_firstlast;
7602 $self->name_company_or_firstlast;
7608 Returns this customer's full (billing) contact name only, "Last, First"
7614 $self->get('last'). ', '. $self->first;
7619 Returns this customer's full (shipping) contact name only, "Last, First"
7625 $self->get('ship_last')
7626 ? $self->get('ship_last'). ', '. $self->ship_first
7630 =item contact_firstlast
7632 Returns this customers full (billing) contact name only, "First Last".
7636 sub contact_firstlast {
7638 $self->first. ' '. $self->get('last');
7641 =item ship_contact_firstlast
7643 Returns this customer's full (shipping) contact name only, "First Last".
7647 sub ship_contact_firstlast {
7649 $self->get('ship_last')
7650 ? $self->first. ' '. $self->get('ship_last')
7651 : $self->contact_firstlast;
7656 Returns this customer's full country name
7662 code2country($self->country);
7665 =item geocode DATA_VENDOR
7667 Returns a value for the customer location as encoded by DATA_VENDOR.
7668 Currently this only makes sense for "CCH" as DATA_VENDOR.
7673 my ($self, $data_vendor) = (shift, shift); #always cch for now
7675 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
7676 return $geocode if $geocode;
7678 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7682 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7683 if $self->country eq 'US';
7685 #CCH specific location stuff
7686 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7688 my @cust_tax_location =
7690 'table' => 'cust_tax_location',
7691 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7692 'extra_sql' => $extra_sql,
7693 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
7696 $geocode = $cust_tax_location[0]->geocode
7697 if scalar(@cust_tax_location);
7706 Returns a status string for this customer, currently:
7710 =item prospect - No packages have ever been ordered
7712 =item active - One or more recurring packages is active
7714 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7716 =item suspended - All non-cancelled recurring packages are suspended
7718 =item cancelled - All recurring packages are cancelled
7724 sub status { shift->cust_status(@_); }
7728 for my $status (qw( prospect active inactive suspended cancelled )) {
7729 my $method = $status.'_sql';
7730 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7731 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7732 $sth->execute( ($self->custnum) x $numnum )
7733 or die "Error executing 'SELECT $sql': ". $sth->errstr;
7734 return $status if $sth->fetchrow_arrayref->[0];
7738 =item ucfirst_cust_status
7740 =item ucfirst_status
7742 Returns the status with the first character capitalized.
7746 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7748 sub ucfirst_cust_status {
7750 ucfirst($self->cust_status);
7755 Returns a hex triplet color string for this customer's status.
7759 use vars qw(%statuscolor);
7760 tie %statuscolor, 'Tie::IxHash',
7761 'prospect' => '7e0079', #'000000', #black? naw, purple
7762 'active' => '00CC00', #green
7763 'inactive' => '0000CC', #blue
7764 'suspended' => 'FF9900', #yellow
7765 'cancelled' => 'FF0000', #red
7768 sub statuscolor { shift->cust_statuscolor(@_); }
7770 sub cust_statuscolor {
7772 $statuscolor{$self->cust_status};
7777 Returns an array of hashes representing the customer's RT tickets.
7784 my $num = $conf->config('cust_main-max_tickets') || 10;
7787 if ( $conf->config('ticket_system') ) {
7788 unless ( $conf->config('ticket_system-custom_priority_field') ) {
7790 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7794 foreach my $priority (
7795 $conf->config('ticket_system-custom_priority_field-values'), ''
7797 last if scalar(@tickets) >= $num;
7799 @{ FS::TicketSystem->customer_tickets( $self->custnum,
7800 $num - scalar(@tickets),
7810 # Return services representing svc_accts in customer support packages
7811 sub support_services {
7813 my %packages = map { $_ => 1 } $conf->config('support_packages');
7815 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7816 grep { $_->part_svc->svcdb eq 'svc_acct' }
7817 map { $_->cust_svc }
7818 grep { exists $packages{ $_->pkgpart } }
7819 $self->ncancelled_pkgs;
7823 # Return a list of latitude/longitude for one of the services (if any)
7824 sub service_coordinates {
7828 grep { $_->latitude && $_->longitude }
7830 map { $_->cust_svc }
7831 $self->ncancelled_pkgs;
7833 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7838 =head1 CLASS METHODS
7844 Class method that returns the list of possible status strings for customers
7845 (see L<the status method|/status>). For example:
7847 @statuses = FS::cust_main->statuses();
7852 #my $self = shift; #could be class...
7858 Returns an SQL expression identifying prospective cust_main records (customers
7859 with no packages ever ordered)
7863 use vars qw($select_count_pkgs);
7864 $select_count_pkgs =
7865 "SELECT COUNT(*) FROM cust_pkg
7866 WHERE cust_pkg.custnum = cust_main.custnum";
7868 sub select_count_pkgs_sql {
7872 sub prospect_sql { "
7873 0 = ( $select_count_pkgs )
7878 Returns an SQL expression identifying active cust_main records (customers with
7879 active recurring packages).
7884 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
7890 Returns an SQL expression identifying inactive cust_main records (customers with
7891 no active recurring packages, but otherwise unsuspended/uncancelled).
7895 sub inactive_sql { "
7896 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7898 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7904 Returns an SQL expression identifying suspended cust_main records.
7909 sub suspended_sql { susp_sql(@_); }
7911 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
7913 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7919 Returns an SQL expression identifying cancelled cust_main records.
7923 sub cancelled_sql { cancel_sql(@_); }
7926 my $recurring_sql = FS::cust_pkg->recurring_sql;
7927 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7930 0 < ( $select_count_pkgs )
7931 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
7932 AND 0 = ( $select_count_pkgs AND $recurring_sql
7933 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7935 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7941 =item uncancelled_sql
7943 Returns an SQL expression identifying un-cancelled cust_main records.
7947 sub uncancelled_sql { uncancel_sql(@_); }
7948 sub uncancel_sql { "
7949 ( 0 < ( $select_count_pkgs
7950 AND ( cust_pkg.cancel IS NULL
7951 OR cust_pkg.cancel = 0
7954 OR 0 = ( $select_count_pkgs )
7960 Returns an SQL fragment to retreive the balance.
7965 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7966 WHERE cust_bill.custnum = cust_main.custnum )
7967 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
7968 WHERE cust_pay.custnum = cust_main.custnum )
7969 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
7970 WHERE cust_credit.custnum = cust_main.custnum )
7971 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
7972 WHERE cust_refund.custnum = cust_main.custnum )
7975 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7977 Returns an SQL fragment to retreive the balance for this customer, only
7978 considering invoices with date earlier than START_TIME, and optionally not
7979 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7980 total_unapplied_payments).
7982 Times are specified as SQL fragments or numeric
7983 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7984 L<Date::Parse> for conversion functions. The empty string can be passed
7985 to disable that time constraint completely.
7987 Available options are:
7991 =item unapplied_date
7993 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
7998 set to true to remove all customer comparison clauses, for totals
8003 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
8008 JOIN clause (typically used with the total option)
8014 sub balance_date_sql {
8015 my( $class, $start, $end, %opt ) = @_;
8017 my $owed = FS::cust_bill->owed_sql;
8018 my $unapp_refund = FS::cust_refund->unapplied_sql;
8019 my $unapp_credit = FS::cust_credit->unapplied_sql;
8020 my $unapp_pay = FS::cust_pay->unapplied_sql;
8022 my $j = $opt{'join'} || '';
8024 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
8025 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
8026 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
8027 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
8029 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
8030 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
8031 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
8032 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
8037 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
8039 Returns an SQL fragment to retreive the total unapplied payments for this
8040 customer, only considering invoices with date earlier than START_TIME, and
8041 optionally not later than END_TIME.
8043 Times are specified as SQL fragments or numeric
8044 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
8045 L<Date::Parse> for conversion functions. The empty string can be passed
8046 to disable that time constraint completely.
8048 Available options are:
8052 sub unapplied_payments_date_sql {
8053 my( $class, $start, $end, ) = @_;
8055 my $unapp_pay = FS::cust_pay->unapplied_sql;
8057 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
8058 'unapplied_date'=>1 );
8060 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
8063 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
8065 Helper method for balance_date_sql; name (and usage) subject to change
8066 (suggestions welcome).
8068 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
8069 cust_refund, cust_credit or cust_pay).
8071 If TABLE is "cust_bill" or the unapplied_date option is true, only
8072 considers records with date earlier than START_TIME, and optionally not
8073 later than END_TIME .
8077 sub _money_table_where {
8078 my( $class, $table, $start, $end, %opt ) = @_;
8081 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
8082 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
8083 push @where, "$table._date <= $start" if defined($start) && length($start);
8084 push @where, "$table._date > $end" if defined($end) && length($end);
8086 push @where, @{$opt{'where'}} if $opt{'where'};
8087 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
8093 =item search_sql HASHREF
8097 Returns a qsearch hash expression to search for parameters specified in HREF.
8098 Valid parameters are
8106 =item cancelled_pkgs
8112 listref of start date, end date
8118 =item current_balance
8120 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
8124 =item flattened_pkgs
8133 my ($class, $params) = @_;
8144 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
8146 "cust_main.agentnum = $1";
8153 #prospect active inactive suspended cancelled
8154 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
8155 my $method = $params->{'status'}. '_sql';
8156 #push @where, $class->$method();
8157 push @where, FS::cust_main->$method();
8161 # parse cancelled package checkbox
8166 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
8167 unless $params->{'cancelled_pkgs'};
8170 # parse without census tract checkbox
8173 push @where, "(censustract = '' or censustract is null)"
8174 if $params->{'no_censustract'};
8180 foreach my $field (qw( signupdate )) {
8182 next unless exists($params->{$field});
8184 my($beginning, $ending) = @{$params->{$field}};
8187 "cust_main.$field IS NOT NULL",
8188 "cust_main.$field >= $beginning",
8189 "cust_main.$field <= $ending";
8191 $orderby ||= "ORDER BY cust_main.$field";
8199 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
8201 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
8208 #my $balance_sql = $class->balance_sql();
8209 my $balance_sql = FS::cust_main->balance_sql();
8211 push @where, map { s/current_balance/$balance_sql/; $_ }
8212 @{ $params->{'current_balance'} };
8218 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
8220 "cust_main.custbatch = '$1'";
8224 # setup queries, subs, etc. for the search
8227 $orderby ||= 'ORDER BY custnum';
8229 # here is the agent virtualization
8230 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
8232 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
8234 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
8236 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
8238 my $select = join(', ',
8239 'cust_main.custnum',
8240 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
8243 my(@extra_headers) = ();
8244 my(@extra_fields) = ();
8246 if ($params->{'flattened_pkgs'}) {
8248 if ($dbh->{Driver}->{Name} eq 'Pg') {
8250 $select .= ", array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
8252 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
8253 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
8254 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
8256 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
8257 "omitting packing information from report.";
8260 my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
8262 my $sth = dbh->prepare($header_query) or die dbh->errstr;
8263 $sth->execute() or die $sth->errstr;
8264 my $headerrow = $sth->fetchrow_arrayref;
8265 my $headercount = $headerrow ? $headerrow->[0] : 0;
8266 while($headercount) {
8267 unshift @extra_headers, "Package ". $headercount;
8268 unshift @extra_fields, eval q!sub {my $c = shift;
8269 my @a = split '\|', $c->magic;
8270 my $p = $a[!.--$headercount. q!];
8278 'table' => 'cust_main',
8279 'select' => $select,
8281 'extra_sql' => $extra_sql,
8282 'order_by' => $orderby,
8283 'count_query' => $count_query,
8284 'extra_headers' => \@extra_headers,
8285 'extra_fields' => \@extra_fields,
8290 =item email_search_sql HASHREF
8294 Emails a notice to the specified customers.
8296 Valid parameters are those of the L<search_sql> method, plus the following:
8318 Optional job queue job for status updates.
8322 Returns an error message, or false for success.
8324 If an error occurs during any email, stops the enture send and returns that
8325 error. Presumably if you're getting SMTP errors aborting is better than
8326 retrying everything.
8330 sub email_search_sql {
8331 my($class, $params) = @_;
8333 my $from = delete $params->{from};
8334 my $subject = delete $params->{subject};
8335 my $html_body = delete $params->{html_body};
8336 my $text_body = delete $params->{text_body};
8338 my $job = delete $params->{'job'};
8340 $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
8341 unless ref($params->{'payby'});
8343 my $sql_query = $class->search_sql($params);
8345 my $count_query = delete($sql_query->{'count_query'});
8346 my $count_sth = dbh->prepare($count_query)
8347 or die "Error preparing $count_query: ". dbh->errstr;
8349 or die "Error executing $count_query: ". $count_sth->errstr;
8350 my $count_arrayref = $count_sth->fetchrow_arrayref;
8351 my $num_cust = $count_arrayref->[0];
8353 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
8354 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
8357 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
8359 #eventually order+limit magic to reduce memory use?
8360 foreach my $cust_main ( qsearch($sql_query) ) {
8362 my $to = $cust_main->invoicing_list_emailonly_scalar;
8365 my $error = send_email(
8369 'subject' => $subject,
8370 'html_body' => $html_body,
8371 'text_body' => $text_body,
8374 return $error if $error;
8376 if ( $job ) { #progressbar foo
8378 if ( time - $min_sec > $last ) {
8379 my $error = $job->update_statustext(
8380 int( 100 * $num / $num_cust )
8382 die $error if $error;
8392 use Storable qw(thaw);
8395 sub process_email_search_sql {
8397 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
8399 my $param = thaw(decode_base64(shift));
8400 warn Dumper($param) if $DEBUG;
8402 $param->{'job'} = $job;
8404 $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
8405 unless ref($param->{'payby'});
8407 my $error = FS::cust_main->email_search_sql( $param );
8408 die $error if $error;
8412 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
8414 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
8415 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
8416 appropriate ship_ field is also searched).
8418 Additional options are the same as FS::Record::qsearch
8423 my( $self, $fuzzy, $hash, @opt) = @_;
8428 check_and_rebuild_fuzzyfiles();
8429 foreach my $field ( keys %$fuzzy ) {
8431 my $all = $self->all_X($field);
8432 next unless scalar(@$all);
8435 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
8438 foreach ( keys %match ) {
8439 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
8440 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
8443 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
8446 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
8448 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
8456 Returns a masked version of the named field
8461 my ($self,$field) = @_;
8465 'x'x(length($self->getfield($field))-4).
8466 substr($self->getfield($field), (length($self->getfield($field))-4));
8476 =item smart_search OPTION => VALUE ...
8478 Accepts the following options: I<search>, the string to search for. The string
8479 will be searched for as a customer number, phone number, name or company name,
8480 as an exact, or, in some cases, a substring or fuzzy match (see the source code
8481 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
8482 skip fuzzy matching when an exact match is found.
8484 Any additional options are treated as an additional qualifier on the search
8487 Returns a (possibly empty) array of FS::cust_main objects.
8494 #here is the agent virtualization
8495 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8499 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
8500 my $search = delete $options{'search'};
8501 ( my $alphanum_search = $search ) =~ s/\W//g;
8503 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8505 #false laziness w/Record::ut_phone
8506 my $phonen = "$1-$2-$3";
8507 $phonen .= " x$4" if $4;
8509 push @cust_main, qsearch( {
8510 'table' => 'cust_main',
8511 'hashref' => { %options },
8512 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8514 join(' OR ', map "$_ = '$phonen'",
8515 qw( daytime night fax
8516 ship_daytime ship_night ship_fax )
8519 " AND $agentnums_sql", #agent virtualization
8522 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8523 #try looking for matches with extensions unless one was specified
8525 push @cust_main, qsearch( {
8526 'table' => 'cust_main',
8527 'hashref' => { %options },
8528 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8530 join(' OR ', map "$_ LIKE '$phonen\%'",
8532 ship_daytime ship_night )
8535 " AND $agentnums_sql", #agent virtualization
8540 # custnum search (also try agent_custid), with some tweaking options if your
8541 # legacy cust "numbers" have letters
8544 if ( $search =~ /^\s*(\d+)\s*$/
8545 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8546 && $search =~ /^\s*(\w\w?\d+)\s*$/
8553 if ( $num <= 2147483647 ) { #need a bigint custnum? wow.
8554 push @cust_main, qsearch( {
8555 'table' => 'cust_main',
8556 'hashref' => { 'custnum' => $num, %options },
8557 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8561 push @cust_main, qsearch( {
8562 'table' => 'cust_main',
8563 'hashref' => { 'agent_custid' => $num, %options },
8564 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8567 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8569 my($company, $last, $first) = ( $1, $2, $3 );
8571 # "Company (Last, First)"
8572 #this is probably something a browser remembered,
8573 #so just do an exact search
8575 foreach my $prefix ( '', 'ship_' ) {
8576 push @cust_main, qsearch( {
8577 'table' => 'cust_main',
8578 'hashref' => { $prefix.'first' => $first,
8579 $prefix.'last' => $last,
8580 $prefix.'company' => $company,
8583 'extra_sql' => " AND $agentnums_sql",
8587 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8588 # try (ship_){last,company}
8592 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8593 # # full strings the browser remembers won't work
8594 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8596 use Lingua::EN::NameParse;
8597 my $NameParse = new Lingua::EN::NameParse(
8599 allow_reversed => 1,
8602 my($last, $first) = ( '', '' );
8603 #maybe disable this too and just rely on NameParse?
8604 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8606 ($last, $first) = ( $1, $2 );
8608 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
8609 } elsif ( ! $NameParse->parse($value) ) {
8611 my %name = $NameParse->components;
8612 $first = $name{'given_name_1'};
8613 $last = $name{'surname_1'};
8617 if ( $first && $last ) {
8619 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8622 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8624 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8625 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8628 push @cust_main, qsearch( {
8629 'table' => 'cust_main',
8630 'hashref' => \%options,
8631 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8634 # or it just be something that was typed in... (try that in a sec)
8638 my $q_value = dbh->quote($value);
8641 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8642 $sql .= " ( LOWER(last) = $q_value
8643 OR LOWER(company) = $q_value
8644 OR LOWER(ship_last) = $q_value
8645 OR LOWER(ship_company) = $q_value
8648 push @cust_main, qsearch( {
8649 'table' => 'cust_main',
8650 'hashref' => \%options,
8651 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8654 #no exact match, trying substring/fuzzy
8655 #always do substring & fuzzy (unless they're explicity config'ed off)
8656 #getting complaints searches are not returning enough
8657 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8659 #still some false laziness w/search_sql (was search/cust_main.cgi)
8664 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
8665 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8668 if ( $first && $last ) {
8671 { 'first' => { op=>'ILIKE', value=>"%$first%" },
8672 'last' => { op=>'ILIKE', value=>"%$last%" },
8674 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
8675 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
8682 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
8683 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
8687 foreach my $hashref ( @hashrefs ) {
8689 push @cust_main, qsearch( {
8690 'table' => 'cust_main',
8691 'hashref' => { %$hashref,
8694 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8703 " AND $agentnums_sql", #extra_sql #agent virtualization
8706 if ( $first && $last ) {
8707 push @cust_main, FS::cust_main->fuzzy_search(
8708 { 'last' => $last, #fuzzy hashref
8709 'first' => $first }, #
8713 foreach my $field ( 'last', 'company' ) {
8715 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8722 #eliminate duplicates
8724 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8732 Accepts the following options: I<email>, the email address to search for. The
8733 email address will be searched for as an email invoice destination and as an
8736 #Any additional options are treated as an additional qualifier on the search
8737 #(i.e. I<agentnum>).
8739 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8749 my $email = delete $options{'email'};
8751 #we're only being used by RT at the moment... no agent virtualization yet
8752 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8756 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8758 my ( $user, $domain ) = ( $1, $2 );
8760 warn "$me smart_search: searching for $user in domain $domain"
8766 'table' => 'cust_main_invoice',
8767 'hashref' => { 'dest' => $email },
8774 map $_->cust_svc->cust_pkg,
8776 'table' => 'svc_acct',
8777 'hashref' => { 'username' => $user, },
8779 'AND ( SELECT domain FROM svc_domain
8780 WHERE svc_acct.domsvc = svc_domain.svcnum
8781 ) = '. dbh->quote($domain),
8787 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8789 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8796 =item check_and_rebuild_fuzzyfiles
8800 use vars qw(@fuzzyfields);
8801 @fuzzyfields = ( 'last', 'first', 'company' );
8803 sub check_and_rebuild_fuzzyfiles {
8804 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8805 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8808 =item rebuild_fuzzyfiles
8812 sub rebuild_fuzzyfiles {
8814 use Fcntl qw(:flock);
8816 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8817 mkdir $dir, 0700 unless -d $dir;
8819 foreach my $fuzzy ( @fuzzyfields ) {
8821 open(LOCK,">>$dir/cust_main.$fuzzy")
8822 or die "can't open $dir/cust_main.$fuzzy: $!";
8824 or die "can't lock $dir/cust_main.$fuzzy: $!";
8826 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8827 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8829 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8830 my $sth = dbh->prepare("SELECT $field FROM cust_main".
8831 " WHERE $field != '' AND $field IS NOT NULL");
8832 $sth->execute or die $sth->errstr;
8834 while ( my $row = $sth->fetchrow_arrayref ) {
8835 print CACHE $row->[0]. "\n";
8840 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8842 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8853 my( $self, $field ) = @_;
8854 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8855 open(CACHE,"<$dir/cust_main.$field")
8856 or die "can't open $dir/cust_main.$field: $!";
8857 my @array = map { chomp; $_; } <CACHE>;
8862 =item append_fuzzyfiles LASTNAME COMPANY
8866 sub append_fuzzyfiles {
8867 #my( $first, $last, $company ) = @_;
8869 &check_and_rebuild_fuzzyfiles;
8871 use Fcntl qw(:flock);
8873 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8875 foreach my $field (qw( first last company )) {
8880 open(CACHE,">>$dir/cust_main.$field")
8881 or die "can't open $dir/cust_main.$field: $!";
8882 flock(CACHE,LOCK_EX)
8883 or die "can't lock $dir/cust_main.$field: $!";
8885 print CACHE "$value\n";
8887 flock(CACHE,LOCK_UN)
8888 or die "can't unlock $dir/cust_main.$field: $!";
8903 #warn join('-',keys %$param);
8904 my $fh = $param->{filehandle};
8905 my @fields = @{$param->{fields}};
8907 eval "use Text::CSV_XS;";
8910 my $csv = new Text::CSV_XS;
8917 local $SIG{HUP} = 'IGNORE';
8918 local $SIG{INT} = 'IGNORE';
8919 local $SIG{QUIT} = 'IGNORE';
8920 local $SIG{TERM} = 'IGNORE';
8921 local $SIG{TSTP} = 'IGNORE';
8922 local $SIG{PIPE} = 'IGNORE';
8924 my $oldAutoCommit = $FS::UID::AutoCommit;
8925 local $FS::UID::AutoCommit = 0;
8928 #while ( $columns = $csv->getline($fh) ) {
8930 while ( defined($line=<$fh>) ) {
8932 $csv->parse($line) or do {
8933 $dbh->rollback if $oldAutoCommit;
8934 return "can't parse: ". $csv->error_input();
8937 my @columns = $csv->fields();
8938 #warn join('-',@columns);
8941 foreach my $field ( @fields ) {
8942 $row{$field} = shift @columns;
8945 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
8946 unless ( $cust_main ) {
8947 $dbh->rollback if $oldAutoCommit;
8948 return "unknown custnum $row{'custnum'}";
8951 if ( $row{'amount'} > 0 ) {
8952 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8954 $dbh->rollback if $oldAutoCommit;
8958 } elsif ( $row{'amount'} < 0 ) {
8959 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8962 $dbh->rollback if $oldAutoCommit;
8972 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8974 return "Empty file!" unless $imported;
8980 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8982 Sends a templated email notification to the customer (see L<Text::Template>).
8984 OPTIONS is a hash and may include
8986 I<from> - the email sender (default is invoice_from)
8988 I<to> - comma-separated scalar or arrayref of recipients
8989 (default is invoicing_list)
8991 I<subject> - The subject line of the sent email notification
8992 (default is "Notice from company_name")
8994 I<extra_fields> - a hashref of name/value pairs which will be substituted
8997 The following variables are vavailable in the template.
8999 I<$first> - the customer first name
9000 I<$last> - the customer last name
9001 I<$company> - the customer company
9002 I<$payby> - a description of the method of payment for the customer
9003 # would be nice to use FS::payby::shortname
9004 I<$payinfo> - the account information used to collect for this customer
9005 I<$expdate> - the expiration of the customer payment in seconds from epoch
9010 my ($self, $template, %options) = @_;
9012 return unless $conf->exists($template);
9014 my $from = $conf->config('invoice_from', $self->agentnum)
9015 if $conf->exists('invoice_from', $self->agentnum);
9016 $from = $options{from} if exists($options{from});
9018 my $to = join(',', $self->invoicing_list_emailonly);
9019 $to = $options{to} if exists($options{to});
9021 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
9022 if $conf->exists('company_name', $self->agentnum);
9023 $subject = $options{subject} if exists($options{subject});
9025 my $notify_template = new Text::Template (TYPE => 'ARRAY',
9026 SOURCE => [ map "$_\n",
9027 $conf->config($template)]
9029 or die "can't create new Text::Template object: Text::Template::ERROR";
9030 $notify_template->compile()
9031 or die "can't compile template: Text::Template::ERROR";
9033 $FS::notify_template::_template::company_name =
9034 $conf->config('company_name', $self->agentnum);
9035 $FS::notify_template::_template::company_address =
9036 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
9038 my $paydate = $self->paydate || '2037-12-31';
9039 $FS::notify_template::_template::first = $self->first;
9040 $FS::notify_template::_template::last = $self->last;
9041 $FS::notify_template::_template::company = $self->company;
9042 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
9043 my $payby = $self->payby;
9044 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
9045 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
9047 #credit cards expire at the end of the month/year of their exp date
9048 if ($payby eq 'CARD' || $payby eq 'DCRD') {
9049 $FS::notify_template::_template::payby = 'credit card';
9050 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
9051 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
9053 }elsif ($payby eq 'COMP') {
9054 $FS::notify_template::_template::payby = 'complimentary account';
9056 $FS::notify_template::_template::payby = 'current method';
9058 $FS::notify_template::_template::expdate = $expire_time;
9060 for (keys %{$options{extra_fields}}){
9062 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
9065 send_email(from => $from,
9067 subject => $subject,
9068 body => $notify_template->fill_in( PACKAGE =>
9069 'FS::notify_template::_template' ),
9074 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
9076 Generates a templated notification to the customer (see L<Text::Template>).
9078 OPTIONS is a hash and may include
9080 I<extra_fields> - a hashref of name/value pairs which will be substituted
9081 into the template. These values may override values mentioned below
9082 and those from the customer record.
9084 The following variables are available in the template instead of or in addition
9085 to the fields of the customer record.
9087 I<$payby> - a description of the method of payment for the customer
9088 # would be nice to use FS::payby::shortname
9089 I<$payinfo> - the masked account information used to collect for this customer
9090 I<$expdate> - the expiration of the customer payment method in seconds from epoch
9091 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
9095 sub generate_letter {
9096 my ($self, $template, %options) = @_;
9098 return unless $conf->exists($template);
9100 my $letter_template = new Text::Template
9102 SOURCE => [ map "$_\n", $conf->config($template)],
9103 DELIMITERS => [ '[@--', '--@]' ],
9105 or die "can't create new Text::Template object: Text::Template::ERROR";
9107 $letter_template->compile()
9108 or die "can't compile template: Text::Template::ERROR";
9110 my %letter_data = map { $_ => $self->$_ } $self->fields;
9111 $letter_data{payinfo} = $self->mask_payinfo;
9113 #my $paydate = $self->paydate || '2037-12-31';
9114 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
9116 my $payby = $self->payby;
9117 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
9118 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
9120 #credit cards expire at the end of the month/year of their exp date
9121 if ($payby eq 'CARD' || $payby eq 'DCRD') {
9122 $letter_data{payby} = 'credit card';
9123 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
9124 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
9126 }elsif ($payby eq 'COMP') {
9127 $letter_data{payby} = 'complimentary account';
9129 $letter_data{payby} = 'current method';
9131 $letter_data{expdate} = $expire_time;
9133 for (keys %{$options{extra_fields}}){
9134 $letter_data{$_} = $options{extra_fields}->{$_};
9137 unless(exists($letter_data{returnaddress})){
9138 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
9139 $self->agent_template)
9141 if ( length($retadd) ) {
9142 $letter_data{returnaddress} = $retadd;
9143 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
9144 $letter_data{returnaddress} =
9145 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
9146 $conf->config('company_address', $self->agentnum)
9149 $letter_data{returnaddress} = '~';
9153 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
9155 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
9157 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
9158 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
9162 ) or die "can't open temp file: $!\n";
9164 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
9166 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
9170 =item print_ps TEMPLATE
9172 Returns an postscript letter filled in from TEMPLATE, as a scalar.
9178 my $file = $self->generate_letter(@_);
9179 FS::Misc::generate_ps($file);
9182 =item print TEMPLATE
9184 Prints the filled in template.
9186 TEMPLATE is the name of a L<Text::Template> to fill in and print.
9190 sub queueable_print {
9193 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
9194 or die "invalid customer number: " . $opt{custvnum};
9196 my $error = $self->print( $opt{template} );
9197 die $error if $error;
9201 my ($self, $template) = (shift, shift);
9202 do_print [ $self->print_ps($template) ];
9205 #these three subs should just go away once agent stuff is all config overrides
9207 sub agent_template {
9209 $self->_agent_plandata('agent_templatename');
9212 sub agent_invoice_from {
9214 $self->_agent_plandata('agent_invoice_from');
9217 sub _agent_plandata {
9218 my( $self, $option ) = @_;
9220 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
9221 #agent-specific Conf
9223 use FS::part_event::Condition;
9225 my $agentnum = $self->agentnum;
9228 if ( driver_name =~ /^Pg/i ) {
9230 } elsif ( driver_name =~ /^mysql/i ) {
9233 die "don't know how to use regular expressions in ". driver_name. " databases";
9236 my $part_event_option =
9238 'select' => 'part_event_option.*',
9239 'table' => 'part_event_option',
9241 LEFT JOIN part_event USING ( eventpart )
9242 LEFT JOIN part_event_option AS peo_agentnum
9243 ON ( part_event.eventpart = peo_agentnum.eventpart
9244 AND peo_agentnum.optionname = 'agentnum'
9245 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
9247 LEFT JOIN part_event_condition
9248 ON ( part_event.eventpart = part_event_condition.eventpart
9249 AND part_event_condition.conditionname = 'cust_bill_age'
9251 LEFT JOIN part_event_condition_option
9252 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
9253 AND part_event_condition_option.optionname = 'age'
9256 #'hashref' => { 'optionname' => $option },
9257 #'hashref' => { 'part_event_option.optionname' => $option },
9259 " WHERE part_event_option.optionname = ". dbh->quote($option).
9260 " AND action = 'cust_bill_send_agent' ".
9261 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
9262 " AND peo_agentnum.optionname = 'agentnum' ".
9263 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
9265 CASE WHEN part_event_condition_option.optionname IS NULL
9267 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
9269 , part_event.weight".
9273 unless ( $part_event_option ) {
9274 return $self->agent->invoice_template || ''
9275 if $option eq 'agent_templatename';
9279 $part_event_option->optionvalue;
9284 ## actual sub, not a method, designed to be called from the queue.
9285 ## sets up the customer, and calls the bill_and_collect
9286 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
9287 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
9288 $cust_main->bill_and_collect(
9293 sub _upgrade_data { #class method
9294 my ($class, %opts) = @_;
9296 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
9297 my $sth = dbh->prepare($sql) or die dbh->errstr;
9298 $sth->execute or die $sth->errstr;
9308 The delete method should possibly take an FS::cust_main object reference
9309 instead of a scalar customer number.
9311 Bill and collect options should probably be passed as references instead of a
9314 There should probably be a configuration file with a list of allowed credit
9317 No multiple currency support (probably a larger project than just this module).
9319 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
9321 Birthdates rely on negative epoch values.
9323 The payby for card/check batches is broken. With mixed batching, bad
9326 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
9330 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
9331 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
9332 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.