5 use base qw( FS::otaker_Mixin FS::payinfo_Mixin FS::Record );
6 use vars qw( @EXPORT_OK $DEBUG $me $conf
8 $import $ignore_expired_card
9 $skip_fuzzyfiles @fuzzyfields
12 use vars qw( $realtime_bop_decline_quiet ); #ugh
16 use Scalar::Util qw( blessed );
17 use List::Util qw( min );
18 use Time::Local qw(timelocal);
19 use Storable qw(thaw);
23 use Digest::MD5 qw(md5_base64);
26 use File::Temp qw( tempfile );
27 use String::Approx qw(amatch);
28 use Business::CreditCard 0.28;
30 use FS::UID qw( getotaker dbh driver_name );
31 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
32 use FS::Misc qw( generate_email send_email generate_ps do_print );
33 use FS::Msgcat qw(gettext);
38 use FS::cust_bill_pkg;
39 use FS::cust_bill_pkg_display;
40 use FS::cust_bill_pkg_tax_location;
41 use FS::cust_bill_pkg_tax_rate_location;
43 use FS::cust_pay_pending;
44 use FS::cust_pay_void;
45 use FS::cust_pay_batch;
48 use FS::part_referral;
49 use FS::cust_main_county;
50 use FS::cust_location;
52 use FS::cust_main_exemption;
53 use FS::cust_tax_adjustment;
55 use FS::tax_rate_location;
56 use FS::cust_tax_location;
57 use FS::part_pkg_taxrate;
59 use FS::cust_main_invoice;
61 use FS::cust_credit_bill;
62 use FS::cust_bill_pay;
63 use FS::prepay_credit;
67 use FS::part_event_condition;
71 use FS::payment_gateway;
72 use FS::agent_payment_gateway;
76 @EXPORT_OK = qw( smart_search );
78 $realtime_bop_decline_quiet = 0;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 $me = '[FS::cust_main]';
87 $ignore_expired_card = 0;
90 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub {
99 install_callback FS::UID sub {
100 $conf = new FS::Conf;
101 #yes, need it for stuff below (prolly should be cached)
106 my ( $hashref, $cache ) = @_;
107 if ( exists $hashref->{'pkgnum'} ) {
108 #@{ $self->{'_pkgnum'} } = ();
109 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110 $self->{'_pkgnum'} = $subcache;
111 #push @{ $self->{'_pkgnum'} },
112 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
118 FS::cust_main - Object methods for cust_main records
124 $record = new FS::cust_main \%hash;
125 $record = new FS::cust_main { 'column' => 'value' };
127 $error = $record->insert;
129 $error = $new_record->replace($old_record);
131 $error = $record->delete;
133 $error = $record->check;
135 @cust_pkg = $record->all_pkgs;
137 @cust_pkg = $record->ncancelled_pkgs;
139 @cust_pkg = $record->suspended_pkgs;
141 $error = $record->bill;
142 $error = $record->bill %options;
143 $error = $record->bill 'time' => $time;
145 $error = $record->collect;
146 $error = $record->collect %options;
147 $error = $record->collect 'invoice_time' => $time,
152 An FS::cust_main object represents a customer. FS::cust_main inherits from
153 FS::Record. The following fields are currently supported:
159 Primary key (assigned automatically for new customers)
163 Agent (see L<FS::agent>)
167 Advertising source (see L<FS::part_referral>)
179 Cocial security number (optional)
195 (optional, see L<FS::cust_main_county>)
199 (see L<FS::cust_main_county>)
205 (see L<FS::cust_main_county>)
241 (optional, see L<FS::cust_main_county>)
245 (see L<FS::cust_main_county>)
251 (see L<FS::cust_main_county>)
267 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
271 Payment Information (See L<FS::payinfo_Mixin> for data format)
275 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
279 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
283 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
287 Start date month (maestro/solo cards only)
291 Start date year (maestro/solo cards only)
295 Issue number (maestro/solo cards only)
299 Name on card or billing name
303 IP address from which payment information was received
307 Tax exempt, empty or `Y'
311 Order taker (see L<FS::access_user>)
317 =item referral_custnum
319 Referring customer number
323 Enable individual CDR spooling, empty or `Y'
327 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
331 Discourage individual CDR printing, empty or `Y'
341 Creates a new customer. To add the customer to the database, see L<"insert">.
343 Note that this stores the hash reference, not a distinct copy of the hash it
344 points to. You can ask the object for a copy with the I<hash> method.
348 sub table { 'cust_main'; }
350 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
352 Adds this customer to the database. If there is an error, returns the error,
353 otherwise returns false.
355 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
356 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
357 are inserted atomicly, or the transaction is rolled back. Passing an empty
358 hash reference is equivalent to not supplying this parameter. There should be
359 a better explanation of this, but until then, here's an example:
362 tie %hash, 'Tie::RefHash'; #this part is important
364 $cust_pkg => [ $svc_acct ],
367 $cust_main->insert( \%hash );
369 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
370 be set as the invoicing list (see L<"invoicing_list">). Errors return as
371 expected and rollback the entire transaction; it is not necessary to call
372 check_invoicing_list first. The invoicing_list is set after the records in the
373 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
374 invoicing_list destination to the newly-created svc_acct. Here's an example:
376 $cust_main->insert( {}, [ $email, 'POST' ] );
378 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
380 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
381 on the supplied jobnum (they will not run until the specific job completes).
382 This can be used to defer provisioning until some action completes (such
383 as running the customer's credit card successfully).
385 The I<noexport> option is deprecated. If I<noexport> is set true, no
386 provisioning jobs (exports) are scheduled. (You can schedule them later with
387 the B<reexport> method.)
389 The I<tax_exemption> option can be set to an arrayref of tax names.
390 FS::cust_main_exemption records will be created and inserted.
396 my $cust_pkgs = @_ ? shift : {};
397 my $invoicing_list = @_ ? shift : '';
399 warn "$me insert called with options ".
400 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
403 local $SIG{HUP} = 'IGNORE';
404 local $SIG{INT} = 'IGNORE';
405 local $SIG{QUIT} = 'IGNORE';
406 local $SIG{TERM} = 'IGNORE';
407 local $SIG{TSTP} = 'IGNORE';
408 local $SIG{PIPE} = 'IGNORE';
410 my $oldAutoCommit = $FS::UID::AutoCommit;
411 local $FS::UID::AutoCommit = 0;
414 my $prepay_identifier = '';
415 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
417 if ( $self->payby eq 'PREPAY' ) {
419 $self->payby('BILL');
420 $prepay_identifier = $self->payinfo;
423 warn " looking up prepaid card $prepay_identifier\n"
426 my $error = $self->get_prepay( $prepay_identifier,
427 'amount_ref' => \$amount,
428 'seconds_ref' => \$seconds,
429 'upbytes_ref' => \$upbytes,
430 'downbytes_ref' => \$downbytes,
431 'totalbytes_ref' => \$totalbytes,
434 $dbh->rollback if $oldAutoCommit;
435 #return "error applying prepaid card (transaction rolled back): $error";
439 $payby = 'PREP' if $amount;
441 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
444 $self->payby('BILL');
445 $amount = $self->paid;
449 warn " inserting $self\n"
452 $self->signupdate(time) unless $self->signupdate;
454 $self->auto_agent_custid()
455 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
457 my $error = $self->SUPER::insert;
459 $dbh->rollback if $oldAutoCommit;
460 #return "inserting cust_main record (transaction rolled back): $error";
464 warn " setting invoicing list\n"
467 if ( $invoicing_list ) {
468 $error = $self->check_invoicing_list( $invoicing_list );
470 $dbh->rollback if $oldAutoCommit;
471 #return "checking invoicing_list (transaction rolled back): $error";
474 $self->invoicing_list( $invoicing_list );
477 warn " setting customer tags\n"
480 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
481 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
482 'custnum' => $self->custnum };
483 my $error = $cust_tag->insert;
485 $dbh->rollback if $oldAutoCommit;
490 if ( $invoicing_list ) {
491 $error = $self->check_invoicing_list( $invoicing_list );
493 $dbh->rollback if $oldAutoCommit;
494 #return "checking invoicing_list (transaction rolled back): $error";
497 $self->invoicing_list( $invoicing_list );
501 warn " setting cust_main_exemption\n"
504 my $tax_exemption = delete $options{'tax_exemption'};
505 if ( $tax_exemption ) {
506 foreach my $taxname ( @$tax_exemption ) {
507 my $cust_main_exemption = new FS::cust_main_exemption {
508 'custnum' => $self->custnum,
509 'taxname' => $taxname,
511 my $error = $cust_main_exemption->insert;
513 $dbh->rollback if $oldAutoCommit;
514 return "inserting cust_main_exemption (transaction rolled back): $error";
519 if ( $conf->config('cust_main-skeleton_tables')
520 && $conf->config('cust_main-skeleton_custnum') ) {
522 warn " inserting skeleton records\n"
525 my $error = $self->start_copy_skel;
527 $dbh->rollback if $oldAutoCommit;
533 warn " ordering packages\n"
536 $error = $self->order_pkgs( $cust_pkgs,
538 'seconds_ref' => \$seconds,
539 'upbytes_ref' => \$upbytes,
540 'downbytes_ref' => \$downbytes,
541 'totalbytes_ref' => \$totalbytes,
544 $dbh->rollback if $oldAutoCommit;
549 $dbh->rollback if $oldAutoCommit;
550 return "No svc_acct record to apply pre-paid time";
552 if ( $upbytes || $downbytes || $totalbytes ) {
553 $dbh->rollback if $oldAutoCommit;
554 return "No svc_acct record to apply pre-paid data";
558 warn " inserting initial $payby payment of $amount\n"
560 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
562 $dbh->rollback if $oldAutoCommit;
563 return "inserting payment (transaction rolled back): $error";
567 unless ( $import || $skip_fuzzyfiles ) {
568 warn " queueing fuzzyfiles update\n"
570 $error = $self->queue_fuzzyfiles_update;
572 $dbh->rollback if $oldAutoCommit;
573 return "updating fuzzy search cache: $error";
578 warn " exporting\n" if $DEBUG > 1;
580 my $export_args = $options{'export_args'} || [];
583 map qsearch( 'part_export', {exportnum=>$_} ),
584 $conf->config('cust_main-exports'); #, $agentnum
586 foreach my $part_export ( @part_export ) {
587 my $error = $part_export->export_insert($self, @$export_args);
589 $dbh->rollback if $oldAutoCommit;
590 return "exporting to ". $part_export->exporttype.
591 " (transaction rolled back): $error";
595 #foreach my $depend_jobnum ( @$depend_jobnums ) {
596 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
598 # foreach my $jobnum ( @jobnums ) {
599 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
600 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
602 # my $error = $queue->depend_insert($depend_jobnum);
604 # $dbh->rollback if $oldAutoCommit;
605 # return "error queuing job dependancy: $error";
612 #if ( exists $options{'jobnums'} ) {
613 # push @{ $options{'jobnums'} }, @jobnums;
616 warn " insert complete; committing transaction\n"
619 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
624 use File::CounterFile;
625 sub auto_agent_custid {
628 my $format = $conf->config('cust_main-auto_agent_custid');
630 if ( $format eq '1YMMXXXXXXXX' ) {
632 my $counter = new File::CounterFile 'cust_main.agent_custid';
635 my $ym = 100000000000 + time2str('%y%m00000000', time);
636 if ( $ym > $counter->value ) {
637 $counter->{'value'} = $agent_custid = $ym;
638 $counter->{'updated'} = 1;
640 $agent_custid = $counter->inc;
646 die "Unknown cust_main-auto_agent_custid format: $format";
649 $self->agent_custid($agent_custid);
653 sub start_copy_skel {
656 #'mg_user_preference' => {},
657 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
658 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
659 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
660 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
661 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
664 _copy_skel( 'cust_main', #tablename
665 $conf->config('cust_main-skeleton_custnum'), #sourceid
666 $self->custnum, #destid
667 @tables, #child tables
671 #recursive subroutine, not a method
673 my( $table, $sourceid, $destid, %child_tables ) = @_;
676 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
677 ( $table, $primary_key ) = ( $1, $2 );
679 my $dbdef_table = dbdef->table($table);
680 $primary_key = $dbdef_table->primary_key
681 or return "$table has no primary key".
682 " (or do you need to run dbdef-create?)";
685 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
686 join (', ', keys %child_tables). "\n"
689 foreach my $child_table_def ( keys %child_tables ) {
693 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
694 ( $child_table, $child_pkey ) = ( $1, $2 );
696 $child_table = $child_table_def;
698 $child_pkey = dbdef->table($child_table)->primary_key;
699 # or return "$table has no primary key".
700 # " (or do you need to run dbdef-create?)\n";
704 if ( keys %{ $child_tables{$child_table_def} } ) {
706 return "$child_table has no primary key".
707 " (run dbdef-create or try specifying it?)\n"
710 #false laziness w/Record::insert and only works on Pg
711 #refactor the proper last-inserted-id stuff out of Record::insert if this
712 # ever gets use for anything besides a quick kludge for one customer
713 my $default = dbdef->table($child_table)->column($child_pkey)->default;
714 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
715 or return "can't parse $child_table.$child_pkey default value ".
716 " for sequence name: $default";
721 my @sel_columns = grep { $_ ne $primary_key }
722 dbdef->table($child_table)->columns;
723 my $sel_columns = join(', ', @sel_columns );
725 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
726 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
727 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
729 my $sel_st = "SELECT $sel_columns FROM $child_table".
730 " WHERE $primary_key = $sourceid";
733 my $sel_sth = dbh->prepare( $sel_st )
734 or return dbh->errstr;
736 $sel_sth->execute or return $sel_sth->errstr;
738 while ( my $row = $sel_sth->fetchrow_hashref ) {
740 warn " selected row: ".
741 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
745 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
746 my $ins_sth =dbh->prepare($statement)
747 or return dbh->errstr;
748 my @param = ( $destid, map $row->{$_}, @ins_columns );
749 warn " $statement: [ ". join(', ', @param). " ]\n"
751 $ins_sth->execute( @param )
752 or return $ins_sth->errstr;
754 #next unless keys %{ $child_tables{$child_table} };
755 next unless $sequence;
757 #another section of that laziness
758 my $seq_sql = "SELECT currval('$sequence')";
759 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
760 $seq_sth->execute or return $seq_sth->errstr;
761 my $insertid = $seq_sth->fetchrow_arrayref->[0];
763 # don't drink soap! recurse! recurse! okay!
765 _copy_skel( $child_table_def,
766 $row->{$child_pkey}, #sourceid
768 %{ $child_tables{$child_table_def} },
770 return $error if $error;
780 =item order_pkg HASHREF | OPTION => VALUE ...
782 Orders a single package.
784 Options may be passed as a list of key/value pairs or as a hash reference.
795 Optional FS::cust_location object
799 Optional arryaref of FS::svc_* service objects.
803 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
804 jobs will have a dependancy on the supplied job (they will not run until the
805 specific job completes). This can be used to defer provisioning until some
806 action completes (such as running the customer's credit card successfully).
810 Optional subject for a ticket created and attached to this customer
814 Optional queue name for ticket additions
822 my $opt = ref($_[0]) ? shift : { @_ };
824 warn "$me order_pkg called with options ".
825 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
828 my $cust_pkg = $opt->{'cust_pkg'};
829 my $svcs = $opt->{'svcs'} || [];
831 my %svc_options = ();
832 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
833 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
835 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
836 qw( ticket_subject ticket_queue );
838 local $SIG{HUP} = 'IGNORE';
839 local $SIG{INT} = 'IGNORE';
840 local $SIG{QUIT} = 'IGNORE';
841 local $SIG{TERM} = 'IGNORE';
842 local $SIG{TSTP} = 'IGNORE';
843 local $SIG{PIPE} = 'IGNORE';
845 my $oldAutoCommit = $FS::UID::AutoCommit;
846 local $FS::UID::AutoCommit = 0;
849 if ( $opt->{'cust_location'} &&
850 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
851 my $error = $opt->{'cust_location'}->insert;
853 $dbh->rollback if $oldAutoCommit;
854 return "inserting cust_location (transaction rolled back): $error";
856 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
859 $cust_pkg->custnum( $self->custnum );
861 my $error = $cust_pkg->insert( %insert_params );
863 $dbh->rollback if $oldAutoCommit;
864 return "inserting cust_pkg (transaction rolled back): $error";
867 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
868 if ( $svc_something->svcnum ) {
869 my $old_cust_svc = $svc_something->cust_svc;
870 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
871 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
872 $error = $new_cust_svc->replace($old_cust_svc);
874 $svc_something->pkgnum( $cust_pkg->pkgnum );
875 if ( $svc_something->isa('FS::svc_acct') ) {
876 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
877 qw( seconds upbytes downbytes totalbytes ) ) {
878 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
879 ${ $opt->{$_.'_ref'} } = 0;
882 $error = $svc_something->insert(%svc_options);
885 $dbh->rollback if $oldAutoCommit;
886 return "inserting svc_ (transaction rolled back): $error";
890 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
895 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
896 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
898 Like the insert method on an existing record, this method orders multiple
899 packages and included services atomicaly. Pass a Tie::RefHash data structure
900 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
901 There should be a better explanation of this, but until then, here's an
905 tie %hash, 'Tie::RefHash'; #this part is important
907 $cust_pkg => [ $svc_acct ],
910 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
912 Services can be new, in which case they are inserted, or existing unaudited
913 services, in which case they are linked to the newly-created package.
915 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
916 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
918 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
919 on the supplied jobnum (they will not run until the specific job completes).
920 This can be used to defer provisioning until some action completes (such
921 as running the customer's credit card successfully).
923 The I<noexport> option is deprecated. If I<noexport> is set true, no
924 provisioning jobs (exports) are scheduled. (You can schedule them later with
925 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
926 on the cust_main object is not recommended, as existing services will also be
929 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
930 provided, the scalars (provided by references) will be incremented by the
931 values of the prepaid card.`
937 my $cust_pkgs = shift;
938 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
940 $seconds_ref ||= $options{'seconds_ref'};
942 warn "$me order_pkgs called with options ".
943 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
946 local $SIG{HUP} = 'IGNORE';
947 local $SIG{INT} = 'IGNORE';
948 local $SIG{QUIT} = 'IGNORE';
949 local $SIG{TERM} = 'IGNORE';
950 local $SIG{TSTP} = 'IGNORE';
951 local $SIG{PIPE} = 'IGNORE';
953 my $oldAutoCommit = $FS::UID::AutoCommit;
954 local $FS::UID::AutoCommit = 0;
957 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
959 foreach my $cust_pkg ( keys %$cust_pkgs ) {
961 my $error = $self->order_pkg(
962 'cust_pkg' => $cust_pkg,
963 'svcs' => $cust_pkgs->{$cust_pkg},
964 'seconds_ref' => $seconds_ref,
965 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
970 $dbh->rollback if $oldAutoCommit;
976 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
980 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
982 Recharges this (existing) customer with the specified prepaid card (see
983 L<FS::prepay_credit>), specified either by I<identifier> or as an
984 FS::prepay_credit object. If there is an error, returns the error, otherwise
987 Optionally, five scalar references can be passed as well. They will have their
988 values filled in with the amount, number of seconds, and number of upload,
989 download, and total bytes applied by this prepaid card.
993 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
994 #the only place that uses these args
995 sub recharge_prepay {
996 my( $self, $prepay_credit, $amountref, $secondsref,
997 $upbytesref, $downbytesref, $totalbytesref ) = @_;
999 local $SIG{HUP} = 'IGNORE';
1000 local $SIG{INT} = 'IGNORE';
1001 local $SIG{QUIT} = 'IGNORE';
1002 local $SIG{TERM} = 'IGNORE';
1003 local $SIG{TSTP} = 'IGNORE';
1004 local $SIG{PIPE} = 'IGNORE';
1006 my $oldAutoCommit = $FS::UID::AutoCommit;
1007 local $FS::UID::AutoCommit = 0;
1010 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
1012 my $error = $self->get_prepay( $prepay_credit,
1013 'amount_ref' => \$amount,
1014 'seconds_ref' => \$seconds,
1015 'upbytes_ref' => \$upbytes,
1016 'downbytes_ref' => \$downbytes,
1017 'totalbytes_ref' => \$totalbytes,
1019 || $self->increment_seconds($seconds)
1020 || $self->increment_upbytes($upbytes)
1021 || $self->increment_downbytes($downbytes)
1022 || $self->increment_totalbytes($totalbytes)
1023 || $self->insert_cust_pay_prepay( $amount,
1025 ? $prepay_credit->identifier
1030 $dbh->rollback if $oldAutoCommit;
1034 if ( defined($amountref) ) { $$amountref = $amount; }
1035 if ( defined($secondsref) ) { $$secondsref = $seconds; }
1036 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1037 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1038 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1040 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1045 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1047 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1048 specified either by I<identifier> or as an FS::prepay_credit object.
1050 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
1051 incremented by the values of the prepaid card.
1053 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1054 check or set this customer's I<agentnum>.
1056 If there is an error, returns the error, otherwise returns false.
1062 my( $self, $prepay_credit, %opt ) = @_;
1064 local $SIG{HUP} = 'IGNORE';
1065 local $SIG{INT} = 'IGNORE';
1066 local $SIG{QUIT} = 'IGNORE';
1067 local $SIG{TERM} = 'IGNORE';
1068 local $SIG{TSTP} = 'IGNORE';
1069 local $SIG{PIPE} = 'IGNORE';
1071 my $oldAutoCommit = $FS::UID::AutoCommit;
1072 local $FS::UID::AutoCommit = 0;
1075 unless ( ref($prepay_credit) ) {
1077 my $identifier = $prepay_credit;
1079 $prepay_credit = qsearchs(
1081 { 'identifier' => $prepay_credit },
1086 unless ( $prepay_credit ) {
1087 $dbh->rollback if $oldAutoCommit;
1088 return "Invalid prepaid card: ". $identifier;
1093 if ( $prepay_credit->agentnum ) {
1094 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1095 $dbh->rollback if $oldAutoCommit;
1096 return "prepaid card not valid for agent ". $self->agentnum;
1098 $self->agentnum($prepay_credit->agentnum);
1101 my $error = $prepay_credit->delete;
1103 $dbh->rollback if $oldAutoCommit;
1104 return "removing prepay_credit (transaction rolled back): $error";
1107 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1108 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1110 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1115 =item increment_upbytes SECONDS
1117 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1118 the specified number of upbytes. If there is an error, returns the error,
1119 otherwise returns false.
1123 sub increment_upbytes {
1124 _increment_column( shift, 'upbytes', @_);
1127 =item increment_downbytes SECONDS
1129 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1130 the specified number of downbytes. If there is an error, returns the error,
1131 otherwise returns false.
1135 sub increment_downbytes {
1136 _increment_column( shift, 'downbytes', @_);
1139 =item increment_totalbytes SECONDS
1141 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1142 the specified number of totalbytes. If there is an error, returns the error,
1143 otherwise returns false.
1147 sub increment_totalbytes {
1148 _increment_column( shift, 'totalbytes', @_);
1151 =item increment_seconds SECONDS
1153 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1154 the specified number of seconds. If there is an error, returns the error,
1155 otherwise returns false.
1159 sub increment_seconds {
1160 _increment_column( shift, 'seconds', @_);
1163 =item _increment_column AMOUNT
1165 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1166 the specified number of seconds or bytes. If there is an error, returns
1167 the error, otherwise returns false.
1171 sub _increment_column {
1172 my( $self, $column, $amount ) = @_;
1173 warn "$me increment_column called: $column, $amount\n"
1176 return '' unless $amount;
1178 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1179 $self->ncancelled_pkgs;
1181 if ( ! @cust_pkg ) {
1182 return 'No packages with primary or single services found'.
1183 ' to apply pre-paid time';
1184 } elsif ( scalar(@cust_pkg) > 1 ) {
1185 #maybe have a way to specify the package/account?
1186 return 'Multiple packages found to apply pre-paid time';
1189 my $cust_pkg = $cust_pkg[0];
1190 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1194 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1196 if ( ! @cust_svc ) {
1197 return 'No account found to apply pre-paid time';
1198 } elsif ( scalar(@cust_svc) > 1 ) {
1199 return 'Multiple accounts found to apply pre-paid time';
1202 my $svc_acct = $cust_svc[0]->svc_x;
1203 warn " found service svcnum ". $svc_acct->pkgnum.
1204 ' ('. $svc_acct->email. ")\n"
1207 $column = "increment_$column";
1208 $svc_acct->$column($amount);
1212 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1214 Inserts a prepayment in the specified amount for this customer. An optional
1215 second argument can specify the prepayment identifier for tracking purposes.
1216 If there is an error, returns the error, otherwise returns false.
1220 sub insert_cust_pay_prepay {
1221 shift->insert_cust_pay('PREP', @_);
1224 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1226 Inserts a cash payment in the specified amount for this customer. An optional
1227 second argument can specify the payment identifier for tracking purposes.
1228 If there is an error, returns the error, otherwise returns false.
1232 sub insert_cust_pay_cash {
1233 shift->insert_cust_pay('CASH', @_);
1236 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1238 Inserts a Western Union payment in the specified amount for this customer. An
1239 optional second argument can specify the prepayment identifier for tracking
1240 purposes. If there is an error, returns the error, otherwise returns false.
1244 sub insert_cust_pay_west {
1245 shift->insert_cust_pay('WEST', @_);
1248 sub insert_cust_pay {
1249 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1250 my $payinfo = scalar(@_) ? shift : '';
1252 my $cust_pay = new FS::cust_pay {
1253 'custnum' => $self->custnum,
1254 'paid' => sprintf('%.2f', $amount),
1255 #'_date' => #date the prepaid card was purchased???
1257 'payinfo' => $payinfo,
1265 This method is deprecated. See the I<depend_jobnum> option to the insert and
1266 order_pkgs methods for a better way to defer provisioning.
1268 Re-schedules all exports by calling the B<reexport> method of all associated
1269 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1270 otherwise returns false.
1277 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1278 "use the depend_jobnum option to insert or order_pkgs to delay export";
1280 local $SIG{HUP} = 'IGNORE';
1281 local $SIG{INT} = 'IGNORE';
1282 local $SIG{QUIT} = 'IGNORE';
1283 local $SIG{TERM} = 'IGNORE';
1284 local $SIG{TSTP} = 'IGNORE';
1285 local $SIG{PIPE} = 'IGNORE';
1287 my $oldAutoCommit = $FS::UID::AutoCommit;
1288 local $FS::UID::AutoCommit = 0;
1291 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1292 my $error = $cust_pkg->reexport;
1294 $dbh->rollback if $oldAutoCommit;
1299 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1304 =item delete NEW_CUSTNUM
1306 This deletes the customer. If there is an error, returns the error, otherwise
1309 This will completely remove all traces of the customer record. This is not
1310 what you want when a customer cancels service; for that, cancel all of the
1311 customer's packages (see L</cancel>).
1313 If the customer has any uncancelled packages, you need to pass a new (valid)
1314 customer number for those packages to be transferred to. Cancelled packages
1315 will be deleted. Did I mention that this is NOT what you want when a customer
1316 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1318 You can't delete a customer with invoices (see L<FS::cust_bill>),
1319 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1320 refunds (see L<FS::cust_refund>).
1327 local $SIG{HUP} = 'IGNORE';
1328 local $SIG{INT} = 'IGNORE';
1329 local $SIG{QUIT} = 'IGNORE';
1330 local $SIG{TERM} = 'IGNORE';
1331 local $SIG{TSTP} = 'IGNORE';
1332 local $SIG{PIPE} = 'IGNORE';
1334 my $oldAutoCommit = $FS::UID::AutoCommit;
1335 local $FS::UID::AutoCommit = 0;
1338 if ( $self->cust_bill ) {
1339 $dbh->rollback if $oldAutoCommit;
1340 return "Can't delete a customer with invoices";
1342 if ( $self->cust_credit ) {
1343 $dbh->rollback if $oldAutoCommit;
1344 return "Can't delete a customer with credits";
1346 if ( $self->cust_pay ) {
1347 $dbh->rollback if $oldAutoCommit;
1348 return "Can't delete a customer with payments";
1350 if ( $self->cust_refund ) {
1351 $dbh->rollback if $oldAutoCommit;
1352 return "Can't delete a customer with refunds";
1355 my @cust_pkg = $self->ncancelled_pkgs;
1357 my $new_custnum = shift;
1358 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1359 $dbh->rollback if $oldAutoCommit;
1360 return "Invalid new customer number: $new_custnum";
1362 foreach my $cust_pkg ( @cust_pkg ) {
1363 my %hash = $cust_pkg->hash;
1364 $hash{'custnum'} = $new_custnum;
1365 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1366 my $error = $new_cust_pkg->replace($cust_pkg,
1367 options => { $cust_pkg->options },
1370 $dbh->rollback if $oldAutoCommit;
1375 my @cancelled_cust_pkg = $self->all_pkgs;
1376 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1377 my $error = $cust_pkg->delete;
1379 $dbh->rollback if $oldAutoCommit;
1384 foreach my $table (qw( cust_main_invoice cust_main_exemption cust_tag )) {
1385 foreach my $record ( qsearch( 'table', { 'custnum' => $self->custnum } ) ) {
1386 my $error = $record->delete;
1388 $dbh->rollback if $oldAutoCommit;
1394 my $error = $self->SUPER::delete;
1396 $dbh->rollback if $oldAutoCommit;
1400 # cust_main exports!
1402 #my $export_args = $options{'export_args'} || [];
1405 map qsearch( 'part_export', {exportnum=>$_} ),
1406 $conf->config('cust_main-exports'); #, $agentnum
1408 foreach my $part_export ( @part_export ) {
1409 my $error = $part_export->export_delete( $self ); #, @$export_args);
1411 $dbh->rollback if $oldAutoCommit;
1412 return "exporting to ". $part_export->exporttype.
1413 " (transaction rolled back): $error";
1417 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1422 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1425 Replaces the OLD_RECORD with this one in the database. If there is an error,
1426 returns the error, otherwise returns false.
1428 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1429 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1430 expected and rollback the entire transaction; it is not necessary to call
1431 check_invoicing_list first. Here's an example:
1433 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1435 Currently available options are: I<tax_exemption>.
1437 The I<tax_exemption> option can be set to an arrayref of tax names.
1438 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1445 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1447 : $self->replace_old;
1451 warn "$me replace called\n"
1454 my $curuser = $FS::CurrentUser::CurrentUser;
1455 if ( $self->payby eq 'COMP'
1456 && $self->payby ne $old->payby
1457 && ! $curuser->access_right('Complimentary customer')
1460 return "You are not permitted to create complimentary accounts.";
1463 local($ignore_expired_card) = 1
1464 if $old->payby =~ /^(CARD|DCRD)$/
1465 && $self->payby =~ /^(CARD|DCRD)$/
1466 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1468 local $SIG{HUP} = 'IGNORE';
1469 local $SIG{INT} = 'IGNORE';
1470 local $SIG{QUIT} = 'IGNORE';
1471 local $SIG{TERM} = 'IGNORE';
1472 local $SIG{TSTP} = 'IGNORE';
1473 local $SIG{PIPE} = 'IGNORE';
1475 my $oldAutoCommit = $FS::UID::AutoCommit;
1476 local $FS::UID::AutoCommit = 0;
1479 my $error = $self->SUPER::replace($old);
1482 $dbh->rollback if $oldAutoCommit;
1486 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1487 my $invoicing_list = shift @param;
1488 $error = $self->check_invoicing_list( $invoicing_list );
1490 $dbh->rollback if $oldAutoCommit;
1493 $self->invoicing_list( $invoicing_list );
1496 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1498 #this could be more efficient than deleting and re-inserting, if it matters
1499 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1500 my $error = $cust_tag->delete;
1502 $dbh->rollback if $oldAutoCommit;
1506 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1507 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1508 'custnum' => $self->custnum };
1509 my $error = $cust_tag->insert;
1511 $dbh->rollback if $oldAutoCommit;
1518 my %options = @param;
1520 my $tax_exemption = delete $options{'tax_exemption'};
1521 if ( $tax_exemption ) {
1523 my %cust_main_exemption =
1524 map { $_->taxname => $_ }
1525 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1527 foreach my $taxname ( @$tax_exemption ) {
1529 next if delete $cust_main_exemption{$taxname};
1531 my $cust_main_exemption = new FS::cust_main_exemption {
1532 'custnum' => $self->custnum,
1533 'taxname' => $taxname,
1535 my $error = $cust_main_exemption->insert;
1537 $dbh->rollback if $oldAutoCommit;
1538 return "inserting cust_main_exemption (transaction rolled back): $error";
1542 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1543 my $error = $cust_main_exemption->delete;
1545 $dbh->rollback if $oldAutoCommit;
1546 return "deleting cust_main_exemption (transaction rolled back): $error";
1552 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1553 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1554 && $self->get('payinfo') !~ /^99\d{14}$/
1556 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1561 # card/check/lec info has changed, want to retry realtime_ invoice events
1562 my $error = $self->retry_realtime;
1564 $dbh->rollback if $oldAutoCommit;
1569 unless ( $import || $skip_fuzzyfiles ) {
1570 $error = $self->queue_fuzzyfiles_update;
1572 $dbh->rollback if $oldAutoCommit;
1573 return "updating fuzzy search cache: $error";
1577 # cust_main exports!
1579 my $export_args = $options{'export_args'} || [];
1582 map qsearch( 'part_export', {exportnum=>$_} ),
1583 $conf->config('cust_main-exports'); #, $agentnum
1585 foreach my $part_export ( @part_export ) {
1586 my $error = $part_export->export_replace( $self, $old, @$export_args);
1588 $dbh->rollback if $oldAutoCommit;
1589 return "exporting to ". $part_export->exporttype.
1590 " (transaction rolled back): $error";
1594 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1599 =item queue_fuzzyfiles_update
1601 Used by insert & replace to update the fuzzy search cache
1605 sub queue_fuzzyfiles_update {
1608 local $SIG{HUP} = 'IGNORE';
1609 local $SIG{INT} = 'IGNORE';
1610 local $SIG{QUIT} = 'IGNORE';
1611 local $SIG{TERM} = 'IGNORE';
1612 local $SIG{TSTP} = 'IGNORE';
1613 local $SIG{PIPE} = 'IGNORE';
1615 my $oldAutoCommit = $FS::UID::AutoCommit;
1616 local $FS::UID::AutoCommit = 0;
1619 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1620 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1622 $dbh->rollback if $oldAutoCommit;
1623 return "queueing job (transaction rolled back): $error";
1626 if ( $self->ship_last ) {
1627 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1628 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1630 $dbh->rollback if $oldAutoCommit;
1631 return "queueing job (transaction rolled back): $error";
1635 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1642 Checks all fields to make sure this is a valid customer record. If there is
1643 an error, returns the error, otherwise returns false. Called by the insert
1644 and replace methods.
1651 warn "$me check BEFORE: \n". $self->_dump
1655 $self->ut_numbern('custnum')
1656 || $self->ut_number('agentnum')
1657 || $self->ut_textn('agent_custid')
1658 || $self->ut_number('refnum')
1659 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1660 || $self->ut_textn('custbatch')
1661 || $self->ut_name('last')
1662 || $self->ut_name('first')
1663 || $self->ut_snumbern('birthdate')
1664 || $self->ut_snumbern('signupdate')
1665 || $self->ut_textn('company')
1666 || $self->ut_text('address1')
1667 || $self->ut_textn('address2')
1668 || $self->ut_text('city')
1669 || $self->ut_textn('county')
1670 || $self->ut_textn('state')
1671 || $self->ut_country('country')
1672 || $self->ut_anything('comments')
1673 || $self->ut_numbern('referral_custnum')
1674 || $self->ut_textn('stateid')
1675 || $self->ut_textn('stateid_state')
1676 || $self->ut_textn('invoice_terms')
1677 || $self->ut_alphan('geocode')
1678 || $self->ut_floatn('cdr_termination_percentage')
1681 #barf. need message catalogs. i18n. etc.
1682 $error .= "Please select an advertising source."
1683 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1684 return $error if $error;
1686 return "Unknown agent"
1687 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1689 return "Unknown refnum"
1690 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1692 return "Unknown referring custnum: ". $self->referral_custnum
1693 unless ! $self->referral_custnum
1694 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1696 if ( $self->censustract ne '' ) {
1697 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1698 or return "Illegal census tract: ". $self->censustract;
1700 $self->censustract("$1.$2");
1703 if ( $self->ss eq '' ) {
1708 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1709 or return "Illegal social security number: ". $self->ss;
1710 $self->ss("$1-$2-$3");
1714 # bad idea to disable, causes billing to fail because of no tax rates later
1715 # unless ( $import ) {
1716 unless ( qsearch('cust_main_county', {
1717 'country' => $self->country,
1720 return "Unknown state/county/country: ".
1721 $self->state. "/". $self->county. "/". $self->country
1722 unless qsearch('cust_main_county',{
1723 'state' => $self->state,
1724 'county' => $self->county,
1725 'country' => $self->country,
1731 $self->ut_phonen('daytime', $self->country)
1732 || $self->ut_phonen('night', $self->country)
1733 || $self->ut_phonen('fax', $self->country)
1734 || $self->ut_zip('zip', $self->country)
1736 return $error if $error;
1738 if ( $conf->exists('cust_main-require_phone')
1739 && ! length($self->daytime) && ! length($self->night)
1742 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1744 : FS::Msgcat::_gettext('daytime');
1745 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1747 : FS::Msgcat::_gettext('night');
1749 return "$daytime_label or $night_label is required"
1753 if ( $self->has_ship_address
1754 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1755 $self->addr_fields )
1759 $self->ut_name('ship_last')
1760 || $self->ut_name('ship_first')
1761 || $self->ut_textn('ship_company')
1762 || $self->ut_text('ship_address1')
1763 || $self->ut_textn('ship_address2')
1764 || $self->ut_text('ship_city')
1765 || $self->ut_textn('ship_county')
1766 || $self->ut_textn('ship_state')
1767 || $self->ut_country('ship_country')
1769 return $error if $error;
1771 #false laziness with above
1772 unless ( qsearchs('cust_main_county', {
1773 'country' => $self->ship_country,
1776 return "Unknown ship_state/ship_county/ship_country: ".
1777 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1778 unless qsearch('cust_main_county',{
1779 'state' => $self->ship_state,
1780 'county' => $self->ship_county,
1781 'country' => $self->ship_country,
1787 $self->ut_phonen('ship_daytime', $self->ship_country)
1788 || $self->ut_phonen('ship_night', $self->ship_country)
1789 || $self->ut_phonen('ship_fax', $self->ship_country)
1790 || $self->ut_zip('ship_zip', $self->ship_country)
1792 return $error if $error;
1794 return "Unit # is required."
1795 if $self->ship_address2 =~ /^\s*$/
1796 && $conf->exists('cust_main-require_address2');
1798 } else { # ship_ info eq billing info, so don't store dup info in database
1800 $self->setfield("ship_$_", '')
1801 foreach $self->addr_fields;
1803 return "Unit # is required."
1804 if $self->address2 =~ /^\s*$/
1805 && $conf->exists('cust_main-require_address2');
1809 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1810 # or return "Illegal payby: ". $self->payby;
1812 FS::payby->can_payby($self->table, $self->payby)
1813 or return "Illegal payby: ". $self->payby;
1815 $error = $self->ut_numbern('paystart_month')
1816 || $self->ut_numbern('paystart_year')
1817 || $self->ut_numbern('payissue')
1818 || $self->ut_textn('paytype')
1820 return $error if $error;
1822 if ( $self->payip eq '' ) {
1825 $error = $self->ut_ip('payip');
1826 return $error if $error;
1829 # If it is encrypted and the private key is not availaible then we can't
1830 # check the credit card.
1831 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1833 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1835 my $payinfo = $self->payinfo;
1836 $payinfo =~ s/\D//g;
1837 $payinfo =~ /^(\d{13,16})$/
1838 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1840 $self->payinfo($payinfo);
1842 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1844 return gettext('unknown_card_type')
1845 if $self->payinfo !~ /^99\d{14}$/ #token
1846 && cardtype($self->payinfo) eq "Unknown";
1848 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1850 return 'Banned credit card: banned on '.
1851 time2str('%a %h %o at %r', $ban->_date).
1852 ' by '. $ban->otaker.
1853 ' (ban# '. $ban->bannum. ')';
1856 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1857 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1858 $self->paycvv =~ /^(\d{4})$/
1859 or return "CVV2 (CID) for American Express cards is four digits.";
1862 $self->paycvv =~ /^(\d{3})$/
1863 or return "CVV2 (CVC2/CID) is three digits.";
1870 my $cardtype = cardtype($payinfo);
1871 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1873 return "Start date or issue number is required for $cardtype cards"
1874 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1876 return "Start month must be between 1 and 12"
1877 if $self->paystart_month
1878 and $self->paystart_month < 1 || $self->paystart_month > 12;
1880 return "Start year must be 1990 or later"
1881 if $self->paystart_year
1882 and $self->paystart_year < 1990;
1884 return "Issue number must be beween 1 and 99"
1886 and $self->payissue < 1 || $self->payissue > 99;
1889 $self->paystart_month('');
1890 $self->paystart_year('');
1891 $self->payissue('');
1894 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1896 my $payinfo = $self->payinfo;
1897 $payinfo =~ s/[^\d\@]//g;
1898 if ( $conf->exists('echeck-nonus') ) {
1899 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1900 $payinfo = "$1\@$2";
1902 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1903 $payinfo = "$1\@$2";
1905 $self->payinfo($payinfo);
1908 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1910 return 'Banned ACH account: banned on '.
1911 time2str('%a %h %o at %r', $ban->_date).
1912 ' by '. $ban->otaker.
1913 ' (ban# '. $ban->bannum. ')';
1916 } elsif ( $self->payby eq 'LECB' ) {
1918 my $payinfo = $self->payinfo;
1919 $payinfo =~ s/\D//g;
1920 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1922 $self->payinfo($payinfo);
1925 } elsif ( $self->payby eq 'BILL' ) {
1927 $error = $self->ut_textn('payinfo');
1928 return "Illegal P.O. number: ". $self->payinfo if $error;
1931 } elsif ( $self->payby eq 'COMP' ) {
1933 my $curuser = $FS::CurrentUser::CurrentUser;
1934 if ( ! $self->custnum
1935 && ! $curuser->access_right('Complimentary customer')
1938 return "You are not permitted to create complimentary accounts."
1941 $error = $self->ut_textn('payinfo');
1942 return "Illegal comp account issuer: ". $self->payinfo if $error;
1945 } elsif ( $self->payby eq 'PREPAY' ) {
1947 my $payinfo = $self->payinfo;
1948 $payinfo =~ s/\W//g; #anything else would just confuse things
1949 $self->payinfo($payinfo);
1950 $error = $self->ut_alpha('payinfo');
1951 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1952 return "Unknown prepayment identifier"
1953 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1958 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1959 return "Expiration date required"
1960 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1964 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1965 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1966 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1967 ( $m, $y ) = ( $2, "19$1" );
1968 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1969 ( $m, $y ) = ( $3, "20$2" );
1971 return "Illegal expiration date: ". $self->paydate;
1973 $self->paydate("$y-$m-01");
1974 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1975 return gettext('expired_card')
1977 && !$ignore_expired_card
1978 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1981 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1982 ( ! $conf->exists('require_cardname')
1983 || $self->payby !~ /^(CARD|DCRD)$/ )
1985 $self->payname( $self->first. " ". $self->getfield('last') );
1987 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1988 or return gettext('illegal_name'). " payname: ". $self->payname;
1992 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1993 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1997 $self->otaker(getotaker) unless $self->otaker;
1999 warn "$me check AFTER: \n". $self->_dump
2002 $self->SUPER::check;
2007 Returns a list of fields which have ship_ duplicates.
2012 qw( last first company
2013 address1 address2 city county state zip country
2018 =item has_ship_address
2020 Returns true if this customer record has a separate shipping address.
2024 sub has_ship_address {
2026 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2031 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2032 city, county, state, zip, country. The shipping address is used if present.
2036 #geocode? dependent on tax-ship_address config, not available in cust_location
2037 #mostly. not yet then.
2041 my $prefix = $self->has_ship_address ? 'ship_' : '';
2043 map { $_ => $self->get($prefix.$_) }
2044 qw( address1 address2 city county state zip country geocode );
2045 #fields that cust_location has
2048 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2050 Returns all packages (see L<FS::cust_pkg>) for this customer.
2056 my $extra_qsearch = ref($_[0]) ? shift : {};
2058 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
2061 if ( $self->{'_pkgnum'} ) {
2062 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2064 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2067 sort sort_packages @cust_pkg;
2072 Synonym for B<all_pkgs>.
2077 shift->all_pkgs(@_);
2082 Returns all locations (see L<FS::cust_location>) for this customer.
2088 qsearch('cust_location', { 'custnum' => $self->custnum } );
2091 =item location_label [ OPTION => VALUE ... ]
2093 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2101 used to separate the address elements (defaults to ', ')
2103 =item escape_function
2105 a callback used for escaping the text of the address elements
2111 # false laziness with FS::cust_location::line
2113 sub location_label {
2117 my $separator = $opt{join_string} || ', ';
2118 my $escape = $opt{escape_function} || sub{ shift };
2120 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2121 my $prefix = length($self->ship_last) ? 'ship_' : '';
2124 foreach (qw ( address1 address2 ) ) {
2125 my $method = "$prefix$_";
2126 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2131 foreach (qw ( city county state zip ) ) {
2132 my $method = "$prefix$_";
2133 if ( $self->$method ) {
2134 $line .= ' (' if $method eq 'county';
2135 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2136 $line .= ' )' if $method eq 'county';
2140 $line .= $separator. &$escape(code2country($self->country))
2141 if $self->country ne $cydefault;
2146 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2148 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2152 sub ncancelled_pkgs {
2154 my $extra_qsearch = ref($_[0]) ? shift : {};
2156 return $self->num_ncancelled_pkgs unless wantarray;
2159 if ( $self->{'_pkgnum'} ) {
2161 warn "$me ncancelled_pkgs: returning cached objects"
2164 @cust_pkg = grep { ! $_->getfield('cancel') }
2165 values %{ $self->{'_pkgnum'}->cache };
2169 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2170 $self->custnum. "\n"
2173 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2175 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2179 sort sort_packages @cust_pkg;
2185 my $extra_qsearch = ref($_[0]) ? shift : {};
2187 $extra_qsearch->{'select'} ||= '*';
2188 $extra_qsearch->{'select'} .=
2189 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2193 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2198 'table' => 'cust_pkg',
2199 'hashref' => { 'custnum' => $self->custnum },
2204 # This should be generalized to use config options to determine order.
2207 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2208 return $locationsort if $locationsort;
2210 if ( $a->get('cancel') xor $b->get('cancel') ) {
2211 return -1 if $b->get('cancel');
2212 return 1 if $a->get('cancel');
2213 #shouldn't get here...
2216 my $a_num_cust_svc = $a->num_cust_svc;
2217 my $b_num_cust_svc = $b->num_cust_svc;
2218 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2219 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2220 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2221 my @a_cust_svc = $a->cust_svc;
2222 my @b_cust_svc = $b->cust_svc;
2223 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2224 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2225 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
2226 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2231 =item suspended_pkgs
2233 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2237 sub suspended_pkgs {
2239 grep { $_->susp } $self->ncancelled_pkgs;
2242 =item unflagged_suspended_pkgs
2244 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2245 customer (thouse packages without the `manual_flag' set).
2249 sub unflagged_suspended_pkgs {
2251 return $self->suspended_pkgs
2252 unless dbdef->table('cust_pkg')->column('manual_flag');
2253 grep { ! $_->manual_flag } $self->suspended_pkgs;
2256 =item unsuspended_pkgs
2258 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2263 sub unsuspended_pkgs {
2265 grep { ! $_->susp } $self->ncancelled_pkgs;
2268 =item next_bill_date
2270 Returns the next date this customer will be billed, as a UNIX timestamp, or
2271 undef if no active package has a next bill date.
2275 sub next_bill_date {
2277 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2280 =item num_cancelled_pkgs
2282 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2287 sub num_cancelled_pkgs {
2288 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2291 sub num_ncancelled_pkgs {
2292 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2296 my( $self ) = shift;
2297 my $sql = scalar(@_) ? shift : '';
2298 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2299 my $sth = dbh->prepare(
2300 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2301 ) or die dbh->errstr;
2302 $sth->execute($self->custnum) or die $sth->errstr;
2303 $sth->fetchrow_arrayref->[0];
2308 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2309 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2310 on success or a list of errors.
2316 grep { $_->unsuspend } $self->suspended_pkgs;
2321 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2323 Returns a list: an empty list on success or a list of errors.
2329 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2332 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2334 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2335 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2336 of a list of pkgparts; the hashref has the following keys:
2340 =item pkgparts - listref of pkgparts
2342 =item (other options are passed to the suspend method)
2347 Returns a list: an empty list on success or a list of errors.
2351 sub suspend_if_pkgpart {
2353 my (@pkgparts, %opt);
2354 if (ref($_[0]) eq 'HASH'){
2355 @pkgparts = @{$_[0]{pkgparts}};
2360 grep { $_->suspend(%opt) }
2361 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2362 $self->unsuspended_pkgs;
2365 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2367 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2368 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2369 instead of a list of pkgparts; the hashref has the following keys:
2373 =item pkgparts - listref of pkgparts
2375 =item (other options are passed to the suspend method)
2379 Returns a list: an empty list on success or a list of errors.
2383 sub suspend_unless_pkgpart {
2385 my (@pkgparts, %opt);
2386 if (ref($_[0]) eq 'HASH'){
2387 @pkgparts = @{$_[0]{pkgparts}};
2392 grep { $_->suspend(%opt) }
2393 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2394 $self->unsuspended_pkgs;
2397 =item cancel [ OPTION => VALUE ... ]
2399 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2401 Available options are:
2405 =item quiet - can be set true to supress email cancellation notices.
2407 =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.
2409 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2411 =item nobill - can be set true to skip billing if it might otherwise be done.
2415 Always returns a list: an empty list on success or a list of errors.
2419 # nb that dates are not specified as valid options to this method
2422 my( $self, %opt ) = @_;
2424 warn "$me cancel called on customer ". $self->custnum. " with options ".
2425 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2428 return ( 'access denied' )
2429 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2431 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2433 #should try decryption (we might have the private key)
2434 # and if not maybe queue a job for the server that does?
2435 return ( "Can't (yet) ban encrypted credit cards" )
2436 if $self->is_encrypted($self->payinfo);
2438 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2439 my $error = $ban->insert;
2440 return ( $error ) if $error;
2444 my @pkgs = $self->ncancelled_pkgs;
2446 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2448 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2449 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2453 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2454 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2457 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2460 sub _banned_pay_hashref {
2471 'payby' => $payby2ban{$self->payby},
2472 'payinfo' => md5_base64($self->payinfo),
2473 #don't ever *search* on reason! #'reason' =>
2479 Returns all notes (see L<FS::cust_main_note>) for this customer.
2486 qsearch( 'cust_main_note',
2487 { 'custnum' => $self->custnum },
2489 'ORDER BY _DATE DESC'
2495 Returns the agent (see L<FS::agent>) for this customer.
2501 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2506 Returns the agent name (see L<FS::agent>) for this customer.
2512 $self->agent->agent;
2517 Returns any tags associated with this customer, as FS::cust_tag objects,
2518 or an empty list if there are no tags.
2524 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2529 Returns any tags associated with this customer, as FS::part_tag objects,
2530 or an empty list if there are no tags.
2536 map $_->part_tag, $self->cust_tag;
2542 Returns the customer class, as an FS::cust_class object, or the empty string
2543 if there is no customer class.
2549 if ( $self->classnum ) {
2550 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2558 Returns the customer category name, or the empty string if there is no customer
2565 my $cust_class = $self->cust_class;
2567 ? $cust_class->categoryname
2573 Returns the customer class name, or the empty string if there is no customer
2580 my $cust_class = $self->cust_class;
2582 ? $cust_class->classname
2587 =item bill_and_collect
2589 Cancels and suspends any packages due, generates bills, applies payments and
2590 credits, and applies collection events to run cards, send bills and notices,
2593 By default, warns on errors and continues with the next operation (but see the
2594 "fatal" flag below).
2596 Options are passed as name-value pairs. Currently available options are:
2602 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:
2606 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2610 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.
2614 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2618 If set true, re-charges setup fees.
2622 If set any errors prevent subsequent operations from continusing. If set
2623 specifically to "return", returns the error (or false, if there is no error).
2624 Any other true value causes errors to die.
2628 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)
2632 Optional FS::queue entry to receive status updates.
2636 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2637 options of those methods are also available.
2641 sub bill_and_collect {
2642 my( $self, %options ) = @_;
2646 #$options{actual_time} not $options{time} because freeside-daily -d is for
2647 #pre-printing invoices
2649 $options{'actual_time'} ||= time;
2650 my $job = $options{'job'};
2652 $job->update_statustext('0,cleaning expired packages') if $job;
2653 $error = $self->cancel_expired_pkgs( $options{actual_time} );
2655 $error = "Error expiring custnum ". $self->custnum. ": $error";
2656 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2657 elsif ( $options{fatal} ) { die $error; }
2658 else { warn $error; }
2661 $error = $self->suspend_adjourned_pkgs( $options{actual_time} );
2663 $error = "Error adjourning custnum ". $self->custnum. ": $error";
2664 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2665 elsif ( $options{fatal} ) { die $error; }
2666 else { warn $error; }
2669 $job->update_statustext('20,billing packages') if $job;
2670 $error = $self->bill( %options );
2672 $error = "Error billing custnum ". $self->custnum. ": $error";
2673 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2674 elsif ( $options{fatal} ) { die $error; }
2675 else { warn $error; }
2678 $job->update_statustext('50,applying payments and credits') if $job;
2679 $error = $self->apply_payments_and_credits;
2681 $error = "Error applying custnum ". $self->custnum. ": $error";
2682 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2683 elsif ( $options{fatal} ) { die $error; }
2684 else { warn $error; }
2687 $job->update_statustext('70,running collection events') if $job;
2688 unless ( $conf->exists('cancelled_cust-noevents')
2689 && ! $self->num_ncancelled_pkgs
2691 $error = $self->collect( %options );
2693 $error = "Error collecting custnum ". $self->custnum. ": $error";
2694 if ($options{fatal} && $options{fatal} eq 'return') { return $error; }
2695 elsif ($options{fatal} ) { die $error; }
2696 else { warn $error; }
2699 $job->update_statustext('100,finished') if $job;
2705 sub cancel_expired_pkgs {
2706 my ( $self, $time, %options ) = @_;
2708 my @cancel_pkgs = $self->ncancelled_pkgs( {
2709 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2714 foreach my $cust_pkg ( @cancel_pkgs ) {
2715 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2716 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2717 'reason_otaker' => $cpr->otaker
2721 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2724 scalar(@errors) ? join(' / ', @errors) : '';
2728 sub suspend_adjourned_pkgs {
2729 my ( $self, $time, %options ) = @_;
2731 my @susp_pkgs = $self->ncancelled_pkgs( {
2733 " AND ( susp IS NULL OR susp = 0 )
2734 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
2735 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2740 #only because there's no SQL test for is_prepaid :/
2742 grep { ( $_->part_pkg->is_prepaid
2747 && $_->adjourn <= $time
2755 foreach my $cust_pkg ( @susp_pkgs ) {
2756 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2757 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2758 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2759 'reason_otaker' => $cpr->otaker
2763 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2766 scalar(@errors) ? join(' / ', @errors) : '';
2772 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2773 conjunction with the collect method by calling B<bill_and_collect>.
2775 If there is an error, returns the error, otherwise returns false.
2777 Options are passed as name-value pairs. Currently available options are:
2783 If set true, re-charges setup fees.
2787 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:
2791 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2795 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2797 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2801 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2805 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.
2809 This boolean value informs the us that the package is being cancelled. This
2810 typically might mean not charging the normal recurring fee but only usage
2811 fees since the last billing. Setup charges may be charged. Not all package
2812 plans support this feature (they tend to charge 0).
2816 Optional terms to be printed on this invoice. Otherwise, customer-specific
2817 terms or the default terms are used.
2824 my( $self, %options ) = @_;
2825 return '' if $self->payby eq 'COMP';
2826 warn "$me bill customer ". $self->custnum. "\n"
2829 my $time = $options{'time'} || time;
2830 my $invoice_time = $options{'invoice_time'} || $time;
2832 $options{'not_pkgpart'} ||= {};
2833 $options{'not_pkgpart'} = { map { $_ => 1 }
2834 split(/\s*,\s*/, $options{'not_pkgpart'})
2836 unless ref($options{'not_pkgpart'});
2838 local $SIG{HUP} = 'IGNORE';
2839 local $SIG{INT} = 'IGNORE';
2840 local $SIG{QUIT} = 'IGNORE';
2841 local $SIG{TERM} = 'IGNORE';
2842 local $SIG{TSTP} = 'IGNORE';
2843 local $SIG{PIPE} = 'IGNORE';
2845 my $oldAutoCommit = $FS::UID::AutoCommit;
2846 local $FS::UID::AutoCommit = 0;
2849 warn "$me acquiring lock on customer ". $self->custnum. "\n"
2852 $self->select_for_update; #mutex
2854 warn "$me running pre-bill events for customer ". $self->custnum. "\n"
2857 my $error = $self->do_cust_event(
2858 'debug' => ( $options{'debug'} || 0 ),
2859 'time' => $invoice_time,
2860 'check_freq' => $options{'check_freq'},
2861 'stage' => 'pre-bill',
2864 $dbh->rollback if $oldAutoCommit;
2868 warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
2871 #keep auto-charge and non-auto-charge line items separate
2872 my @passes = ( '', 'no_auto' );
2874 my %cust_bill_pkg = map { $_ => [] } @passes;
2877 # find the packages which are due for billing, find out how much they are
2878 # & generate invoice database.
2881 my %total_setup = map { my $z = 0; $_ => \$z; } @passes;
2882 my %total_recur = map { my $z = 0; $_ => \$z; } @passes;
2884 my %taxlisthash = map { $_ => {} } @passes;
2886 my @precommit_hooks = ();
2888 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
2889 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2891 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2893 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2895 #? to avoid use of uninitialized value errors... ?
2896 $cust_pkg->setfield('bill', '')
2897 unless defined($cust_pkg->bill);
2899 #my $part_pkg = $cust_pkg->part_pkg;
2901 my $real_pkgpart = $cust_pkg->pkgpart;
2902 my %hash = $cust_pkg->hash;
2904 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2906 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2908 my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
2911 $self->_make_lines( 'part_pkg' => $part_pkg,
2912 'cust_pkg' => $cust_pkg,
2913 'precommit_hooks' => \@precommit_hooks,
2914 'line_items' => $cust_bill_pkg{$pass},
2915 'setup' => $total_setup{$pass},
2916 'recur' => $total_recur{$pass},
2917 'tax_matrix' => $taxlisthash{$pass},
2919 'real_pkgpart' => $real_pkgpart,
2920 'options' => \%options,
2923 $dbh->rollback if $oldAutoCommit;
2927 } #foreach my $part_pkg
2929 } #foreach my $cust_pkg
2931 #if the customer isn't on an automatic payby, everything can go on a single
2933 #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
2934 #merge everything into one list
2937 foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
2939 my @cust_bill_pkg = @{ $cust_bill_pkg{$pass} };
2941 next unless @cust_bill_pkg; #don't create an invoice w/o line items
2943 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2944 !$conf->exists('postal_invoice-recurring_only')
2948 my $postal_pkg = $self->charge_postal_fee();
2949 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2951 $dbh->rollback if $oldAutoCommit;
2952 return "can't charge postal invoice fee for customer ".
2953 $self->custnum. ": $postal_pkg";
2955 } elsif ( $postal_pkg ) {
2957 my $real_pkgpart = $postal_pkg->pkgpart;
2958 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2959 my %postal_options = %options;
2960 delete $postal_options{cancel};
2962 $self->_make_lines( 'part_pkg' => $part_pkg,
2963 'cust_pkg' => $postal_pkg,
2964 'precommit_hooks' => \@precommit_hooks,
2965 'line_items' => \@cust_bill_pkg,
2966 'setup' => $total_setup{$pass},
2967 'recur' => $total_recur{$pass},
2968 'tax_matrix' => $taxlisthash{$pass},
2970 'real_pkgpart' => $real_pkgpart,
2971 'options' => \%postal_options,
2974 $dbh->rollback if $oldAutoCommit;
2983 my $listref_or_error =
2984 $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
2986 unless ( ref( $listref_or_error ) ) {
2987 $dbh->rollback if $oldAutoCommit;
2988 return $listref_or_error;
2991 foreach my $taxline ( @$listref_or_error ) {
2992 ${ $total_setup{$pass} } =
2993 sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
2994 push @cust_bill_pkg, $taxline;
2997 #add tax adjustments
2998 warn "adding tax adjustments...\n" if $DEBUG > 2;
2999 foreach my $cust_tax_adjustment (
3000 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
3006 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
3008 my $itemdesc = $cust_tax_adjustment->taxname;
3009 $itemdesc = '' if $itemdesc eq 'Tax';
3011 push @cust_bill_pkg, new FS::cust_bill_pkg {
3017 'itemdesc' => $itemdesc,
3018 'itemcomment' => $cust_tax_adjustment->comment,
3019 'cust_tax_adjustment' => $cust_tax_adjustment,
3020 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3025 my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
3027 my @cust_bill = $self->cust_bill;
3028 my $balance = $self->balance;
3029 my $previous_balance = scalar(@cust_bill)
3030 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
3033 $previous_balance += $cust_bill[$#cust_bill]->charged
3034 if scalar(@cust_bill);
3035 #my $balance_adjustments =
3036 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
3038 #create the new invoice
3039 my $cust_bill = new FS::cust_bill ( {
3040 'custnum' => $self->custnum,
3041 '_date' => ( $invoice_time ),
3042 'charged' => $charged,
3043 'billing_balance' => $balance,
3044 'previous_balance' => $previous_balance,
3045 'invoice_terms' => $options{'invoice_terms'},
3047 $error = $cust_bill->insert;
3049 $dbh->rollback if $oldAutoCommit;
3050 return "can't create invoice for customer #". $self->custnum. ": $error";
3053 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
3054 $cust_bill_pkg->invnum($cust_bill->invnum);
3055 my $error = $cust_bill_pkg->insert;
3057 $dbh->rollback if $oldAutoCommit;
3058 return "can't create invoice line item: $error";
3062 } #foreach my $pass ( keys %cust_bill_pkg )
3064 foreach my $hook ( @precommit_hooks ) {
3066 &{$hook}; #($self) ?
3069 $dbh->rollback if $oldAutoCommit;
3070 return "$@ running precommit hook $hook\n";
3074 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3078 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
3080 This is a weird one. Perhaps it should not even be exposed.
3082 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
3083 Usually used internally by bill method B<bill>.
3085 If there is an error, returns the error, otherwise returns reference to a
3086 list of line items suitable for insertion.
3092 An array ref of the line items being billed.
3096 A strange beast. The keys to this hash are internal identifiers consisting
3097 of the name of the tax object type, a space, and its unique identifier ( e.g.
3098 'cust_main_county 23' ). The values of the hash are listrefs. The first
3099 item in the list is the tax object. The remaining items are either line
3100 items or floating point values (currency amounts).
3102 The taxes are calculated on this entity. Calculated exemption records are
3103 transferred to the LINEITEMREF items on the assumption that they are related.
3109 This specifies the date appearing on the associated invoice. Some
3110 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
3115 sub calculate_taxes {
3116 my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
3118 my @tax_line_items = ();
3120 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
3122 # keys are tax names (as printed on invoices / itemdesc )
3123 # values are listrefs of taxlisthash keys (internal identifiers)
3126 # keys are taxlisthash keys (internal identifiers)
3127 # values are (cumulative) amounts
3130 # keys are taxlisthash keys (internal identifiers)
3131 # values are listrefs of cust_bill_pkg_tax_location hashrefs
3132 my %tax_location = ();
3134 # keys are taxlisthash keys (internal identifiers)
3135 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
3136 my %tax_rate_location = ();
3138 foreach my $tax ( keys %$taxlisthash ) {
3139 my $tax_object = shift @{ $taxlisthash->{$tax} };
3140 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
3141 warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
3142 my $hashref_or_error =
3143 $tax_object->taxline( $taxlisthash->{$tax},
3144 'custnum' => $self->custnum,
3145 'invoice_time' => $invoice_time
3147 return $hashref_or_error unless ref($hashref_or_error);
3149 unshift @{ $taxlisthash->{$tax} }, $tax_object;
3151 my $name = $hashref_or_error->{'name'};
3152 my $amount = $hashref_or_error->{'amount'};
3154 #warn "adding $amount as $name\n";
3155 $taxname{ $name } ||= [];
3156 push @{ $taxname{ $name } }, $tax;
3158 $tax{ $tax } += $amount;
3160 $tax_location{ $tax } ||= [];
3161 if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
3162 push @{ $tax_location{ $tax } },
3164 'taxnum' => $tax_object->taxnum,
3165 'taxtype' => ref($tax_object),
3166 'pkgnum' => $tax_object->get('pkgnum'),
3167 'locationnum' => $tax_object->get('locationnum'),
3168 'amount' => sprintf('%.2f', $amount ),
3172 $tax_rate_location{ $tax } ||= [];
3173 if ( ref($tax_object) eq 'FS::tax_rate' ) {
3174 my $taxratelocationnum =
3175 $tax_object->tax_rate_location->taxratelocationnum;
3176 push @{ $tax_rate_location{ $tax } },
3178 'taxnum' => $tax_object->taxnum,
3179 'taxtype' => ref($tax_object),
3180 'amount' => sprintf('%.2f', $amount ),
3181 'locationtaxid' => $tax_object->location,
3182 'taxratelocationnum' => $taxratelocationnum,
3188 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
3189 my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
3190 foreach my $tax ( keys %$taxlisthash ) {
3191 foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
3192 next unless ref($_) eq 'FS::cust_bill_pkg';
3194 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
3195 splice( @{ $_->_cust_tax_exempt_pkg } );
3199 #consolidate and create tax line items
3200 warn "consolidating and generating...\n" if $DEBUG > 2;
3201 foreach my $taxname ( keys %taxname ) {
3204 my @cust_bill_pkg_tax_location = ();
3205 my @cust_bill_pkg_tax_rate_location = ();
3206 warn "adding $taxname\n" if $DEBUG > 1;
3207 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
3208 next if $seen{$taxitem}++;
3209 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
3210 $tax += $tax{$taxitem};
3211 push @cust_bill_pkg_tax_location,
3212 map { new FS::cust_bill_pkg_tax_location $_ }
3213 @{ $tax_location{ $taxitem } };
3214 push @cust_bill_pkg_tax_rate_location,
3215 map { new FS::cust_bill_pkg_tax_rate_location $_ }
3216 @{ $tax_rate_location{ $taxitem } };
3220 $tax = sprintf('%.2f', $tax );
3222 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
3228 if ( $pkg_category and
3229 $conf->config('invoice_latexsummary') ||
3230 $conf->config('invoice_htmlsummary')
3234 my %hash = ( 'section' => $pkg_category->categoryname );
3235 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3239 push @tax_line_items, new FS::cust_bill_pkg {
3245 'itemdesc' => $taxname,
3246 'display' => \@display,
3247 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3248 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
3257 my ($self, %params) = @_;
3259 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
3260 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
3261 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
3262 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
3263 my $total_setup = $params{setup} or die "no setup accumulator specified";
3264 my $total_recur = $params{recur} or die "no recur accumulator specified";
3265 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
3266 my $time = $params{'time'} or die "no time specified";
3267 my (%options) = %{$params{options}};
3270 my $real_pkgpart = $params{real_pkgpart};
3271 my %hash = $cust_pkg->hash;
3272 my $old_cust_pkg = new FS::cust_pkg \%hash;
3278 $cust_pkg->pkgpart($part_pkg->pkgpart);
3286 if ( $options{'resetup'}
3287 || ( ! $cust_pkg->setup
3288 && ( ! $cust_pkg->start_date
3289 || $cust_pkg->start_date <= $time
3291 && ( ! $conf->exists('disable_setup_suspended_pkgs')
3292 || ( $conf->exists('disable_setup_suspended_pkgs') &&
3293 ! $cust_pkg->getfield('susp')
3300 warn " bill setup\n" if $DEBUG > 1;
3303 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
3304 return "$@ running calc_setup for $cust_pkg\n"
3307 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
3309 $cust_pkg->setfield('setup', $time)
3310 unless $cust_pkg->setup;
3311 #do need it, but it won't get written to the db
3312 #|| $cust_pkg->pkgpart != $real_pkgpart;
3314 $cust_pkg->setfield('start_date', '')
3315 if $cust_pkg->start_date;
3320 # bill recurring fee
3323 #XXX unit stuff here too
3327 if ( ! $cust_pkg->get('susp')
3328 and ! $cust_pkg->get('start_date')
3329 and ( $part_pkg->getfield('freq') ne '0'
3330 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3332 || ( $part_pkg->plan eq 'voip_cdr'
3333 && $part_pkg->option('bill_every_call')
3335 || ( $options{cancel} )
3338 # XXX should this be a package event? probably. events are called
3339 # at collection time at the moment, though...
3340 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
3341 if $part_pkg->can('reset_usage');
3342 #don't want to reset usage just cause we want a line item??
3343 #&& $part_pkg->pkgpart == $real_pkgpart;
3345 warn " bill recur\n" if $DEBUG > 1;
3348 # XXX shared with $recur_prog
3349 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
3353 #over two params! lets at least switch to a hashref for the rest...
3354 my $increment_next_bill = ( $part_pkg->freq ne '0'
3355 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3356 && !$options{cancel}
3358 my %param = ( 'precommit_hooks' => $precommit_hooks,
3359 'increment_next_bill' => $increment_next_bill,
3360 'discounts' => \@discounts,
3363 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
3364 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
3365 return "$@ running $method for $cust_pkg\n"
3368 if ( $increment_next_bill ) {
3370 my $next_bill = $part_pkg->add_freq($sdate);
3371 return "unparsable frequency: ". $part_pkg->freq
3372 if $next_bill == -1;
3374 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
3375 # only for figuring next bill date, nothing else, so, reset $sdate again
3377 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
3378 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
3379 $cust_pkg->last_bill($sdate);
3381 $cust_pkg->setfield('bill', $next_bill );
3387 warn "\$setup is undefined" unless defined($setup);
3388 warn "\$recur is undefined" unless defined($recur);
3389 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
3392 # If there's line items, create em cust_bill_pkg records
3393 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
3398 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
3399 # hmm.. and if just the options are modified in some weird price plan?
3401 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
3404 my $error = $cust_pkg->replace( $old_cust_pkg,
3405 'options' => { $cust_pkg->options },
3407 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
3408 if $error; #just in case
3411 $setup = sprintf( "%.2f", $setup );
3412 $recur = sprintf( "%.2f", $recur );
3413 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
3414 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3416 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3417 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3420 if ( $setup != 0 || $recur != 0 ) {
3422 warn " charges (setup=$setup, recur=$recur); adding line items\n"
3425 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3427 warn " adding customer package invoice detail: $_\n"
3428 foreach @cust_pkg_detail;
3430 push @details, @cust_pkg_detail;
3432 my $cust_bill_pkg = new FS::cust_bill_pkg {
3433 'pkgnum' => $cust_pkg->pkgnum,
3435 'unitsetup' => $unitsetup,
3437 'unitrecur' => $unitrecur,
3438 'quantity' => $cust_pkg->quantity,
3439 'details' => \@details,
3440 'discounts' => \@discounts,
3441 'hidden' => $part_pkg->hidden,
3444 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3445 $cust_bill_pkg->sdate( $hash{last_bill} );
3446 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
3447 $cust_bill_pkg->edate( $time ) if $options{cancel};
3448 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3449 $cust_bill_pkg->sdate( $sdate );
3450 $cust_bill_pkg->edate( $cust_pkg->bill );
3451 #$cust_bill_pkg->edate( $time ) if $options{cancel};
3454 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3455 unless $part_pkg->pkgpart == $real_pkgpart;
3457 $$total_setup += $setup;
3458 $$total_recur += $recur;
3465 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3466 return $error if $error;
3468 push @$cust_bill_pkgs, $cust_bill_pkg;
3470 } #if $setup != 0 || $recur != 0
3480 my $part_pkg = shift;
3481 my $taxlisthash = shift;
3482 my $cust_bill_pkg = shift;
3483 my $cust_pkg = shift;
3484 my $invoice_time = shift;
3485 my $real_pkgpart = shift;
3486 my $options = shift;
3488 my %cust_bill_pkg = ();
3492 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3493 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3494 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3495 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3497 if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3499 if ( $conf->exists('enable_taxproducts')
3500 && ( scalar($part_pkg->part_pkg_taxoverride)
3501 || $part_pkg->has_taxproduct
3506 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3507 return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3510 foreach my $class (@classes) {
3511 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3512 return $err_or_ref unless ref($err_or_ref);
3513 $taxes{$class} = $err_or_ref;
3516 unless (exists $taxes{''}) {
3517 my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3518 return $err_or_ref unless ref($err_or_ref);
3519 $taxes{''} = $err_or_ref;
3524 my @loc_keys = qw( city county state country );
3526 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3527 my $cust_location = $cust_pkg->cust_location;
3528 %taxhash = map { $_ => $cust_location->$_() } @loc_keys;
3531 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3534 %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3537 $taxhash{'taxclass'} = $part_pkg->taxclass;
3540 my %taxhash_elim = %taxhash;
3541 my @elim = qw( city county state );
3544 #first try a match with taxclass
3545 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3547 if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
3548 #then try a match without taxclass
3549 my %no_taxclass = %taxhash_elim;
3550 $no_taxclass{ 'taxclass' } = '';
3551 @taxes = qsearch( 'cust_main_county', \%no_taxclass );
3554 $taxhash_elim{ shift(@elim) } = '';
3556 } while ( !scalar(@taxes) && scalar(@elim) );
3558 @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3560 if $self->cust_main_exemption; #just to be safe
3562 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3564 $_->set('pkgnum', $cust_pkg->pkgnum );
3565 $_->set('locationnum', $cust_pkg->locationnum );
3569 $taxes{''} = [ @taxes ];
3570 $taxes{'setup'} = [ @taxes ];
3571 $taxes{'recur'} = [ @taxes ];
3572 $taxes{$_} = [ @taxes ] foreach (@classes);
3574 # # maybe eliminate this entirely, along with all the 0% records
3575 # unless ( @taxes ) {
3577 # "fatal: can't find tax rate for state/county/country/taxclass ".
3578 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
3581 } #if $conf->exists('enable_taxproducts') ...
3586 my $separate = $conf->exists('separate_usage');
3587 my $usage_mandate = $cust_pkg->part_pkg->option('usage_mandate', 'Hush!');
3588 if ( $separate || $cust_bill_pkg->hidden || $usage_mandate ) {
3590 my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3591 my %hash = $cust_bill_pkg->hidden # maybe for all bill linked?
3592 ? ( 'section' => $temp_pkg->part_pkg->categoryname )
3595 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
3596 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
3598 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3599 push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3601 push @display, new FS::cust_bill_pkg_display
3604 ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3608 if ($separate && $section && $summary) {
3609 push @display, new FS::cust_bill_pkg_display { type => 'U',
3614 if ($usage_mandate || $section && $summary) {
3615 $hash{post_total} = 'Y';
3618 $hash{section} = $section if ($separate || $usage_mandate);
3619 push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3622 $cust_bill_pkg->set('display', \@display);
3624 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3625 foreach my $key (keys %tax_cust_bill_pkg) {
3626 my @taxes = @{ $taxes{$key} || [] };
3627 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3629 my %localtaxlisthash = ();
3630 foreach my $tax ( @taxes ) {
3632 my $taxname = ref( $tax ). ' '. $tax->taxnum;
3633 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3634 # ' locationnum'. $cust_pkg->locationnum
3635 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3637 $taxlisthash->{ $taxname } ||= [ $tax ];
3638 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
3640 $localtaxlisthash{ $taxname } ||= [ $tax ];
3641 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
3645 warn "finding taxed taxes...\n" if $DEBUG > 2;
3646 foreach my $tax ( keys %localtaxlisthash ) {
3647 my $tax_object = shift @{ $localtaxlisthash{$tax} };
3648 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3650 next unless $tax_object->can('tax_on_tax');
3652 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3653 my $totname = ref( $tot ). ' '. $tot->taxnum;
3655 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3657 next unless exists( $localtaxlisthash{ $totname } ); # only increase
3659 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3660 my $hashref_or_error =
3661 $tax_object->taxline( $localtaxlisthash{$tax},
3662 'custnum' => $self->custnum,
3663 'invoice_time' => $invoice_time,
3665 return $hashref_or_error
3666 unless ref($hashref_or_error);
3668 $taxlisthash->{ $totname } ||= [ $tot ];
3669 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
3681 my $part_pkg = shift;
3685 my $geocode = $self->geocode('cch');
3687 my @taxclassnums = map { $_->taxclassnum }
3688 $part_pkg->part_pkg_taxoverride($class);
3690 unless (@taxclassnums) {
3691 @taxclassnums = map { $_->taxclassnum }
3692 grep { $_->taxable eq 'Y' }
3693 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3695 warn "Found taxclassnum values of ". join(',', @taxclassnums)
3700 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3702 @taxes = qsearch({ 'table' => 'tax_rate',
3703 'hashref' => { 'geocode' => $geocode, },
3704 'extra_sql' => $extra_sql,
3706 if scalar(@taxclassnums);
3708 warn "Found taxes ".
3709 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
3716 =item collect [ HASHREF | OPTION => VALUE ... ]
3718 (Attempt to) collect money for this customer's outstanding invoices (see
3719 L<FS::cust_bill>). Usually used after the bill method.
3721 Actions are now triggered by billing events; see L<FS::part_event> and the
3722 billing events web interface. Old-style invoice events (see
3723 L<FS::part_bill_event>) have been deprecated.
3725 If there is an error, returns the error, otherwise returns false.
3727 Options are passed as name-value pairs.
3729 Currently available options are:
3735 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.
3739 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3743 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3747 set true to surpress email card/ACH decline notices.
3751 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)
3757 # allows for one time override of normal customer billing method
3762 my( $self, %options ) = @_;
3763 my $invoice_time = $options{'invoice_time'} || time;
3766 local $SIG{HUP} = 'IGNORE';
3767 local $SIG{INT} = 'IGNORE';
3768 local $SIG{QUIT} = 'IGNORE';
3769 local $SIG{TERM} = 'IGNORE';
3770 local $SIG{TSTP} = 'IGNORE';
3771 local $SIG{PIPE} = 'IGNORE';
3773 my $oldAutoCommit = $FS::UID::AutoCommit;
3774 local $FS::UID::AutoCommit = 0;
3777 $self->select_for_update; #mutex
3780 my $balance = $self->balance;
3781 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3784 if ( exists($options{'retry_card'}) ) {
3785 carp 'retry_card option passed to collect is deprecated; use retry';
3786 $options{'retry'} ||= $options{'retry_card'};
3788 if ( exists($options{'retry'}) && $options{'retry'} ) {
3789 my $error = $self->retry_realtime;
3791 $dbh->rollback if $oldAutoCommit;
3796 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3798 #never want to roll back an event just because it returned an error
3799 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3801 $self->do_cust_event(
3802 'debug' => ( $options{'debug'} || 0 ),
3803 'time' => $invoice_time,
3804 'check_freq' => $options{'check_freq'},
3805 'stage' => 'collect',
3810 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3812 Runs billing events; see L<FS::part_event> and the billing events web
3815 If there is an error, returns the error, otherwise returns false.
3817 Options are passed as name-value pairs.
3819 Currently available options are:
3825 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.
3829 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3833 "collect" (the default) or "pre-bill"
3837 set true to surpress email card/ACH decline notices.
3841 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)
3847 # allows for one time override of normal customer billing method
3851 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3854 my( $self, %options ) = @_;
3855 my $time = $options{'time'} || time;
3858 local $SIG{HUP} = 'IGNORE';
3859 local $SIG{INT} = 'IGNORE';
3860 local $SIG{QUIT} = 'IGNORE';
3861 local $SIG{TERM} = 'IGNORE';
3862 local $SIG{TSTP} = 'IGNORE';
3863 local $SIG{PIPE} = 'IGNORE';
3865 my $oldAutoCommit = $FS::UID::AutoCommit;
3866 local $FS::UID::AutoCommit = 0;
3869 $self->select_for_update; #mutex
3872 my $balance = $self->balance;
3873 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
3876 # if ( exists($options{'retry_card'}) ) {
3877 # carp 'retry_card option passed to collect is deprecated; use retry';
3878 # $options{'retry'} ||= $options{'retry_card'};
3880 # if ( exists($options{'retry'}) && $options{'retry'} ) {
3881 # my $error = $self->retry_realtime;
3883 # $dbh->rollback if $oldAutoCommit;
3888 # false laziness w/pay_batch::import_results
3890 my $due_cust_event = $self->due_cust_event(
3891 'debug' => ( $options{'debug'} || 0 ),
3893 'check_freq' => $options{'check_freq'},
3894 'stage' => ( $options{'stage'} || 'collect' ),
3896 unless( ref($due_cust_event) ) {
3897 $dbh->rollback if $oldAutoCommit;
3898 return $due_cust_event;
3901 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3902 #never want to roll back an event just because it or a different one
3904 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3906 foreach my $cust_event ( @$due_cust_event ) {
3910 #re-eval event conditions (a previous event could have changed things)
3911 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
3912 #don't leave stray "new/locked" records around
3913 my $error = $cust_event->delete;
3914 return $error if $error;
3919 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
3920 warn " running cust_event ". $cust_event->eventnum. "\n"
3923 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
3924 if ( my $error = $cust_event->do_event() ) {
3925 #XXX wtf is this? figure out a proper dealio with return value
3937 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
3939 Inserts database records for and returns an ordered listref of new events due
3940 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
3941 events are due, an empty listref is returned. If there is an error, returns a
3942 scalar error message.
3944 To actually run the events, call each event's test_condition method, and if
3945 still true, call the event's do_event method.
3947 Options are passed as a hashref or as a list of name-value pairs. Available
3954 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.
3958 "collect" (the default) or "pre-bill"
3962 "Current time" for the events.
3966 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)
3970 Only return events for the specified eventtable (by default, events of all eventtables are returned)
3974 Explicitly pass the objects to be tested (typically used with eventtable).
3978 Set to true to return the objects, but not actually insert them into the
3985 sub due_cust_event {
3987 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
3990 #my $DEBUG = $opt{'debug'}
3991 local($DEBUG) = $opt{'debug'}
3992 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
3994 warn "$me due_cust_event called with options ".
3995 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
3998 $opt{'time'} ||= time;
4000 local $SIG{HUP} = 'IGNORE';
4001 local $SIG{INT} = 'IGNORE';
4002 local $SIG{QUIT} = 'IGNORE';
4003 local $SIG{TERM} = 'IGNORE';
4004 local $SIG{TSTP} = 'IGNORE';
4005 local $SIG{PIPE} = 'IGNORE';
4007 my $oldAutoCommit = $FS::UID::AutoCommit;
4008 local $FS::UID::AutoCommit = 0;
4011 $self->select_for_update #mutex
4012 unless $opt{testonly};
4015 # find possible events (initial search)
4018 my @cust_event = ();
4020 my @eventtable = $opt{'eventtable'}
4021 ? ( $opt{'eventtable'} )
4022 : FS::part_event->eventtables_runorder;
4024 foreach my $eventtable ( @eventtable ) {
4027 if ( $opt{'objects'} ) {
4029 @objects = @{ $opt{'objects'} };
4033 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
4034 @objects = ( $eventtable eq 'cust_main' )
4036 : ( $self->$eventtable() );
4040 my @e_cust_event = ();
4042 my $cross = "CROSS JOIN $eventtable";
4043 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
4044 unless $eventtable eq 'cust_main';
4046 foreach my $object ( @objects ) {
4048 #this first search uses the condition_sql magic for optimization.
4049 #the more possible events we can eliminate in this step the better
4051 my $cross_where = '';
4052 my $pkey = $object->primary_key;
4053 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
4055 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
4057 FS::part_event_condition->where_conditions_sql( $eventtable,
4058 'time'=>$opt{'time'}
4060 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
4062 $extra_sql = "AND $extra_sql" if $extra_sql;
4064 #here is the agent virtualization
4065 $extra_sql .= " AND ( part_event.agentnum IS NULL
4066 OR part_event.agentnum = ". $self->agentnum. ' )';
4068 $extra_sql .= " $order";
4070 warn "searching for events for $eventtable ". $object->$pkey. "\n"
4071 if $opt{'debug'} > 2;
4072 my @part_event = qsearch( {
4073 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
4074 'select' => 'part_event.*',
4075 'table' => 'part_event',
4076 'addl_from' => "$cross $join",
4077 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
4078 'eventtable' => $eventtable,
4081 'extra_sql' => "AND $cross_where $extra_sql",
4085 my $pkey = $object->primary_key;
4086 warn " ". scalar(@part_event).
4087 " possible events found for $eventtable ". $object->$pkey(). "\n";
4090 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
4094 warn " ". scalar(@e_cust_event).
4095 " subtotal possible cust events found for $eventtable\n"
4098 push @cust_event, @e_cust_event;
4102 warn " ". scalar(@cust_event).
4103 " total possible cust events found in initial search\n"
4111 $opt{stage} ||= 'collect';
4113 grep { my $stage = $_->part_event->event_stage;
4114 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
4124 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
4125 'stats_hashref' => \%unsat ),
4128 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
4131 warn " invalid conditions not eliminated with condition_sql:\n".
4132 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
4133 if keys %unsat && $DEBUG; # > 1;
4139 unless( $opt{testonly} ) {
4140 foreach my $cust_event ( @cust_event ) {
4142 my $error = $cust_event->insert();
4144 $dbh->rollback if $oldAutoCommit;
4151 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4157 warn " returning events: ". Dumper(@cust_event). "\n"
4164 =item retry_realtime
4166 Schedules realtime / batch credit card / electronic check / LEC billing
4167 events for for retry. Useful if card information has changed or manual
4168 retry is desired. The 'collect' method must be called to actually retry
4171 Implementation details: For either this customer, or for each of this
4172 customer's open invoices, changes the status of the first "done" (with
4173 statustext error) realtime processing event to "failed".
4177 sub retry_realtime {
4180 local $SIG{HUP} = 'IGNORE';
4181 local $SIG{INT} = 'IGNORE';
4182 local $SIG{QUIT} = 'IGNORE';
4183 local $SIG{TERM} = 'IGNORE';
4184 local $SIG{TSTP} = 'IGNORE';
4185 local $SIG{PIPE} = 'IGNORE';
4187 my $oldAutoCommit = $FS::UID::AutoCommit;
4188 local $FS::UID::AutoCommit = 0;
4191 #a little false laziness w/due_cust_event (not too bad, really)
4193 my $join = FS::part_event_condition->join_conditions_sql;
4194 my $order = FS::part_event_condition->order_conditions_sql;
4197 . join ( ' OR ' , map {
4198 "( part_event.eventtable = " . dbh->quote($_)
4199 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
4200 } FS::part_event->eventtables)
4203 #here is the agent virtualization
4204 my $agent_virt = " ( part_event.agentnum IS NULL
4205 OR part_event.agentnum = ". $self->agentnum. ' )';
4207 #XXX this shouldn't be hardcoded, actions should declare it...
4208 my @realtime_events = qw(
4209 cust_bill_realtime_card
4210 cust_bill_realtime_check
4211 cust_bill_realtime_lec
4215 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
4220 my @cust_event = qsearchs({
4221 'table' => 'cust_event',
4222 'select' => 'cust_event.*',
4223 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
4224 'hashref' => { 'status' => 'done' },
4225 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
4226 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
4229 my %seen_invnum = ();
4230 foreach my $cust_event (@cust_event) {
4232 #max one for the customer, one for each open invoice
4233 my $cust_X = $cust_event->cust_X;
4234 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
4238 or $cust_event->part_event->eventtable eq 'cust_bill'
4241 my $error = $cust_event->retry;
4243 $dbh->rollback if $oldAutoCommit;
4244 return "error scheduling event for retry: $error";
4249 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4257 =item realtime_collect [ OPTION => VALUE ... ]
4259 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4260 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4261 gateway. See L<http://420.am/business-onlinepayment> and
4262 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4264 On failure returns an error message.
4266 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.
4268 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4270 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
4271 then it is deduced from the customer record.
4273 If no I<amount> is specified, then the customer balance is used.
4275 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4276 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4277 if set, will override the value from the customer record.
4279 I<description> is a free-text field passed to the gateway. It defaults to
4280 the value defined by the business-onlinepayment-description configuration
4281 option, or "Internet services" if that is unset.
4283 If an I<invnum> is specified, this payment (if successful) is applied to the
4284 specified invoice. If you don't specify an I<invnum> you might want to
4285 call the B<apply_payments> method or set the I<apply> option.
4287 I<apply> can be set to true to apply a resulting payment.
4289 I<quiet> can be set true to surpress email decline notices.
4291 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4292 resulting paynum, if any.
4294 I<payunique> is a unique identifier for this payment.
4296 I<session_id> is a session identifier associated with this payment.
4298 I<depend_jobnum> allows payment capture to unlock export jobs
4302 sub realtime_collect {
4303 my( $self, %options ) = @_;
4306 warn "$me realtime_collect:\n";
4307 warn " $_ => $options{$_}\n" foreach keys %options;
4310 $options{amount} = $self->balance unless exists( $options{amount} );
4311 $options{method} = FS::payby->payby2bop($self->payby)
4312 unless exists( $options{method} );
4314 return $self->realtime_bop({%options});
4318 =item realtime_bop { [ ARG => VALUE ... ] }
4320 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4321 via a Business::OnlinePayment realtime gateway. See
4322 L<http://420.am/business-onlinepayment> for supported gateways.
4324 Required arguments in the hashref are I<method>, and I<amount>
4326 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4328 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4330 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4331 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4332 if set, will override the value from the customer record.
4334 I<description> is a free-text field passed to the gateway. It defaults to
4335 the value defined by the business-onlinepayment-description configuration
4336 option, or "Internet services" if that is unset.
4338 If an I<invnum> is specified, this payment (if successful) is applied to the
4339 specified invoice. If you don't specify an I<invnum> you might want to
4340 call the B<apply_payments> method or set the I<apply> option.
4342 I<apply> can be set to true to apply a resulting payment.
4344 I<quiet> can be set true to surpress email decline notices.
4346 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4347 resulting paynum, if any.
4349 I<payunique> is a unique identifier for this payment.
4351 I<session_id> is a session identifier associated with this payment.
4353 I<depend_jobnum> allows payment capture to unlock export jobs
4355 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4359 # some helper routines
4360 sub _bop_recurring_billing {
4361 my( $self, %opt ) = @_;
4363 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
4365 if ( defined($method) && $method eq 'transaction_is_recur' ) {
4367 return 1 if $opt{'trans_is_recur'};
4371 my %hash = ( 'custnum' => $self->custnum,
4376 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4377 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4387 sub _payment_gateway {
4388 my ($self, $options) = @_;
4390 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4391 unless exists($options->{payment_gateway});
4393 $options->{payment_gateway};
4397 my ($self, $options) = @_;
4400 'login' => $options->{payment_gateway}->gateway_username,
4401 'password' => $options->{payment_gateway}->gateway_password,
4406 my ($self, $options) = @_;
4408 $options->{payment_gateway}->gatewaynum
4409 ? $options->{payment_gateway}->options
4410 : @{ $options->{payment_gateway}->get('options') };
4415 my ($self, $options) = @_;
4417 unless ( $options->{'description'} ) {
4418 if ( $conf->exists('business-onlinepayment-description') ) {
4419 my $dtempl = $conf->config('business-onlinepayment-description');
4421 my $agent = $self->agent->agent;
4423 $options->{'description'} = eval qq("$dtempl");
4425 $options->{'description'} = 'Internet services';
4429 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4430 $options->{invnum} ||= '';
4431 $options->{payname} = $self->payname unless exists( $options->{payname} );
4435 my ($self, $options) = @_;
4438 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4439 $content{customer_ip} = $payip if length($payip);
4441 $content{invoice_number} = $options->{'invnum'}
4442 if exists($options->{'invnum'}) && length($options->{'invnum'});
4444 $content{email_customer} =
4445 ( $conf->exists('business-onlinepayment-email_customer')
4446 || $conf->exists('business-onlinepayment-email-override') );
4448 my ($payname, $payfirst, $paylast);
4449 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
4450 ($payname = $options->{payname}) =~
4451 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4452 or return "Illegal payname $payname";
4453 ($payfirst, $paylast) = ($1, $2);
4455 $payfirst = $self->getfield('first');
4456 $paylast = $self->getfield('last');
4457 $payname = "$payfirst $paylast";
4460 $content{last_name} = $paylast;
4461 $content{first_name} = $payfirst;
4463 $content{name} = $payname;
4465 $content{address} = exists($options->{'address1'})
4466 ? $options->{'address1'}
4468 my $address2 = exists($options->{'address2'})
4469 ? $options->{'address2'}
4471 $content{address} .= ", ". $address2 if length($address2);
4473 $content{city} = exists($options->{city})
4476 $content{state} = exists($options->{state})
4479 $content{zip} = exists($options->{zip})
4482 $content{country} = exists($options->{country})
4483 ? $options->{country}
4486 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4487 $content{phone} = $self->daytime || $self->night;
4492 my %bop_method2payby = (
4502 if (ref($_[0]) eq 'HASH') {
4503 %options = %{$_[0]};
4505 my ( $method, $amount ) = ( shift, shift );
4507 $options{method} = $method;
4508 $options{amount} = $amount;
4512 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
4513 warn " $_ => $options{$_}\n" foreach keys %options;
4516 return $self->fake_bop(%options) if $options{'fake'};
4518 $self->_bop_defaults(\%options);
4521 # set trans_is_recur based on invnum if there is one
4524 my $trans_is_recur = 0;
4525 if ( $options{'invnum'} ) {
4527 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
4528 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
4531 map { $_->part_pkg }
4533 map { $_->cust_pkg }
4534 $cust_bill->cust_bill_pkg;
4537 if grep { $_->freq ne '0' } @part_pkg;
4545 my $payment_gateway = $self->_payment_gateway( \%options );
4546 my $namespace = $payment_gateway->gateway_namespace;
4548 eval "use $namespace";
4552 # check for banned credit card/ACH
4555 my $ban = qsearchs('banned_pay', {
4556 'payby' => $bop_method2payby{$options{method}},
4557 'payinfo' => md5_base64($options{payinfo}),
4559 return "Banned credit card" if $ban;
4565 my $bop_content = $self->_bop_content(\%options);
4566 return $bop_content unless ref($bop_content);
4568 my @invoicing_list = $self->invoicing_list_emailonly;
4569 if ( $conf->exists('emailinvoiceautoalways')
4570 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4571 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4572 push @invoicing_list, $self->all_emails;
4575 my $email = ($conf->exists('business-onlinepayment-email-override'))
4576 ? $conf->config('business-onlinepayment-email-override')
4577 : $invoicing_list[0];
4581 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
4583 $content{card_number} = $options{payinfo};
4584 $paydate = exists($options{'paydate'})
4585 ? $options{'paydate'}
4587 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4588 $content{expiration} = "$2/$1";
4590 my $paycvv = exists($options{'paycvv'})
4591 ? $options{'paycvv'}
4593 $content{cvv2} = $paycvv
4596 my $paystart_month = exists($options{'paystart_month'})
4597 ? $options{'paystart_month'}
4598 : $self->paystart_month;
4600 my $paystart_year = exists($options{'paystart_year'})
4601 ? $options{'paystart_year'}
4602 : $self->paystart_year;
4604 $content{card_start} = "$paystart_month/$paystart_year"
4605 if $paystart_month && $paystart_year;
4607 my $payissue = exists($options{'payissue'})
4608 ? $options{'payissue'}
4610 $content{issue_number} = $payissue if $payissue;
4612 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
4613 'trans_is_recur' => $trans_is_recur,
4617 $content{recurring_billing} = 'YES';
4618 $content{acct_code} = 'rebill'
4619 if $conf->exists('credit_card-recurring_billing_acct_code');
4622 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
4623 ( $content{account_number}, $content{routing_code} ) =
4624 split('@', $options{payinfo});
4625 $content{bank_name} = $options{payname};
4626 $content{bank_state} = exists($options{'paystate'})
4627 ? $options{'paystate'}
4628 : $self->getfield('paystate');
4629 $content{account_type} = exists($options{'paytype'})
4630 ? uc($options{'paytype'}) || 'CHECKING'
4631 : uc($self->getfield('paytype')) || 'CHECKING';
4632 $content{account_name} = $self->getfield('first'). ' '.
4633 $self->getfield('last');
4635 $content{customer_org} = $self->company ? 'B' : 'I';
4636 $content{state_id} = exists($options{'stateid'})
4637 ? $options{'stateid'}
4638 : $self->getfield('stateid');
4639 $content{state_id_state} = exists($options{'stateid_state'})
4640 ? $options{'stateid_state'}
4641 : $self->getfield('stateid_state');
4642 $content{customer_ssn} = exists($options{'ss'})
4645 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
4646 $content{phone} = $options{payinfo};
4647 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4654 # run transaction(s)
4657 my $balance = exists( $options{'balance'} )
4658 ? $options{'balance'}
4661 $self->select_for_update; #mutex ... just until we get our pending record in
4663 #the checks here are intended to catch concurrent payments
4664 #double-form-submission prevention is taken care of in cust_pay_pending::check
4667 return "The customer's balance has changed; $options{method} transaction aborted."
4668 if $self->balance < $balance;
4669 #&& $self->balance < $options{amount}; #might as well anyway?
4671 #also check and make sure there aren't *other* pending payments for this cust
4673 my @pending = qsearch('cust_pay_pending', {
4674 'custnum' => $self->custnum,
4675 'status' => { op=>'!=', value=>'done' }
4677 return "A payment is already being processed for this customer (".
4678 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4679 "); $options{method} transaction aborted."
4680 if scalar(@pending);
4682 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4684 my $cust_pay_pending = new FS::cust_pay_pending {
4685 'custnum' => $self->custnum,
4686 #'invnum' => $options{'invnum'},
4687 'paid' => $options{amount},
4689 'payby' => $bop_method2payby{$options{method}},
4690 'payinfo' => $options{payinfo},
4691 'paydate' => $paydate,
4692 'recurring_billing' => $content{recurring_billing},
4693 'pkgnum' => $options{'pkgnum'},
4695 'gatewaynum' => $payment_gateway->gatewaynum || '',
4696 'session_id' => $options{session_id} || '',
4697 'jobnum' => $options{depend_jobnum} || '',
4699 $cust_pay_pending->payunique( $options{payunique} )
4700 if defined($options{payunique}) && length($options{payunique});
4701 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4702 return $cpp_new_err if $cpp_new_err;
4704 my( $action1, $action2 ) =
4705 split( /\s*\,\s*/, $payment_gateway->gateway_action );
4707 my $transaction = new $namespace( $payment_gateway->gateway_module,
4708 $self->_bop_options(\%options),
4711 $transaction->content(
4712 'type' => $options{method},
4713 $self->_bop_auth(\%options),
4714 'action' => $action1,
4715 'description' => $options{'description'},
4716 'amount' => $options{amount},
4717 #'invoice_number' => $options{'invnum'},
4718 'customer_id' => $self->custnum,
4720 'reference' => $cust_pay_pending->paypendingnum, #for now
4725 $cust_pay_pending->status('pending');
4726 my $cpp_pending_err = $cust_pay_pending->replace;
4727 return $cpp_pending_err if $cpp_pending_err;
4730 my $BOP_TESTING = 0;
4731 my $BOP_TESTING_SUCCESS = 1;
4733 unless ( $BOP_TESTING ) {
4734 $transaction->test_transaction(1)
4735 if $conf->exists('business-onlinepayment-test_transaction');
4736 $transaction->submit();
4738 if ( $BOP_TESTING_SUCCESS ) {
4739 $transaction->is_success(1);
4740 $transaction->authorization('fake auth');
4742 $transaction->is_success(0);
4743 $transaction->error_message('fake failure');
4747 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4749 return { reference => $cust_pay_pending->paypendingnum,
4750 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
4752 } elsif ( $transaction->is_success() && $action2 ) {
4754 $cust_pay_pending->status('authorized');
4755 my $cpp_authorized_err = $cust_pay_pending->replace;
4756 return $cpp_authorized_err if $cpp_authorized_err;
4758 my $auth = $transaction->authorization;
4759 my $ordernum = $transaction->can('order_number')
4760 ? $transaction->order_number
4764 new Business::OnlinePayment( $payment_gateway->gateway_module,
4765 $self->_bop_options(\%options),
4770 type => $options{method},
4772 $self->_bop_auth(\%options),
4773 order_number => $ordernum,
4774 amount => $options{amount},
4775 authorization => $auth,
4776 description => $options{'description'},
4779 foreach my $field (qw( authorization_source_code returned_ACI
4780 transaction_identifier validation_code
4781 transaction_sequence_num local_transaction_date
4782 local_transaction_time AVS_result_code )) {
4783 $capture{$field} = $transaction->$field() if $transaction->can($field);
4786 $capture->content( %capture );
4788 $capture->test_transaction(1)
4789 if $conf->exists('business-onlinepayment-test_transaction');
4792 unless ( $capture->is_success ) {
4793 my $e = "Authorization successful but capture failed, custnum #".
4794 $self->custnum. ': '. $capture->result_code.
4795 ": ". $capture->error_message;
4803 # remove paycvv after initial transaction
4806 #false laziness w/misc/process/payment.cgi - check both to make sure working
4808 if ( defined $self->dbdef_table->column('paycvv')
4809 && length($self->paycvv)
4810 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
4812 my $error = $self->remove_cvv;
4814 warn "WARNING: error removing cvv: $error\n";
4823 if ( $transaction->can('card_token') && $transaction->card_token ) {
4825 $self->card_token($transaction->card_token);
4827 if ( $options{'payinfo'} eq $self->payinfo ) {
4828 $self->payinfo($transaction->card_token);
4829 my $error = $self->replace;
4831 warn "WARNING: error storing token: $error, but proceeding anyway\n";
4841 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
4853 if (ref($_[0]) eq 'HASH') {
4854 %options = %{$_[0]};
4856 my ( $method, $amount ) = ( shift, shift );
4858 $options{method} = $method;
4859 $options{amount} = $amount;
4862 if ( $options{'fake_failure'} ) {
4863 return "Error: No error; test failure requested with fake_failure";
4867 #if ( $payment_gateway->gatewaynum ) { # agent override
4868 # $paybatch = $payment_gateway->gatewaynum. '-';
4871 #$paybatch .= "$processor:". $transaction->authorization;
4873 #$paybatch .= ':'. $transaction->order_number
4874 # if $transaction->can('order_number')
4875 # && length($transaction->order_number);
4877 my $paybatch = 'FakeProcessor:54:32';
4879 my $cust_pay = new FS::cust_pay ( {
4880 'custnum' => $self->custnum,
4881 'invnum' => $options{'invnum'},
4882 'paid' => $options{amount},
4884 'payby' => $bop_method2payby{$options{method}},
4885 #'payinfo' => $payinfo,
4886 'payinfo' => '4111111111111111',
4887 'paybatch' => $paybatch,
4888 #'paydate' => $paydate,
4889 'paydate' => '2012-05-01',
4891 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
4893 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4896 $cust_pay->invnum(''); #try again with no specific invnum
4897 my $error2 = $cust_pay->insert( $options{'manual'} ?
4898 ( 'manual' => 1 ) : ()
4901 # gah, even with transactions.
4902 my $e = 'WARNING: Card/ACH debited but database not updated - '.
4903 "error inserting (fake!) payment: $error2".
4904 " (previously tried insert with invnum #$options{'invnum'}" .
4911 if ( $options{'paynum_ref'} ) {
4912 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4915 return ''; #no error
4920 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
4922 # Wraps up processing of a realtime credit card, ACH (electronic check) or
4923 # phone bill transaction.
4925 sub _realtime_bop_result {
4926 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
4928 warn "$me _realtime_bop_result: pending transaction ".
4929 $cust_pay_pending->paypendingnum. "\n";
4930 warn " $_ => $options{$_}\n" foreach keys %options;
4933 my $payment_gateway = $options{payment_gateway}
4934 or return "no payment gateway in arguments to _realtime_bop_result";
4936 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
4937 my $cpp_captured_err = $cust_pay_pending->replace;
4938 return $cpp_captured_err if $cpp_captured_err;
4940 if ( $transaction->is_success() ) {
4943 if ( $payment_gateway->gatewaynum ) { # agent override
4944 $paybatch = $payment_gateway->gatewaynum. '-';
4947 $paybatch .= $payment_gateway->gateway_module. ":".
4948 $transaction->authorization;
4950 $paybatch .= ':'. $transaction->order_number
4951 if $transaction->can('order_number')
4952 && length($transaction->order_number);
4954 my $cust_pay = new FS::cust_pay ( {
4955 'custnum' => $self->custnum,
4956 'invnum' => $options{'invnum'},
4957 'paid' => $cust_pay_pending->paid,
4959 'payby' => $cust_pay_pending->payby,
4960 'payinfo' => $options{'payinfo'},
4961 'paybatch' => $paybatch,
4962 'paydate' => $cust_pay_pending->paydate,
4963 'pkgnum' => $cust_pay_pending->pkgnum,
4965 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
4966 $cust_pay->payunique( $options{payunique} )
4967 if defined($options{payunique}) && length($options{payunique});
4969 my $oldAutoCommit = $FS::UID::AutoCommit;
4970 local $FS::UID::AutoCommit = 0;
4973 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
4975 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4978 $cust_pay->invnum(''); #try again with no specific invnum
4979 my $error2 = $cust_pay->insert( $options{'manual'} ?
4980 ( 'manual' => 1 ) : ()
4983 # gah. but at least we have a record of the state we had to abort in
4984 # from cust_pay_pending now.
4985 my $e = "WARNING: $options{method} captured but payment not recorded -".
4986 " error inserting payment (". $payment_gateway->gateway_module.
4988 " (previously tried insert with invnum #$options{'invnum'}" .
4989 ": $error ) - pending payment saved as paypendingnum ".
4990 $cust_pay_pending->paypendingnum. "\n";
4996 my $jobnum = $cust_pay_pending->jobnum;
4998 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5000 unless ( $placeholder ) {
5001 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5002 my $e = "WARNING: $options{method} captured but job $jobnum not ".
5003 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
5008 $error = $placeholder->delete;
5011 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5012 my $e = "WARNING: $options{method} captured but could not delete ".
5013 "job $jobnum for paypendingnum ".
5014 $cust_pay_pending->paypendingnum. ": $error\n";
5021 if ( $options{'paynum_ref'} ) {
5022 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5025 $cust_pay_pending->status('done');
5026 $cust_pay_pending->statustext('captured');
5027 $cust_pay_pending->paynum($cust_pay->paynum);
5028 my $cpp_done_err = $cust_pay_pending->replace;
5030 if ( $cpp_done_err ) {
5032 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5033 my $e = "WARNING: $options{method} captured but payment not recorded - ".
5034 "error updating status for paypendingnum ".
5035 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5041 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5043 if ( $options{'apply'} ) {
5044 my $apply_error = $self->apply_payments_and_credits;
5045 if ( $apply_error ) {
5046 warn "WARNING: error applying payment: $apply_error\n";
5047 #but we still should return no error cause the payment otherwise went
5052 return ''; #no error
5058 my $perror = $payment_gateway->gateway_module. " error: ".
5059 $transaction->error_message;
5061 my $jobnum = $cust_pay_pending->jobnum;
5063 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5065 if ( $placeholder ) {
5066 my $error = $placeholder->depended_delete;
5067 $error ||= $placeholder->delete;
5068 warn "error removing provisioning jobs after declined paypendingnum ".
5069 $cust_pay_pending->paypendingnum. "\n";
5071 my $e = "error finding job $jobnum for declined paypendingnum ".
5072 $cust_pay_pending->paypendingnum. "\n";
5078 unless ( $transaction->error_message ) {
5081 if ( $transaction->can('response_page') ) {
5083 'page' => ( $transaction->can('response_page')
5084 ? $transaction->response_page
5087 'code' => ( $transaction->can('response_code')
5088 ? $transaction->response_code
5091 'headers' => ( $transaction->can('response_headers')
5092 ? $transaction->response_headers
5098 "No additional debugging information available for ".
5099 $payment_gateway->gateway_module;
5102 $perror .= "No error_message returned from ".
5103 $payment_gateway->gateway_module. " -- ".
5104 ( ref($t_response) ? Dumper($t_response) : $t_response );
5108 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
5109 && $conf->exists('emaildecline')
5110 && grep { $_ ne 'POST' } $self->invoicing_list
5111 && ! grep { $transaction->error_message =~ /$_/ }
5112 $conf->config('emaildecline-exclude')
5114 my @templ = $conf->config('declinetemplate');
5115 my $template = new Text::Template (
5117 SOURCE => [ map "$_\n", @templ ],
5118 ) or return "($perror) can't create template: $Text::Template::ERROR";
5119 $template->compile()
5120 or return "($perror) can't compile template: $Text::Template::ERROR";
5124 scalar( $conf->config('company_name', $self->agentnum ) ),
5125 'company_address' =>
5126 join("\n", $conf->config('company_address', $self->agentnum ) ),
5127 'error' => $transaction->error_message,
5130 my $error = send_email(
5131 'from' => $conf->config('invoice_from', $self->agentnum ),
5132 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
5133 'subject' => 'Your payment could not be processed',
5134 'body' => [ $template->fill_in(HASH => $templ_hash) ],
5137 $perror .= " (also received error sending decline notification: $error)"
5142 $cust_pay_pending->status('done');
5143 $cust_pay_pending->statustext("declined: $perror");
5144 my $cpp_done_err = $cust_pay_pending->replace;
5145 if ( $cpp_done_err ) {
5146 my $e = "WARNING: $options{method} declined but pending payment not ".
5147 "resolved - error updating status for paypendingnum ".
5148 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5150 $perror = "$e ($perror)";
5158 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
5160 Verifies successful third party processing of a realtime credit card,
5161 ACH (electronic check) or phone bill transaction via a
5162 Business::OnlineThirdPartyPayment realtime gateway. See
5163 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
5165 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
5167 The additional options I<payname>, I<city>, I<state>,
5168 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5169 if set, will override the value from the customer record.
5171 I<description> is a free-text field passed to the gateway. It defaults to
5172 "Internet services".
5174 If an I<invnum> is specified, this payment (if successful) is applied to the
5175 specified invoice. If you don't specify an I<invnum> you might want to
5176 call the B<apply_payments> method.
5178 I<quiet> can be set true to surpress email decline notices.
5180 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
5181 resulting paynum, if any.
5183 I<payunique> is a unique identifier for this payment.
5185 Returns a hashref containing elements bill_error (which will be undefined
5186 upon success) and session_id of any associated session.
5190 sub realtime_botpp_capture {
5191 my( $self, $cust_pay_pending, %options ) = @_;
5193 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5194 warn " $_ => $options{$_}\n" foreach keys %options;
5197 eval "use Business::OnlineThirdPartyPayment";
5201 # select the gateway
5204 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5206 my $payment_gateway = $cust_pay_pending->gatewaynum
5207 ? qsearchs( 'payment_gateway',
5208 { gatewaynum => $cust_pay_pending->gatewaynum }
5210 : $self->agent->payment_gateway( 'method' => $method,
5211 # 'invnum' => $cust_pay_pending->invnum,
5212 # 'payinfo' => $cust_pay_pending->payinfo,
5215 $options{payment_gateway} = $payment_gateway; # for the helper subs
5221 my @invoicing_list = $self->invoicing_list_emailonly;
5222 if ( $conf->exists('emailinvoiceautoalways')
5223 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5224 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5225 push @invoicing_list, $self->all_emails;
5228 my $email = ($conf->exists('business-onlinepayment-email-override'))
5229 ? $conf->config('business-onlinepayment-email-override')
5230 : $invoicing_list[0];
5234 $content{email_customer} =
5235 ( $conf->exists('business-onlinepayment-email_customer')
5236 || $conf->exists('business-onlinepayment-email-override') );
5239 # run transaction(s)
5243 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5244 $self->_bop_options(\%options),
5247 $transaction->reference({ %options });
5249 $transaction->content(
5251 $self->_bop_auth(\%options),
5252 'action' => 'Post Authorization',
5253 'description' => $options{'description'},
5254 'amount' => $cust_pay_pending->paid,
5255 #'invoice_number' => $options{'invnum'},
5256 'customer_id' => $self->custnum,
5257 'referer' => 'http://cleanwhisker.420.am/',
5258 'reference' => $cust_pay_pending->paypendingnum,
5260 'phone' => $self->daytime || $self->night,
5262 # plus whatever is required for bogus capture avoidance
5265 $transaction->submit();
5268 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5271 bill_error => $error,
5272 session_id => $cust_pay_pending->session_id,
5277 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5281 sub default_payment_gateway {
5282 my( $self, $method ) = @_;
5284 die "Real-time processing not enabled\n"
5285 unless $conf->exists('business-onlinepayment');
5287 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5290 my $bop_config = 'business-onlinepayment';
5291 $bop_config .= '-ach'
5292 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5293 my ( $processor, $login, $password, $action, @bop_options ) =
5294 $conf->config($bop_config);
5295 $action ||= 'normal authorization';
5296 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5297 die "No real-time processor is enabled - ".
5298 "did you set the business-onlinepayment configuration value?\n"
5301 ( $processor, $login, $password, $action, @bop_options )
5306 Removes the I<paycvv> field from the database directly.
5308 If there is an error, returns the error, otherwise returns false.
5314 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5315 or return dbh->errstr;
5316 $sth->execute($self->custnum)
5317 or return $sth->errstr;
5322 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5324 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5325 via a Business::OnlinePayment realtime gateway. See
5326 L<http://420.am/business-onlinepayment> for supported gateways.
5328 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5330 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5332 Most gateways require a reference to an original payment transaction to refund,
5333 so you probably need to specify a I<paynum>.
5335 I<amount> defaults to the original amount of the payment if not specified.
5337 I<reason> specifies a reason for the refund.
5339 I<paydate> specifies the expiration date for a credit card overriding the
5340 value from the customer record or the payment record. Specified as yyyy-mm-dd
5342 Implementation note: If I<amount> is unspecified or equal to the amount of the
5343 orignal payment, first an attempt is made to "void" the transaction via
5344 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5345 the normal attempt is made to "refund" ("credit") the transaction via the
5346 gateway is attempted.
5348 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5349 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5350 #if set, will override the value from the customer record.
5352 #If an I<invnum> is specified, this payment (if successful) is applied to the
5353 #specified invoice. If you don't specify an I<invnum> you might want to
5354 #call the B<apply_payments> method.
5358 #some false laziness w/realtime_bop, not enough to make it worth merging
5359 #but some useful small subs should be pulled out
5360 sub realtime_refund_bop {
5364 if (ref($_[0]) eq 'HASH') {
5365 %options = %{$_[0]};
5369 $options{method} = $method;
5373 warn "$me realtime_refund_bop (new): $options{method} refund\n";
5374 warn " $_ => $options{$_}\n" foreach keys %options;
5378 # look up the original payment and optionally a gateway for that payment
5382 my $amount = $options{'amount'};
5384 my( $processor, $login, $password, @bop_options, $namespace ) ;
5385 my( $auth, $order_number ) = ( '', '', '' );
5387 if ( $options{'paynum'} ) {
5389 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
5390 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5391 or return "Unknown paynum $options{'paynum'}";
5392 $amount ||= $cust_pay->paid;
5394 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5395 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5396 $cust_pay->paybatch;
5397 my $gatewaynum = '';
5398 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5400 if ( $gatewaynum ) { #gateway for the payment to be refunded
5402 my $payment_gateway =
5403 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5404 die "payment gateway $gatewaynum not found"
5405 unless $payment_gateway;
5407 $processor = $payment_gateway->gateway_module;
5408 $login = $payment_gateway->gateway_username;
5409 $password = $payment_gateway->gateway_password;
5410 $namespace = $payment_gateway->gateway_namespace;
5411 @bop_options = $payment_gateway->options;
5413 } else { #try the default gateway
5416 my $payment_gateway =
5417 $self->agent->payment_gateway('method' => $options{method});
5419 ( $conf_processor, $login, $password, $namespace ) =
5420 map { my $method = "gateway_$_"; $payment_gateway->$method }
5421 qw( module username password namespace );
5423 @bop_options = $payment_gateway->gatewaynum
5424 ? $payment_gateway->options
5425 : @{ $payment_gateway->get('options') };
5427 return "processor of payment $options{'paynum'} $processor does not".
5428 " match default processor $conf_processor"
5429 unless $processor eq $conf_processor;
5434 } else { # didn't specify a paynum, so look for agent gateway overrides
5435 # like a normal transaction
5437 my $payment_gateway =
5438 $self->agent->payment_gateway( 'method' => $options{method},
5439 #'payinfo' => $payinfo,
5441 my( $processor, $login, $password, $namespace ) =
5442 map { my $method = "gateway_$_"; $payment_gateway->$method }
5443 qw( module username password namespace );
5445 my @bop_options = $payment_gateway->gatewaynum
5446 ? $payment_gateway->options
5447 : @{ $payment_gateway->get('options') };
5450 return "neither amount nor paynum specified" unless $amount;
5452 eval "use $namespace";
5456 'type' => $options{method},
5458 'password' => $password,
5459 'order_number' => $order_number,
5460 'amount' => $amount,
5461 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5463 $content{authorization} = $auth
5464 if length($auth); #echeck/ACH transactions have an order # but no auth
5465 #(at least with authorize.net)
5467 my $disable_void_after;
5468 if ($conf->exists('disable_void_after')
5469 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5470 $disable_void_after = $1;
5473 #first try void if applicable
5474 if ( $cust_pay && $cust_pay->paid == $amount
5476 ( not defined($disable_void_after) )
5477 || ( time < ($cust_pay->_date + $disable_void_after ) )
5480 warn " attempting void\n" if $DEBUG > 1;
5481 my $void = new Business::OnlinePayment( $processor, @bop_options );
5482 if ( $void->can('info') ) {
5483 if ( $cust_pay->payby eq 'CARD'
5484 && $void->info('CC_void_requires_card') )
5486 $content{'card_number'} = $cust_pay->payinfo;
5487 } elsif ( $cust_pay->payby eq 'CHEK'
5488 && $void->info('ECHECK_void_requires_account') )
5490 ( $content{'account_number'}, $content{'routing_code'} ) =
5491 split('@', $cust_pay->payinfo);
5492 $content{'name'} = $self->get('first'). ' '. $self->get('last');
5495 $void->content( 'action' => 'void', %content );
5496 $void->test_transaction(1)
5497 if $conf->exists('business-onlinepayment-test_transaction');
5499 if ( $void->is_success ) {
5500 my $error = $cust_pay->void($options{'reason'});
5502 # gah, even with transactions.
5503 my $e = 'WARNING: Card/ACH voided but database not updated - '.
5504 "error voiding payment: $error";
5508 warn " void successful\n" if $DEBUG > 1;
5513 warn " void unsuccessful, trying refund\n"
5517 my $address = $self->address1;
5518 $address .= ", ". $self->address2 if $self->address2;
5520 my($payname, $payfirst, $paylast);
5521 if ( $self->payname && $options{method} ne 'ECHECK' ) {
5522 $payname = $self->payname;
5523 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5524 or return "Illegal payname $payname";
5525 ($payfirst, $paylast) = ($1, $2);
5527 $payfirst = $self->getfield('first');
5528 $paylast = $self->getfield('last');
5529 $payname = "$payfirst $paylast";
5532 my @invoicing_list = $self->invoicing_list_emailonly;
5533 if ( $conf->exists('emailinvoiceautoalways')
5534 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5535 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5536 push @invoicing_list, $self->all_emails;
5539 my $email = ($conf->exists('business-onlinepayment-email-override'))
5540 ? $conf->config('business-onlinepayment-email-override')
5541 : $invoicing_list[0];
5543 my $payip = exists($options{'payip'})
5546 $content{customer_ip} = $payip
5550 if ( $options{method} eq 'CC' ) {
5553 $content{card_number} = $payinfo = $cust_pay->payinfo;
5554 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
5555 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
5556 ($content{expiration} = "$2/$1"); # where available
5558 $content{card_number} = $payinfo = $self->payinfo;
5559 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
5560 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5561 $content{expiration} = "$2/$1";
5564 } elsif ( $options{method} eq 'ECHECK' ) {
5567 $payinfo = $cust_pay->payinfo;
5569 $payinfo = $self->payinfo;
5571 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
5572 $content{bank_name} = $self->payname;
5573 $content{account_type} = 'CHECKING';
5574 $content{account_name} = $payname;
5575 $content{customer_org} = $self->company ? 'B' : 'I';
5576 $content{customer_ssn} = $self->ss;
5577 } elsif ( $options{method} eq 'LEC' ) {
5578 $content{phone} = $payinfo = $self->payinfo;
5582 my $refund = new Business::OnlinePayment( $processor, @bop_options );
5583 my %sub_content = $refund->content(
5584 'action' => 'credit',
5585 'customer_id' => $self->custnum,
5586 'last_name' => $paylast,
5587 'first_name' => $payfirst,
5589 'address' => $address,
5590 'city' => $self->city,
5591 'state' => $self->state,
5592 'zip' => $self->zip,
5593 'country' => $self->country,
5595 'phone' => $self->daytime || $self->night,
5598 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
5600 $refund->test_transaction(1)
5601 if $conf->exists('business-onlinepayment-test_transaction');
5604 return "$processor error: ". $refund->error_message
5605 unless $refund->is_success();
5607 my $paybatch = "$processor:". $refund->authorization;
5608 $paybatch .= ':'. $refund->order_number
5609 if $refund->can('order_number') && $refund->order_number;
5611 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
5612 my @cust_bill_pay = $cust_pay->cust_bill_pay;
5613 last unless @cust_bill_pay;
5614 my $cust_bill_pay = pop @cust_bill_pay;
5615 my $error = $cust_bill_pay->delete;
5619 my $cust_refund = new FS::cust_refund ( {
5620 'custnum' => $self->custnum,
5621 'paynum' => $options{'paynum'},
5622 'refund' => $amount,
5624 'payby' => $bop_method2payby{$options{method}},
5625 'payinfo' => $payinfo,
5626 'paybatch' => $paybatch,
5627 'reason' => $options{'reason'} || 'card or ACH refund',
5629 my $error = $cust_refund->insert;
5631 $cust_refund->paynum(''); #try again with no specific paynum
5632 my $error2 = $cust_refund->insert;
5634 # gah, even with transactions.
5635 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
5636 "error inserting refund ($processor): $error2".
5637 " (previously tried insert with paynum #$options{'paynum'}" .
5648 =item batch_card OPTION => VALUE...
5650 Adds a payment for this invoice to the pending credit card batch (see
5651 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
5652 runs the payment using a realtime gateway.
5657 my ($self, %options) = @_;
5660 if (exists($options{amount})) {
5661 $amount = $options{amount};
5663 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
5665 return '' unless $amount > 0;
5667 my $invnum = delete $options{invnum};
5668 my $payby = $options{invnum} || $self->payby; #dubious
5670 if ($options{'realtime'}) {
5671 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
5677 my $oldAutoCommit = $FS::UID::AutoCommit;
5678 local $FS::UID::AutoCommit = 0;
5681 #this needs to handle mysql as well as Pg, like svc_acct.pm
5682 #(make it into a common function if folks need to do batching with mysql)
5683 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
5684 or return "Cannot lock pay_batch: " . $dbh->errstr;
5688 'payby' => FS::payby->payby2payment($payby),
5691 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
5693 unless ( $pay_batch ) {
5694 $pay_batch = new FS::pay_batch \%pay_batch;
5695 my $error = $pay_batch->insert;
5697 $dbh->rollback if $oldAutoCommit;
5698 die "error creating new batch: $error\n";
5702 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
5703 'batchnum' => $pay_batch->batchnum,
5704 'custnum' => $self->custnum,
5707 foreach (qw( address1 address2 city state zip country payby payinfo paydate
5709 $options{$_} = '' unless exists($options{$_});
5712 my $cust_pay_batch = new FS::cust_pay_batch ( {
5713 'batchnum' => $pay_batch->batchnum,
5714 'invnum' => $invnum || 0, # is there a better value?
5715 # this field should be
5717 # cust_bill_pay_batch now
5718 'custnum' => $self->custnum,
5719 'last' => $self->getfield('last'),
5720 'first' => $self->getfield('first'),
5721 'address1' => $options{address1} || $self->address1,
5722 'address2' => $options{address2} || $self->address2,
5723 'city' => $options{city} || $self->city,
5724 'state' => $options{state} || $self->state,
5725 'zip' => $options{zip} || $self->zip,
5726 'country' => $options{country} || $self->country,
5727 'payby' => $options{payby} || $self->payby,
5728 'payinfo' => $options{payinfo} || $self->payinfo,
5729 'exp' => $options{paydate} || $self->paydate,
5730 'payname' => $options{payname} || $self->payname,
5731 'amount' => $amount, # consolidating
5734 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
5735 if $old_cust_pay_batch;
5738 if ($old_cust_pay_batch) {
5739 $error = $cust_pay_batch->replace($old_cust_pay_batch)
5741 $error = $cust_pay_batch->insert;
5745 $dbh->rollback if $oldAutoCommit;
5749 my $unapplied = $self->total_unapplied_credits
5750 + $self->total_unapplied_payments
5751 + $self->in_transit_payments;
5752 foreach my $cust_bill ($self->open_cust_bill) {
5753 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
5754 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
5755 'invnum' => $cust_bill->invnum,
5756 'paybatchnum' => $cust_pay_batch->paybatchnum,
5757 'amount' => $cust_bill->owed,
5760 if ($unapplied >= $cust_bill_pay_batch->amount){
5761 $unapplied -= $cust_bill_pay_batch->amount;
5764 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
5765 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
5767 $error = $cust_bill_pay_batch->insert;
5769 $dbh->rollback if $oldAutoCommit;
5774 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5778 =item apply_payments_and_credits [ OPTION => VALUE ... ]
5780 Applies unapplied payments and credits.
5782 In most cases, this new method should be used in place of sequential
5783 apply_payments and apply_credits methods.
5785 A hash of optional arguments may be passed. Currently "manual" is supported.
5786 If true, a payment receipt is sent instead of a statement when
5787 'payment_receipt_email' configuration option is set.
5789 If there is an error, returns the error, otherwise returns false.
5793 sub apply_payments_and_credits {
5794 my( $self, %options ) = @_;
5796 local $SIG{HUP} = 'IGNORE';
5797 local $SIG{INT} = 'IGNORE';
5798 local $SIG{QUIT} = 'IGNORE';
5799 local $SIG{TERM} = 'IGNORE';
5800 local $SIG{TSTP} = 'IGNORE';
5801 local $SIG{PIPE} = 'IGNORE';
5803 my $oldAutoCommit = $FS::UID::AutoCommit;
5804 local $FS::UID::AutoCommit = 0;
5807 $self->select_for_update; #mutex
5809 foreach my $cust_bill ( $self->open_cust_bill ) {
5810 my $error = $cust_bill->apply_payments_and_credits(%options);
5812 $dbh->rollback if $oldAutoCommit;
5813 return "Error applying: $error";
5817 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5822 =item apply_credits OPTION => VALUE ...
5824 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
5825 to outstanding invoice balances in chronological order (or reverse
5826 chronological order if the I<order> option is set to B<newest>) and returns the
5827 value of any remaining unapplied credits available for refund (see
5828 L<FS::cust_refund>).
5830 Dies if there is an error.
5838 local $SIG{HUP} = 'IGNORE';
5839 local $SIG{INT} = 'IGNORE';
5840 local $SIG{QUIT} = 'IGNORE';
5841 local $SIG{TERM} = 'IGNORE';
5842 local $SIG{TSTP} = 'IGNORE';
5843 local $SIG{PIPE} = 'IGNORE';
5845 my $oldAutoCommit = $FS::UID::AutoCommit;
5846 local $FS::UID::AutoCommit = 0;
5849 $self->select_for_update; #mutex
5851 unless ( $self->total_unapplied_credits ) {
5852 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5856 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
5857 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
5859 my @invoices = $self->open_cust_bill;
5860 @invoices = sort { $b->_date <=> $a->_date } @invoices
5861 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
5863 if ( $conf->exists('pkg-balances') ) {
5864 # limit @credits to those w/ a pkgnum grepped from $self
5866 foreach my $i (@invoices) {
5867 foreach my $li ( $i->cust_bill_pkg ) {
5868 $pkgnums{$li->pkgnum} = 1;
5871 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
5876 foreach my $cust_bill ( @invoices ) {
5878 if ( !defined($credit) || $credit->credited == 0) {
5879 $credit = pop @credits or last;
5883 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
5884 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
5886 $owed = $cust_bill->owed;
5888 unless ( $owed > 0 ) {
5889 push @credits, $credit;
5893 my $amount = min( $credit->credited, $owed );
5895 my $cust_credit_bill = new FS::cust_credit_bill ( {
5896 'crednum' => $credit->crednum,
5897 'invnum' => $cust_bill->invnum,
5898 'amount' => $amount,
5900 $cust_credit_bill->pkgnum( $credit->pkgnum )
5901 if $conf->exists('pkg-balances') && $credit->pkgnum;
5902 my $error = $cust_credit_bill->insert;
5904 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5908 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5912 my $total_unapplied_credits = $self->total_unapplied_credits;
5914 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5916 return $total_unapplied_credits;
5919 =item apply_payments [ OPTION => VALUE ... ]
5921 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
5922 to outstanding invoice balances in chronological order.
5924 #and returns the value of any remaining unapplied payments.
5926 A hash of optional arguments may be passed. Currently "manual" is supported.
5927 If true, a payment receipt is sent instead of a statement when
5928 'payment_receipt_email' configuration option is set.
5930 Dies if there is an error.
5934 sub apply_payments {
5935 my( $self, %options ) = @_;
5937 local $SIG{HUP} = 'IGNORE';
5938 local $SIG{INT} = 'IGNORE';
5939 local $SIG{QUIT} = 'IGNORE';
5940 local $SIG{TERM} = 'IGNORE';
5941 local $SIG{TSTP} = 'IGNORE';
5942 local $SIG{PIPE} = 'IGNORE';
5944 my $oldAutoCommit = $FS::UID::AutoCommit;
5945 local $FS::UID::AutoCommit = 0;
5948 $self->select_for_update; #mutex
5952 my @payments = sort { $b->_date <=> $a->_date }
5953 grep { $_->unapplied > 0 }
5956 my @invoices = sort { $a->_date <=> $b->_date}
5957 grep { $_->owed > 0 }
5960 if ( $conf->exists('pkg-balances') ) {
5961 # limit @payments to those w/ a pkgnum grepped from $self
5963 foreach my $i (@invoices) {
5964 foreach my $li ( $i->cust_bill_pkg ) {
5965 $pkgnums{$li->pkgnum} = 1;
5968 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
5973 foreach my $cust_bill ( @invoices ) {
5975 if ( !defined($payment) || $payment->unapplied == 0 ) {
5976 $payment = pop @payments or last;
5980 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
5981 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
5983 $owed = $cust_bill->owed;
5985 unless ( $owed > 0 ) {
5986 push @payments, $payment;
5990 my $amount = min( $payment->unapplied, $owed );
5992 my $cust_bill_pay = new FS::cust_bill_pay ( {
5993 'paynum' => $payment->paynum,
5994 'invnum' => $cust_bill->invnum,
5995 'amount' => $amount,
5997 $cust_bill_pay->pkgnum( $payment->pkgnum )
5998 if $conf->exists('pkg-balances') && $payment->pkgnum;
5999 my $error = $cust_bill_pay->insert(%options);
6001 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6005 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6009 my $total_unapplied_payments = $self->total_unapplied_payments;
6011 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6013 return $total_unapplied_payments;
6018 Returns the total owed for this customer on all invoices
6019 (see L<FS::cust_bill/owed>).
6025 $self->total_owed_date(2145859200); #12/31/2037
6028 =item total_owed_date TIME
6030 Returns the total owed for this customer on all invoices with date earlier than
6031 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6032 see L<Time::Local> and L<Date::Parse> for conversion functions.
6036 sub total_owed_date {
6040 my $custnum = $self->custnum;
6042 my $owed_sql = FS::cust_bill->owed_sql;
6045 SELECT SUM($owed_sql) FROM cust_bill
6046 WHERE custnum = $custnum
6050 sprintf( "%.2f", $self->scalar_sql($sql) );
6054 =item total_owed_pkgnum PKGNUM
6056 Returns the total owed on all invoices for this customer's specific package
6057 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
6061 sub total_owed_pkgnum {
6062 my( $self, $pkgnum ) = @_;
6063 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
6066 =item total_owed_date_pkgnum TIME PKGNUM
6068 Returns the total owed for this customer's specific package when using
6069 experimental package balances on all invoices with date earlier than
6070 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6071 see L<Time::Local> and L<Date::Parse> for conversion functions.
6075 sub total_owed_date_pkgnum {
6076 my( $self, $time, $pkgnum ) = @_;
6079 foreach my $cust_bill (
6080 grep { $_->_date <= $time }
6081 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6083 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
6085 sprintf( "%.2f", $total_bill );
6091 Returns the total amount of all payments.
6098 $total += $_->paid foreach $self->cust_pay;
6099 sprintf( "%.2f", $total );
6102 =item total_unapplied_credits
6104 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6105 customer. See L<FS::cust_credit/credited>.
6107 =item total_credited
6109 Old name for total_unapplied_credits. Don't use.
6113 sub total_credited {
6114 #carp "total_credited deprecated, use total_unapplied_credits";
6115 shift->total_unapplied_credits(@_);
6118 sub total_unapplied_credits {
6121 my $custnum = $self->custnum;
6123 my $unapplied_sql = FS::cust_credit->unapplied_sql;
6126 SELECT SUM($unapplied_sql) FROM cust_credit
6127 WHERE custnum = $custnum
6130 sprintf( "%.2f", $self->scalar_sql($sql) );
6134 =item total_unapplied_credits_pkgnum PKGNUM
6136 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6137 customer. See L<FS::cust_credit/credited>.
6141 sub total_unapplied_credits_pkgnum {
6142 my( $self, $pkgnum ) = @_;
6143 my $total_credit = 0;
6144 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
6145 sprintf( "%.2f", $total_credit );
6149 =item total_unapplied_payments
6151 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
6152 See L<FS::cust_pay/unapplied>.
6156 sub total_unapplied_payments {
6159 my $custnum = $self->custnum;
6161 my $unapplied_sql = FS::cust_pay->unapplied_sql;
6164 SELECT SUM($unapplied_sql) FROM cust_pay
6165 WHERE custnum = $custnum
6168 sprintf( "%.2f", $self->scalar_sql($sql) );
6172 =item total_unapplied_payments_pkgnum PKGNUM
6174 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
6175 specific package when using experimental package balances. See
6176 L<FS::cust_pay/unapplied>.
6180 sub total_unapplied_payments_pkgnum {
6181 my( $self, $pkgnum ) = @_;
6182 my $total_unapplied = 0;
6183 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
6184 sprintf( "%.2f", $total_unapplied );
6188 =item total_unapplied_refunds
6190 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
6191 customer. See L<FS::cust_refund/unapplied>.
6195 sub total_unapplied_refunds {
6197 my $custnum = $self->custnum;
6199 my $unapplied_sql = FS::cust_refund->unapplied_sql;
6202 SELECT SUM($unapplied_sql) FROM cust_refund
6203 WHERE custnum = $custnum
6206 sprintf( "%.2f", $self->scalar_sql($sql) );
6212 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6213 total_unapplied_credits minus total_unapplied_payments).
6219 $self->balance_date_range;
6222 =item balance_date TIME
6224 Returns the balance for this customer, only considering invoices with date
6225 earlier than TIME (total_owed_date minus total_credited minus
6226 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
6227 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
6234 $self->balance_date_range(shift);
6237 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
6239 Returns the balance for this customer, optionally considering invoices with
6240 date earlier than START_TIME, and not later than END_TIME
6241 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
6243 Times are specified as SQL fragments or numeric
6244 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
6245 L<Date::Parse> for conversion functions. The empty string can be passed
6246 to disable that time constraint completely.
6248 Available options are:
6252 =item unapplied_date
6254 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)
6260 sub balance_date_range {
6262 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
6263 ') FROM cust_main WHERE custnum='. $self->custnum;
6264 sprintf( "%.2f", $self->scalar_sql($sql) );
6267 =item balance_pkgnum PKGNUM
6269 Returns the balance for this customer's specific package when using
6270 experimental package balances (total_owed plus total_unrefunded, minus
6271 total_unapplied_credits minus total_unapplied_payments)
6275 sub balance_pkgnum {
6276 my( $self, $pkgnum ) = @_;
6279 $self->total_owed_pkgnum($pkgnum)
6280 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6281 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
6282 - $self->total_unapplied_credits_pkgnum($pkgnum)
6283 - $self->total_unapplied_payments_pkgnum($pkgnum)
6287 =item in_transit_payments
6289 Returns the total of requests for payments for this customer pending in
6290 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
6294 sub in_transit_payments {
6296 my $in_transit_payments = 0;
6297 foreach my $pay_batch ( qsearch('pay_batch', {
6300 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6301 'batchnum' => $pay_batch->batchnum,
6302 'custnum' => $self->custnum,
6304 $in_transit_payments += $cust_pay_batch->amount;
6307 sprintf( "%.2f", $in_transit_payments );
6312 Returns a hash of useful information for making a payment.
6322 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6323 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6324 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6328 For credit card transactions:
6340 For electronic check transactions:
6355 $return{balance} = $self->balance;
6357 $return{payname} = $self->payname
6358 || ( $self->first. ' '. $self->get('last') );
6360 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6362 $return{payby} = $self->payby;
6363 $return{stateid_state} = $self->stateid_state;
6365 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6366 $return{card_type} = cardtype($self->payinfo);
6367 $return{payinfo} = $self->paymask;
6369 @return{'month', 'year'} = $self->paydate_monthyear;
6373 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6374 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6375 $return{payinfo1} = $payinfo1;
6376 $return{payinfo2} = $payinfo2;
6377 $return{paytype} = $self->paytype;
6378 $return{paystate} = $self->paystate;
6382 #doubleclick protection
6384 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6390 =item paydate_monthyear
6392 Returns a two-element list consisting of the month and year of this customer's
6393 paydate (credit card expiration date for CARD customers)
6397 sub paydate_monthyear {
6399 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6401 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6408 =item tax_exemption TAXNAME
6413 my( $self, $taxname ) = @_;
6415 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6416 'taxname' => $taxname,
6421 =item cust_main_exemption
6425 sub cust_main_exemption {
6427 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6430 =item invoicing_list [ ARRAYREF ]
6432 If an arguement is given, sets these email addresses as invoice recipients
6433 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
6434 (except as warnings), so use check_invoicing_list first.
6436 Returns a list of email addresses (with svcnum entries expanded).
6438 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
6439 check it without disturbing anything by passing nothing.
6441 This interface may change in the future.
6445 sub invoicing_list {
6446 my( $self, $arrayref ) = @_;
6449 my @cust_main_invoice;
6450 if ( $self->custnum ) {
6451 @cust_main_invoice =
6452 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6454 @cust_main_invoice = ();
6456 foreach my $cust_main_invoice ( @cust_main_invoice ) {
6457 #warn $cust_main_invoice->destnum;
6458 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6459 #warn $cust_main_invoice->destnum;
6460 my $error = $cust_main_invoice->delete;
6461 warn $error if $error;
6464 if ( $self->custnum ) {
6465 @cust_main_invoice =
6466 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6468 @cust_main_invoice = ();
6470 my %seen = map { $_->address => 1 } @cust_main_invoice;
6471 foreach my $address ( @{$arrayref} ) {
6472 next if exists $seen{$address} && $seen{$address};
6473 $seen{$address} = 1;
6474 my $cust_main_invoice = new FS::cust_main_invoice ( {
6475 'custnum' => $self->custnum,
6478 my $error = $cust_main_invoice->insert;
6479 warn $error if $error;
6483 if ( $self->custnum ) {
6485 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6492 =item check_invoicing_list ARRAYREF
6494 Checks these arguements as valid input for the invoicing_list method. If there
6495 is an error, returns the error, otherwise returns false.
6499 sub check_invoicing_list {
6500 my( $self, $arrayref ) = @_;
6502 foreach my $address ( @$arrayref ) {
6504 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6505 return 'Can\'t add FAX invoice destination with a blank FAX number.';
6508 my $cust_main_invoice = new FS::cust_main_invoice ( {
6509 'custnum' => $self->custnum,
6512 my $error = $self->custnum
6513 ? $cust_main_invoice->check
6514 : $cust_main_invoice->checkdest
6516 return $error if $error;
6520 return "Email address required"
6521 if $conf->exists('cust_main-require_invoicing_list_email')
6522 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6527 =item set_default_invoicing_list
6529 Sets the invoicing list to all accounts associated with this customer,
6530 overwriting any previous invoicing list.
6534 sub set_default_invoicing_list {
6536 $self->invoicing_list($self->all_emails);
6541 Returns the email addresses of all accounts provisioned for this customer.
6548 foreach my $cust_pkg ( $self->all_pkgs ) {
6549 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6551 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6552 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6554 $list{$_}=1 foreach map { $_->email } @svc_acct;
6559 =item invoicing_list_addpost
6561 Adds postal invoicing to this customer. If this customer is already configured
6562 to receive postal invoices, does nothing.
6566 sub invoicing_list_addpost {
6568 return if grep { $_ eq 'POST' } $self->invoicing_list;
6569 my @invoicing_list = $self->invoicing_list;
6570 push @invoicing_list, 'POST';
6571 $self->invoicing_list(\@invoicing_list);
6574 =item invoicing_list_emailonly
6576 Returns the list of email invoice recipients (invoicing_list without non-email
6577 destinations such as POST and FAX).
6581 sub invoicing_list_emailonly {
6583 warn "$me invoicing_list_emailonly called"
6585 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
6588 =item invoicing_list_emailonly_scalar
6590 Returns the list of email invoice recipients (invoicing_list without non-email
6591 destinations such as POST and FAX) as a comma-separated scalar.
6595 sub invoicing_list_emailonly_scalar {
6597 warn "$me invoicing_list_emailonly_scalar called"
6599 join(', ', $self->invoicing_list_emailonly);
6602 =item referral_custnum_cust_main
6604 Returns the customer who referred this customer (or the empty string, if
6605 this customer was not referred).
6607 Note the difference with referral_cust_main method: This method,
6608 referral_custnum_cust_main returns the single customer (if any) who referred
6609 this customer, while referral_cust_main returns an array of customers referred
6614 sub referral_custnum_cust_main {
6616 return '' unless $self->referral_custnum;
6617 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6620 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
6622 Returns an array of customers referred by this customer (referral_custnum set
6623 to this custnum). If DEPTH is given, recurses up to the given depth, returning
6624 customers referred by customers referred by this customer and so on, inclusive.
6625 The default behavior is DEPTH 1 (no recursion).
6627 Note the difference with referral_custnum_cust_main method: This method,
6628 referral_cust_main, returns an array of customers referred BY this customer,
6629 while referral_custnum_cust_main returns the single customer (if any) who
6630 referred this customer.
6634 sub referral_cust_main {
6636 my $depth = @_ ? shift : 1;
6637 my $exclude = @_ ? shift : {};
6640 map { $exclude->{$_->custnum}++; $_; }
6641 grep { ! $exclude->{ $_->custnum } }
6642 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
6646 map { $_->referral_cust_main($depth-1, $exclude) }
6653 =item referral_cust_main_ncancelled
6655 Same as referral_cust_main, except only returns customers with uncancelled
6660 sub referral_cust_main_ncancelled {
6662 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
6665 =item referral_cust_pkg [ DEPTH ]
6667 Like referral_cust_main, except returns a flat list of all unsuspended (and
6668 uncancelled) packages for each customer. The number of items in this list may
6669 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
6673 sub referral_cust_pkg {
6675 my $depth = @_ ? shift : 1;
6677 map { $_->unsuspended_pkgs }
6678 grep { $_->unsuspended_pkgs }
6679 $self->referral_cust_main($depth);
6682 =item referring_cust_main
6684 Returns the single cust_main record for the customer who referred this customer
6685 (referral_custnum), or false.
6689 sub referring_cust_main {
6691 return '' unless $self->referral_custnum;
6692 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6695 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
6697 Applies a credit to this customer. If there is an error, returns the error,
6698 otherwise returns false.
6700 REASON can be a text string, an FS::reason object, or a scalar reference to
6701 a reasonnum. If a text string, it will be automatically inserted as a new
6702 reason, and a 'reason_type' option must be passed to indicate the
6703 FS::reason_type for the new reason.
6705 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
6707 Any other options are passed to FS::cust_credit::insert.
6712 my( $self, $amount, $reason, %options ) = @_;
6714 my $cust_credit = new FS::cust_credit {
6715 'custnum' => $self->custnum,
6716 'amount' => $amount,
6719 if ( ref($reason) ) {
6721 if ( ref($reason) eq 'SCALAR' ) {
6722 $cust_credit->reasonnum( $$reason );
6724 $cust_credit->reasonnum( $reason->reasonnum );
6728 $cust_credit->set('reason', $reason)
6731 for (qw( addlinfo eventnum )) {
6732 $cust_credit->$_( delete $options{$_} )
6733 if exists($options{$_});
6736 $cust_credit->insert(%options);
6740 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
6742 Creates a one-time charge for this customer. If there is an error, returns
6743 the error, otherwise returns false.
6745 New-style, with a hashref of options:
6747 my $error = $cust_main->charge(
6751 'start_date' => str2time('7/4/2009'),
6752 'pkg' => 'Description',
6753 'comment' => 'Comment',
6754 'additional' => [], #extra invoice detail
6755 'classnum' => 1, #pkg_class
6757 'setuptax' => '', # or 'Y' for tax exempt
6760 'taxclass' => 'Tax class',
6763 'taxproduct' => 2, #part_pkg_taxproduct
6764 'override' => {}, #XXX describe
6766 #will be filled in with the new object
6767 'cust_pkg_ref' => \$cust_pkg,
6769 #generate an invoice immediately
6771 'invoice_terms' => '', #with these terms
6777 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
6783 my ( $amount, $quantity, $start_date, $classnum );
6784 my ( $pkg, $comment, $additional );
6785 my ( $setuptax, $taxclass ); #internal taxes
6786 my ( $taxproduct, $override ); #vendor (CCH) taxes
6788 my $cust_pkg_ref = '';
6789 my ( $bill_now, $invoice_terms ) = ( 0, '' );
6790 if ( ref( $_[0] ) ) {
6791 $amount = $_[0]->{amount};
6792 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
6793 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
6794 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
6795 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
6796 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
6797 : '$'. sprintf("%.2f",$amount);
6798 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
6799 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
6800 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
6801 $additional = $_[0]->{additional} || [];
6802 $taxproduct = $_[0]->{taxproductnum};
6803 $override = { '' => $_[0]->{tax_override} };
6804 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
6805 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
6806 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
6811 $pkg = @_ ? shift : 'One-time charge';
6812 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
6814 $taxclass = @_ ? shift : '';
6818 local $SIG{HUP} = 'IGNORE';
6819 local $SIG{INT} = 'IGNORE';
6820 local $SIG{QUIT} = 'IGNORE';
6821 local $SIG{TERM} = 'IGNORE';
6822 local $SIG{TSTP} = 'IGNORE';
6823 local $SIG{PIPE} = 'IGNORE';
6825 my $oldAutoCommit = $FS::UID::AutoCommit;
6826 local $FS::UID::AutoCommit = 0;
6829 my $part_pkg = new FS::part_pkg ( {
6831 'comment' => $comment,
6835 'classnum' => ( $classnum ? $classnum : '' ),
6836 'setuptax' => $setuptax,
6837 'taxclass' => $taxclass,
6838 'taxproductnum' => $taxproduct,
6841 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
6842 ( 0 .. @$additional - 1 )
6844 'additional_count' => scalar(@$additional),
6845 'setup_fee' => $amount,
6848 my $error = $part_pkg->insert( options => \%options,
6849 tax_overrides => $override,
6852 $dbh->rollback if $oldAutoCommit;
6856 my $pkgpart = $part_pkg->pkgpart;
6857 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
6858 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
6859 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
6860 $error = $type_pkgs->insert;
6862 $dbh->rollback if $oldAutoCommit;
6867 my $cust_pkg = new FS::cust_pkg ( {
6868 'custnum' => $self->custnum,
6869 'pkgpart' => $pkgpart,
6870 'quantity' => $quantity,
6871 'start_date' => $start_date,
6872 'no_auto' => $no_auto,
6875 $error = $cust_pkg->insert;
6877 $dbh->rollback if $oldAutoCommit;
6879 } elsif ( $cust_pkg_ref ) {
6880 ${$cust_pkg_ref} = $cust_pkg;
6884 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
6885 'pkg_list' => [ $cust_pkg ],
6888 $dbh->rollback if $oldAutoCommit;
6893 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6898 #=item charge_postal_fee
6900 #Applies a one time charge this customer. If there is an error,
6901 #returns the error, returns the cust_pkg charge object or false
6902 #if there was no charge.
6906 # This should be a customer event. For that to work requires that bill
6907 # also be a customer event.
6909 sub charge_postal_fee {
6912 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
6913 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
6915 my $cust_pkg = new FS::cust_pkg ( {
6916 'custnum' => $self->custnum,
6917 'pkgpart' => $pkgpart,
6921 my $error = $cust_pkg->insert;
6922 $error ? $error : $cust_pkg;
6927 Returns all the invoices (see L<FS::cust_bill>) for this customer.
6933 map { $_ } #return $self->num_cust_bill unless wantarray;
6934 sort { $a->_date <=> $b->_date }
6935 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6938 =item open_cust_bill
6940 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
6945 sub open_cust_bill {
6949 'table' => 'cust_bill',
6950 'hashref' => { 'custnum' => $self->custnum, },
6951 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
6952 'order_by' => 'ORDER BY _date ASC',
6957 =item cust_statements
6959 Returns all the statements (see L<FS::cust_statement>) for this customer.
6963 sub cust_statement {
6965 map { $_ } #return $self->num_cust_statement unless wantarray;
6966 sort { $a->_date <=> $b->_date }
6967 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
6972 Returns all the credits (see L<FS::cust_credit>) for this customer.
6978 map { $_ } #return $self->num_cust_credit unless wantarray;
6979 sort { $a->_date <=> $b->_date }
6980 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
6983 =item cust_credit_pkgnum
6985 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
6986 package when using experimental package balances.
6990 sub cust_credit_pkgnum {
6991 my( $self, $pkgnum ) = @_;
6992 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
6993 sort { $a->_date <=> $b->_date }
6994 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
6995 'pkgnum' => $pkgnum,
7002 Returns all the payments (see L<FS::cust_pay>) for this customer.
7008 return $self->num_cust_pay unless wantarray;
7009 sort { $a->_date <=> $b->_date }
7010 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
7015 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
7016 called automatically when the cust_pay method is used in a scalar context.
7022 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
7023 my $sth = dbh->prepare($sql) or die dbh->errstr;
7024 $sth->execute($self->custnum) or die $sth->errstr;
7025 $sth->fetchrow_arrayref->[0];
7028 =item cust_pay_pkgnum
7030 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
7031 package when using experimental package balances.
7035 sub cust_pay_pkgnum {
7036 my( $self, $pkgnum ) = @_;
7037 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
7038 sort { $a->_date <=> $b->_date }
7039 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
7040 'pkgnum' => $pkgnum,
7047 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
7053 map { $_ } #return $self->num_cust_pay_void unless wantarray;
7054 sort { $a->_date <=> $b->_date }
7055 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
7058 =item cust_pay_batch
7060 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
7064 sub cust_pay_batch {
7066 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
7067 sort { $a->paybatchnum <=> $b->paybatchnum }
7068 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
7071 =item cust_pay_pending
7073 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
7074 (without status "done").
7078 sub cust_pay_pending {
7080 return $self->num_cust_pay_pending unless wantarray;
7081 sort { $a->_date <=> $b->_date }
7082 qsearch( 'cust_pay_pending', {
7083 'custnum' => $self->custnum,
7084 'status' => { op=>'!=', value=>'done' },
7089 =item num_cust_pay_pending
7091 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7092 customer (without status "done"). Also called automatically when the
7093 cust_pay_pending method is used in a scalar context.
7097 sub num_cust_pay_pending {
7099 my $sql = " SELECT COUNT(*) FROM cust_pay_pending ".
7100 " WHERE custnum = ? AND status != 'done' ";
7101 my $sth = dbh->prepare($sql) or die dbh->errstr;
7102 $sth->execute($self->custnum) or die $sth->errstr;
7103 $sth->fetchrow_arrayref->[0];
7108 Returns all the refunds (see L<FS::cust_refund>) for this customer.
7114 map { $_ } #return $self->num_cust_refund unless wantarray;
7115 sort { $a->_date <=> $b->_date }
7116 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
7119 =item display_custnum
7121 Returns the displayed customer number for this customer: agent_custid if
7122 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
7126 sub display_custnum {
7128 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
7129 return $self->agent_custid;
7131 return $self->custnum;
7137 Returns a name string for this customer, either "Company (Last, First)" or
7144 my $name = $self->contact;
7145 $name = $self->company. " ($name)" if $self->company;
7151 Returns a name string for this (service/shipping) contact, either
7152 "Company (Last, First)" or "Last, First".
7158 if ( $self->get('ship_last') ) {
7159 my $name = $self->ship_contact;
7160 $name = $self->ship_company. " ($name)" if $self->ship_company;
7169 Returns a name string for this customer, either "Company" or "First Last".
7175 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
7178 =item ship_name_short
7180 Returns a name string for this (service/shipping) contact, either "Company"
7185 sub ship_name_short {
7187 if ( $self->get('ship_last') ) {
7188 $self->ship_company !~ /^\s*$/
7189 ? $self->ship_company
7190 : $self->ship_contact_firstlast;
7192 $self->name_company_or_firstlast;
7198 Returns this customer's full (billing) contact name only, "Last, First"
7204 $self->get('last'). ', '. $self->first;
7209 Returns this customer's full (shipping) contact name only, "Last, First"
7215 $self->get('ship_last')
7216 ? $self->get('ship_last'). ', '. $self->ship_first
7220 =item contact_firstlast
7222 Returns this customers full (billing) contact name only, "First Last".
7226 sub contact_firstlast {
7228 $self->first. ' '. $self->get('last');
7231 =item ship_contact_firstlast
7233 Returns this customer's full (shipping) contact name only, "First Last".
7237 sub ship_contact_firstlast {
7239 $self->get('ship_last')
7240 ? $self->first. ' '. $self->get('ship_last')
7241 : $self->contact_firstlast;
7246 Returns this customer's full country name
7252 code2country($self->country);
7255 =item geocode DATA_VENDOR
7257 Returns a value for the customer location as encoded by DATA_VENDOR.
7258 Currently this only makes sense for "CCH" as DATA_VENDOR.
7263 my ($self, $data_vendor) = (shift, shift); #always cch for now
7265 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
7266 return $geocode if $geocode;
7268 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7272 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7273 if $self->country eq 'US';
7277 #CCH specific location stuff
7278 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7280 my @cust_tax_location =
7282 'table' => 'cust_tax_location',
7283 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7284 'extra_sql' => $extra_sql,
7285 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
7288 $geocode = $cust_tax_location[0]->geocode
7289 if scalar(@cust_tax_location);
7298 Returns a status string for this customer, currently:
7302 =item prospect - No packages have ever been ordered
7304 =item ordered - Recurring packages all are new (not yet billed).
7306 =item active - One or more recurring packages is active
7308 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7310 =item suspended - All non-cancelled recurring packages are suspended
7312 =item cancelled - All recurring packages are cancelled
7318 sub status { shift->cust_status(@_); }
7322 # prospect ordered active inactive suspended cancelled
7323 for my $status ( FS::cust_main->statuses() ) {
7324 my $method = $status.'_sql';
7325 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7326 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7327 $sth->execute( ($self->custnum) x $numnum )
7328 or die "Error executing 'SELECT $sql': ". $sth->errstr;
7329 return $status if $sth->fetchrow_arrayref->[0];
7333 =item ucfirst_cust_status
7335 =item ucfirst_status
7337 Returns the status with the first character capitalized.
7341 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7343 sub ucfirst_cust_status {
7345 ucfirst($self->cust_status);
7350 Returns a hex triplet color string for this customer's status.
7354 use vars qw(%statuscolor);
7355 tie %statuscolor, 'Tie::IxHash',
7356 'prospect' => '7e0079', #'000000', #black? naw, purple
7357 'active' => '00CC00', #green
7358 'ordered' => '009999', #teal? cyan?
7359 'inactive' => '0000CC', #blue
7360 'suspended' => 'FF9900', #yellow
7361 'cancelled' => 'FF0000', #red
7364 sub statuscolor { shift->cust_statuscolor(@_); }
7366 sub cust_statuscolor {
7368 $statuscolor{$self->cust_status};
7373 Returns an array of hashes representing the customer's RT tickets.
7380 my $num = $conf->config('cust_main-max_tickets') || 10;
7383 if ( $conf->config('ticket_system') ) {
7384 unless ( $conf->config('ticket_system-custom_priority_field') ) {
7386 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7390 foreach my $priority (
7391 $conf->config('ticket_system-custom_priority_field-values'), ''
7393 last if scalar(@tickets) >= $num;
7395 @{ FS::TicketSystem->customer_tickets( $self->custnum,
7396 $num - scalar(@tickets),
7406 # Return services representing svc_accts in customer support packages
7407 sub support_services {
7409 my %packages = map { $_ => 1 } $conf->config('support_packages');
7411 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7412 grep { $_->part_svc->svcdb eq 'svc_acct' }
7413 map { $_->cust_svc }
7414 grep { exists $packages{ $_->pkgpart } }
7415 $self->ncancelled_pkgs;
7419 # Return a list of latitude/longitude for one of the services (if any)
7420 sub service_coordinates {
7424 grep { $_->latitude && $_->longitude }
7426 map { $_->cust_svc }
7427 $self->ncancelled_pkgs;
7429 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7434 =head1 CLASS METHODS
7440 Class method that returns the list of possible status strings for customers
7441 (see L<the status method|/status>). For example:
7443 @statuses = FS::cust_main->statuses();
7448 #my $self = shift; #could be class...
7454 Returns an SQL expression identifying prospective cust_main records (customers
7455 with no packages ever ordered)
7459 use vars qw($select_count_pkgs);
7460 $select_count_pkgs =
7461 "SELECT COUNT(*) FROM cust_pkg
7462 WHERE cust_pkg.custnum = cust_main.custnum";
7464 sub select_count_pkgs_sql {
7469 " 0 = ( $select_count_pkgs ) ";
7474 Returns an SQL expression identifying ordered cust_main records (customers with
7475 recurring packages not yet setup).
7480 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
7485 Returns an SQL expression identifying active cust_main records (customers with
7486 active recurring packages).
7491 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7496 Returns an SQL expression identifying inactive cust_main records (customers with
7497 no active recurring packages, but otherwise unsuspended/uncancelled).
7501 sub inactive_sql { "
7502 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7504 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7510 Returns an SQL expression identifying suspended cust_main records.
7515 sub suspended_sql { susp_sql(@_); }
7517 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
7519 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7525 Returns an SQL expression identifying cancelled cust_main records.
7529 sub cancelled_sql { cancel_sql(@_); }
7532 my $recurring_sql = FS::cust_pkg->recurring_sql;
7533 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7536 0 < ( $select_count_pkgs )
7537 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
7538 AND 0 = ( $select_count_pkgs AND $recurring_sql
7539 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7541 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7547 =item uncancelled_sql
7549 Returns an SQL expression identifying un-cancelled cust_main records.
7553 sub uncancelled_sql { uncancel_sql(@_); }
7554 sub uncancel_sql { "
7555 ( 0 < ( $select_count_pkgs
7556 AND ( cust_pkg.cancel IS NULL
7557 OR cust_pkg.cancel = 0
7560 OR 0 = ( $select_count_pkgs )
7566 Returns an SQL fragment to retreive the balance.
7571 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7572 WHERE cust_bill.custnum = cust_main.custnum )
7573 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
7574 WHERE cust_pay.custnum = cust_main.custnum )
7575 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
7576 WHERE cust_credit.custnum = cust_main.custnum )
7577 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
7578 WHERE cust_refund.custnum = cust_main.custnum )
7581 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
7583 Returns an SQL fragment to retreive the balance for this customer, optionally
7584 considering invoices with date earlier than START_TIME, and not
7585 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7586 total_unapplied_payments).
7588 Times are specified as SQL fragments or numeric
7589 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7590 L<Date::Parse> for conversion functions. The empty string can be passed
7591 to disable that time constraint completely.
7593 Available options are:
7597 =item unapplied_date
7599 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)
7604 set to true to remove all customer comparison clauses, for totals
7609 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
7614 JOIN clause (typically used with the total option)
7618 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
7619 time will be ignored. Note that START_TIME and END_TIME only limit the date
7620 range for invoices and I<unapplied> payments, credits, and refunds.
7626 sub balance_date_sql {
7627 my( $class, $start, $end, %opt ) = @_;
7629 my $cutoff = $opt{'cutoff'};
7631 my $owed = FS::cust_bill->owed_sql($cutoff);
7632 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
7633 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
7634 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7636 my $j = $opt{'join'} || '';
7638 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
7639 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
7640 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
7641 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
7643 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
7644 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
7645 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
7646 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
7651 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
7653 Returns an SQL fragment to retreive the total unapplied payments for this
7654 customer, only considering invoices with date earlier than START_TIME, and
7655 optionally not later than END_TIME.
7657 Times are specified as SQL fragments or numeric
7658 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7659 L<Date::Parse> for conversion functions. The empty string can be passed
7660 to disable that time constraint completely.
7662 Available options are:
7666 sub unapplied_payments_date_sql {
7667 my( $class, $start, $end, %opt ) = @_;
7669 my $cutoff = $opt{'cutoff'};
7671 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7673 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
7674 'unapplied_date'=>1 );
7676 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
7679 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7681 Helper method for balance_date_sql; name (and usage) subject to change
7682 (suggestions welcome).
7684 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
7685 cust_refund, cust_credit or cust_pay).
7687 If TABLE is "cust_bill" or the unapplied_date option is true, only
7688 considers records with date earlier than START_TIME, and optionally not
7689 later than END_TIME .
7693 sub _money_table_where {
7694 my( $class, $table, $start, $end, %opt ) = @_;
7697 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
7698 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
7699 push @where, "$table._date <= $start" if defined($start) && length($start);
7700 push @where, "$table._date > $end" if defined($end) && length($end);
7702 push @where, @{$opt{'where'}} if $opt{'where'};
7703 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
7709 =item search HASHREF
7713 Returns a qsearch hash expression to search for parameters specified in
7714 HASHREF. Valid parameters are
7722 =item cancelled_pkgs
7728 listref of start date, end date
7738 =item current_balance
7740 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
7744 =item flattened_pkgs
7753 my ($class, $params) = @_;
7764 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
7766 "cust_main.agentnum = $1";
7770 # do the same for user
7773 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
7775 "cust_main.usernum = $1";
7782 #prospect ordered active inactive suspended cancelled
7783 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
7784 my $method = $params->{'status'}. '_sql';
7785 #push @where, $class->$method();
7786 push @where, FS::cust_main->$method();
7790 # parse cancelled package checkbox
7795 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
7796 unless $params->{'cancelled_pkgs'};
7799 # parse without census tract checkbox
7802 push @where, "(censustract = '' or censustract is null)"
7803 if $params->{'no_censustract'};
7809 foreach my $field (qw( signupdate )) {
7811 next unless exists($params->{$field});
7813 my($beginning, $ending, $hour) = @{$params->{$field}};
7816 "cust_main.$field IS NOT NULL",
7817 "cust_main.$field >= $beginning",
7818 "cust_main.$field <= $ending";
7820 # XXX: do this for mysql and/or pull it out of here
7822 if ($dbh->{Driver}->{Name} eq 'Pg') {
7823 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
7826 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
7830 $orderby ||= "ORDER BY cust_main.$field";
7838 if ( $params->{'classnum'} ) {
7840 my @classnum = ref( $params->{'classnum'} )
7841 ? @{ $params->{'classnum'} }
7842 : ( $params->{'classnum'} );
7844 @classnum = grep /^(\d*)$/, @classnum;
7847 push @where, '( '. join(' OR ', map {
7848 $_ ? "cust_main.classnum = $_"
7849 : "cust_main.classnum IS NULL"
7862 if ( $params->{'payby'} ) {
7864 my @payby = ref( $params->{'payby'} )
7865 ? @{ $params->{'payby'} }
7866 : ( $params->{'payby'} );
7868 @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
7870 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
7876 # paydate_year / paydate_month
7879 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
7881 $params->{'paydate_month'} =~ /^(\d\d?)$/
7882 or die "paydate_year without paydate_month?";
7886 'paydate IS NOT NULL',
7888 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
7896 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
7898 if ( $1 eq 'NULL' ) {
7900 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
7903 "cust_main.invoice_terms IS NOT NULL",
7904 "cust_main.invoice_terms = '$1'";
7912 if ( $params->{'current_balance'} ) {
7914 #my $balance_sql = $class->balance_sql();
7915 my $balance_sql = FS::cust_main->balance_sql();
7917 my @current_balance =
7918 ref( $params->{'current_balance'} )
7919 ? @{ $params->{'current_balance'} }
7920 : ( $params->{'current_balance'} );
7922 push @where, map { s/current_balance/$balance_sql/; $_ }
7931 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
7933 "cust_main.custbatch = '$1'";
7937 # setup queries, subs, etc. for the search
7940 $orderby ||= 'ORDER BY custnum';
7942 # here is the agent virtualization
7943 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
7945 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
7947 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
7949 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
7951 my $select = join(', ',
7952 'cust_main.custnum',
7953 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
7956 my(@extra_headers) = ();
7957 my(@extra_fields) = ();
7959 if ($params->{'flattened_pkgs'}) {
7961 if ($dbh->{Driver}->{Name} eq 'Pg') {
7963 $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";
7965 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
7966 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
7967 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
7969 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
7970 "omitting packing information from report.";
7973 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";
7975 my $sth = dbh->prepare($header_query) or die dbh->errstr;
7976 $sth->execute() or die $sth->errstr;
7977 my $headerrow = $sth->fetchrow_arrayref;
7978 my $headercount = $headerrow ? $headerrow->[0] : 0;
7979 while($headercount) {
7980 unshift @extra_headers, "Package ". $headercount;
7981 unshift @extra_fields, eval q!sub {my $c = shift;
7982 my @a = split '\|', $c->magic;
7983 my $p = $a[!.--$headercount. q!];
7991 'table' => 'cust_main',
7992 'select' => $select,
7994 'extra_sql' => $extra_sql,
7995 'order_by' => $orderby,
7996 'count_query' => $count_query,
7997 'extra_headers' => \@extra_headers,
7998 'extra_fields' => \@extra_fields,
8003 =item email_search_result HASHREF
8007 Emails a notice to the specified customers.
8009 Valid parameters are those of the L<search> method, plus the following:
8031 Optional job queue job for status updates.
8035 Returns an error message, or false for success.
8037 If an error occurs during any email, stops the enture send and returns that
8038 error. Presumably if you're getting SMTP errors aborting is better than
8039 retrying everything.
8043 sub email_search_result {
8044 my($class, $params) = @_;
8046 my $from = delete $params->{from};
8047 my $subject = delete $params->{subject};
8048 my $html_body = delete $params->{html_body};
8049 my $text_body = delete $params->{text_body};
8052 my $job = delete $params->{'job'}
8053 or die "email_search_result must run from the job queue.\n";
8055 $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
8056 unless ref($params->{'payby'});
8058 my $sql_query = $class->search($params);
8060 my $count_query = delete($sql_query->{'count_query'});
8061 my $count_sth = dbh->prepare($count_query)
8062 or die "Error preparing $count_query: ". dbh->errstr;
8064 or die "Error executing $count_query: ". $count_sth->errstr;
8065 my $count_arrayref = $count_sth->fetchrow_arrayref;
8066 my $num_cust = $count_arrayref->[0];
8068 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
8069 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
8072 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
8073 my @retry_jobs = ();
8076 #eventually order+limit magic to reduce memory use?
8077 foreach my $cust_main ( qsearch($sql_query) ) {
8079 #progressbar first, so that the count is right
8081 if ( time - $min_sec > $last ) {
8082 my $error = $job->update_statustext(
8083 int( 100 * $num / $num_cust )
8085 die $error if $error;
8089 my $to = $cust_main->invoicing_list_emailonly_scalar;
8095 'subject' => $subject,
8096 'html_body' => $html_body,
8097 'text_body' => $text_body,
8100 $error = send_email( generate_email( @message ) );
8103 # queue the sending of this message so that the user can see what we
8104 # tried to do, and retry if desired
8105 my $queue = new FS::queue {
8106 'job' => 'FS::Misc::process_send_email',
8107 'custnum' => $cust_main->custnum,
8108 'status' => 'failed',
8109 'statustext' => $error,
8111 $queue->insert(@message);
8112 push @retry_jobs, $queue;
8119 if($success == 0 and
8120 (scalar(@retry_jobs) > 10 or $num == $num_cust)
8122 # 10 is arbitrary, but if we have enough failures, that's
8123 # probably a configuration or network problem, and we
8124 # abort the batch and run away screaming.
8125 # We NEVER do this if anything was successfully sent.
8126 $_->delete foreach (@retry_jobs);
8127 return "multiple failures: '$error'\n";
8132 # fail the job, but with a status message that makes it clear
8133 # something was sent.
8134 return "Sent $success, failed ".scalar(@retry_jobs).". Failed attempts placed in job queue.\n";
8140 sub process_email_search_result {
8142 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
8144 my $param = thaw(decode_base64(shift));
8145 warn Dumper($param) if $DEBUG;
8147 $param->{'job'} = $job;
8149 $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
8150 unless ref($param->{'payby'});
8152 my $error = FS::cust_main->email_search_result( $param );
8153 die $error if $error;
8157 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
8159 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
8160 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
8161 specified (the appropriate ship_ field is also searched).
8163 Additional options are the same as FS::Record::qsearch
8168 my( $self, $fuzzy, $hash, @opt) = @_;
8173 check_and_rebuild_fuzzyfiles();
8174 foreach my $field ( keys %$fuzzy ) {
8176 my $all = $self->all_X($field);
8177 next unless scalar(@$all);
8180 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
8183 foreach ( keys %match ) {
8184 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
8185 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
8188 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
8191 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
8193 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
8201 Returns a masked version of the named field
8206 my ($self,$field) = @_;
8210 'x'x(length($self->getfield($field))-4).
8211 substr($self->getfield($field), (length($self->getfield($field))-4));
8221 =item smart_search OPTION => VALUE ...
8223 Accepts the following options: I<search>, the string to search for. The string
8224 will be searched for as a customer number, phone number, name or company name,
8225 as an exact, or, in some cases, a substring or fuzzy match (see the source code
8226 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
8227 skip fuzzy matching when an exact match is found.
8229 Any additional options are treated as an additional qualifier on the search
8232 Returns a (possibly empty) array of FS::cust_main objects.
8239 #here is the agent virtualization
8240 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8244 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
8245 my $search = delete $options{'search'};
8246 ( my $alphanum_search = $search ) =~ s/\W//g;
8248 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8250 #false laziness w/Record::ut_phone
8251 my $phonen = "$1-$2-$3";
8252 $phonen .= " x$4" if $4;
8254 push @cust_main, qsearch( {
8255 'table' => 'cust_main',
8256 'hashref' => { %options },
8257 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8259 join(' OR ', map "$_ = '$phonen'",
8260 qw( daytime night fax
8261 ship_daytime ship_night ship_fax )
8264 " AND $agentnums_sql", #agent virtualization
8267 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8268 #try looking for matches with extensions unless one was specified
8270 push @cust_main, qsearch( {
8271 'table' => 'cust_main',
8272 'hashref' => { %options },
8273 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8275 join(' OR ', map "$_ LIKE '$phonen\%'",
8277 ship_daytime ship_night )
8280 " AND $agentnums_sql", #agent virtualization
8285 # custnum search (also try agent_custid), with some tweaking options if your
8286 # legacy cust "numbers" have letters
8289 if ( $search =~ /^\s*(\d+)\s*$/
8290 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8291 && $search =~ /^\s*(\w\w?\d+)\s*$/
8293 || ( $conf->exists('address1-search' )
8294 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
8301 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
8302 push @cust_main, qsearch( {
8303 'table' => 'cust_main',
8304 'hashref' => { 'custnum' => $num, %options },
8305 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8309 push @cust_main, qsearch( {
8310 'table' => 'cust_main',
8311 'hashref' => { 'agent_custid' => $num, %options },
8312 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8315 if ( $conf->exists('address1-search') ) {
8316 my $len = length($num);
8318 foreach my $prefix ( '', 'ship_' ) {
8319 push @cust_main, qsearch( {
8320 'table' => 'cust_main',
8321 'hashref' => { %options, },
8323 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8324 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
8325 " AND $agentnums_sql",
8330 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8332 my($company, $last, $first) = ( $1, $2, $3 );
8334 # "Company (Last, First)"
8335 #this is probably something a browser remembered,
8336 #so just do an exact search (but case-insensitive, so USPS standardization
8337 #doesn't throw a wrench in the works)
8339 foreach my $prefix ( '', 'ship_' ) {
8340 push @cust_main, qsearch( {
8341 'table' => 'cust_main',
8342 'hashref' => { %options },
8344 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8346 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
8347 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
8348 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
8354 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8355 # try (ship_){last,company}
8359 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8360 # # full strings the browser remembers won't work
8361 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8363 use Lingua::EN::NameParse;
8364 my $NameParse = new Lingua::EN::NameParse(
8366 allow_reversed => 1,
8369 my($last, $first) = ( '', '' );
8370 #maybe disable this too and just rely on NameParse?
8371 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8373 ($last, $first) = ( $1, $2 );
8375 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
8376 } elsif ( ! $NameParse->parse($value) ) {
8378 my %name = $NameParse->components;
8379 $first = $name{'given_name_1'};
8380 $last = $name{'surname_1'};
8384 if ( $first && $last ) {
8386 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8389 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8391 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8392 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8395 push @cust_main, qsearch( {
8396 'table' => 'cust_main',
8397 'hashref' => \%options,
8398 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8401 # or it just be something that was typed in... (try that in a sec)
8405 my $q_value = dbh->quote($value);
8408 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8409 $sql .= " ( LOWER(last) = $q_value
8410 OR LOWER(company) = $q_value
8411 OR LOWER(ship_last) = $q_value
8412 OR LOWER(ship_company) = $q_value
8414 $sql .= " OR LOWER(address1) = $q_value
8415 OR LOWER(ship_address1) = $q_value
8417 if $conf->exists('address1-search');
8420 push @cust_main, qsearch( {
8421 'table' => 'cust_main',
8422 'hashref' => \%options,
8423 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8426 #no exact match, trying substring/fuzzy
8427 #always do substring & fuzzy (unless they're explicity config'ed off)
8428 #getting complaints searches are not returning enough
8429 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8431 #still some false laziness w/search (was search/cust_main.cgi)
8436 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
8437 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8440 if ( $first && $last ) {
8443 { 'first' => { op=>'ILIKE', value=>"%$first%" },
8444 'last' => { op=>'ILIKE', value=>"%$last%" },
8446 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
8447 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
8454 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
8455 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
8459 if ( $conf->exists('address1-search') ) {
8461 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
8462 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
8466 foreach my $hashref ( @hashrefs ) {
8468 push @cust_main, qsearch( {
8469 'table' => 'cust_main',
8470 'hashref' => { %$hashref,
8473 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8482 " AND $agentnums_sql", #extra_sql #agent virtualization
8485 if ( $first && $last ) {
8486 push @cust_main, FS::cust_main->fuzzy_search(
8487 { 'last' => $last, #fuzzy hashref
8488 'first' => $first }, #
8492 foreach my $field ( 'last', 'company' ) {
8494 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8496 if ( $conf->exists('address1-search') ) {
8498 FS::cust_main->fuzzy_search( { 'address1' => $value }, @fuzopts );
8505 #eliminate duplicates
8507 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8515 Accepts the following options: I<email>, the email address to search for. The
8516 email address will be searched for as an email invoice destination and as an
8519 #Any additional options are treated as an additional qualifier on the search
8520 #(i.e. I<agentnum>).
8522 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8532 my $email = delete $options{'email'};
8534 #we're only being used by RT at the moment... no agent virtualization yet
8535 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8539 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8541 my ( $user, $domain ) = ( $1, $2 );
8543 warn "$me smart_search: searching for $user in domain $domain"
8549 'table' => 'cust_main_invoice',
8550 'hashref' => { 'dest' => $email },
8557 map $_->cust_svc->cust_pkg,
8559 'table' => 'svc_acct',
8560 'hashref' => { 'username' => $user, },
8562 'AND ( SELECT domain FROM svc_domain
8563 WHERE svc_acct.domsvc = svc_domain.svcnum
8564 ) = '. dbh->quote($domain),
8570 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8572 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8579 =item check_and_rebuild_fuzzyfiles
8583 sub check_and_rebuild_fuzzyfiles {
8584 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8585 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8588 =item rebuild_fuzzyfiles
8592 sub rebuild_fuzzyfiles {
8594 use Fcntl qw(:flock);
8596 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8597 mkdir $dir, 0700 unless -d $dir;
8599 foreach my $fuzzy ( @fuzzyfields ) {
8601 open(LOCK,">>$dir/cust_main.$fuzzy")
8602 or die "can't open $dir/cust_main.$fuzzy: $!";
8604 or die "can't lock $dir/cust_main.$fuzzy: $!";
8606 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8607 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8609 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8610 my $sth = dbh->prepare("SELECT $field FROM cust_main".
8611 " WHERE $field != '' AND $field IS NOT NULL");
8612 $sth->execute or die $sth->errstr;
8614 while ( my $row = $sth->fetchrow_arrayref ) {
8615 print CACHE $row->[0]. "\n";
8620 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8622 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8633 my( $self, $field ) = @_;
8634 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8635 open(CACHE,"<$dir/cust_main.$field")
8636 or die "can't open $dir/cust_main.$field: $!";
8637 my @array = map { chomp; $_; } <CACHE>;
8642 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
8646 sub append_fuzzyfiles {
8647 #my( $first, $last, $company ) = @_;
8649 &check_and_rebuild_fuzzyfiles;
8651 use Fcntl qw(:flock);
8653 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8655 foreach my $field (@fuzzyfields) {
8660 open(CACHE,">>$dir/cust_main.$field")
8661 or die "can't open $dir/cust_main.$field: $!";
8662 flock(CACHE,LOCK_EX)
8663 or die "can't lock $dir/cust_main.$field: $!";
8665 print CACHE "$value\n";
8667 flock(CACHE,LOCK_UN)
8668 or die "can't unlock $dir/cust_main.$field: $!";
8683 #warn join('-',keys %$param);
8684 my $fh = $param->{filehandle};
8685 my @fields = @{$param->{fields}};
8687 eval "use Text::CSV_XS;";
8690 my $csv = new Text::CSV_XS;
8697 local $SIG{HUP} = 'IGNORE';
8698 local $SIG{INT} = 'IGNORE';
8699 local $SIG{QUIT} = 'IGNORE';
8700 local $SIG{TERM} = 'IGNORE';
8701 local $SIG{TSTP} = 'IGNORE';
8702 local $SIG{PIPE} = 'IGNORE';
8704 my $oldAutoCommit = $FS::UID::AutoCommit;
8705 local $FS::UID::AutoCommit = 0;
8708 #while ( $columns = $csv->getline($fh) ) {
8710 while ( defined($line=<$fh>) ) {
8712 $csv->parse($line) or do {
8713 $dbh->rollback if $oldAutoCommit;
8714 return "can't parse: ". $csv->error_input();
8717 my @columns = $csv->fields();
8718 #warn join('-',@columns);
8721 foreach my $field ( @fields ) {
8722 $row{$field} = shift @columns;
8725 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
8726 unless ( $cust_main ) {
8727 $dbh->rollback if $oldAutoCommit;
8728 return "unknown custnum $row{'custnum'}";
8731 if ( $row{'amount'} > 0 ) {
8732 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8734 $dbh->rollback if $oldAutoCommit;
8738 } elsif ( $row{'amount'} < 0 ) {
8739 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8742 $dbh->rollback if $oldAutoCommit;
8752 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8754 return "Empty file!" unless $imported;
8760 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8762 Sends a templated email notification to the customer (see L<Text::Template>).
8764 OPTIONS is a hash and may include
8766 I<from> - the email sender (default is invoice_from)
8768 I<to> - comma-separated scalar or arrayref of recipients
8769 (default is invoicing_list)
8771 I<subject> - The subject line of the sent email notification
8772 (default is "Notice from company_name")
8774 I<extra_fields> - a hashref of name/value pairs which will be substituted
8777 The following variables are vavailable in the template.
8779 I<$first> - the customer first name
8780 I<$last> - the customer last name
8781 I<$company> - the customer company
8782 I<$payby> - a description of the method of payment for the customer
8783 # would be nice to use FS::payby::shortname
8784 I<$payinfo> - the account information used to collect for this customer
8785 I<$expdate> - the expiration of the customer payment in seconds from epoch
8790 my ($self, $template, %options) = @_;
8792 return unless $conf->exists($template);
8794 my $from = $conf->config('invoice_from', $self->agentnum)
8795 if $conf->exists('invoice_from', $self->agentnum);
8796 $from = $options{from} if exists($options{from});
8798 my $to = join(',', $self->invoicing_list_emailonly);
8799 $to = $options{to} if exists($options{to});
8801 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
8802 if $conf->exists('company_name', $self->agentnum);
8803 $subject = $options{subject} if exists($options{subject});
8805 my $notify_template = new Text::Template (TYPE => 'ARRAY',
8806 SOURCE => [ map "$_\n",
8807 $conf->config($template)]
8809 or die "can't create new Text::Template object: Text::Template::ERROR";
8810 $notify_template->compile()
8811 or die "can't compile template: Text::Template::ERROR";
8813 $FS::notify_template::_template::company_name =
8814 $conf->config('company_name', $self->agentnum);
8815 $FS::notify_template::_template::company_address =
8816 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
8818 my $paydate = $self->paydate || '2037-12-31';
8819 $FS::notify_template::_template::first = $self->first;
8820 $FS::notify_template::_template::last = $self->last;
8821 $FS::notify_template::_template::company = $self->company;
8822 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
8823 my $payby = $self->payby;
8824 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8825 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8827 #credit cards expire at the end of the month/year of their exp date
8828 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8829 $FS::notify_template::_template::payby = 'credit card';
8830 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8831 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8833 }elsif ($payby eq 'COMP') {
8834 $FS::notify_template::_template::payby = 'complimentary account';
8836 $FS::notify_template::_template::payby = 'current method';
8838 $FS::notify_template::_template::expdate = $expire_time;
8840 for (keys %{$options{extra_fields}}){
8842 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
8845 send_email(from => $from,
8847 subject => $subject,
8848 body => $notify_template->fill_in( PACKAGE =>
8849 'FS::notify_template::_template' ),
8854 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8856 Generates a templated notification to the customer (see L<Text::Template>).
8858 OPTIONS is a hash and may include
8860 I<extra_fields> - a hashref of name/value pairs which will be substituted
8861 into the template. These values may override values mentioned below
8862 and those from the customer record.
8864 The following variables are available in the template instead of or in addition
8865 to the fields of the customer record.
8867 I<$payby> - a description of the method of payment for the customer
8868 # would be nice to use FS::payby::shortname
8869 I<$payinfo> - the masked account information used to collect for this customer
8870 I<$expdate> - the expiration of the customer payment method in seconds from epoch
8871 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
8875 sub generate_letter {
8876 my ($self, $template, %options) = @_;
8878 return unless $conf->exists($template);
8880 my $letter_template = new Text::Template
8882 SOURCE => [ map "$_\n", $conf->config($template)],
8883 DELIMITERS => [ '[@--', '--@]' ],
8885 or die "can't create new Text::Template object: Text::Template::ERROR";
8887 $letter_template->compile()
8888 or die "can't compile template: Text::Template::ERROR";
8890 my %letter_data = map { $_ => $self->$_ } $self->fields;
8891 $letter_data{payinfo} = $self->mask_payinfo;
8893 #my $paydate = $self->paydate || '2037-12-31';
8894 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
8896 my $payby = $self->payby;
8897 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8898 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8900 #credit cards expire at the end of the month/year of their exp date
8901 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8902 $letter_data{payby} = 'credit card';
8903 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8904 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8906 }elsif ($payby eq 'COMP') {
8907 $letter_data{payby} = 'complimentary account';
8909 $letter_data{payby} = 'current method';
8911 $letter_data{expdate} = $expire_time;
8913 for (keys %{$options{extra_fields}}){
8914 $letter_data{$_} = $options{extra_fields}->{$_};
8917 unless(exists($letter_data{returnaddress})){
8918 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
8919 $self->agent_template)
8921 if ( length($retadd) ) {
8922 $letter_data{returnaddress} = $retadd;
8923 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
8924 $letter_data{returnaddress} =
8925 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
8926 $conf->config('company_address', $self->agentnum)
8929 $letter_data{returnaddress} = '~';
8933 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
8935 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
8937 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
8938 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
8942 ) or die "can't open temp file: $!\n";
8944 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
8946 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
8950 =item print_ps TEMPLATE
8952 Returns an postscript letter filled in from TEMPLATE, as a scalar.
8958 my $file = $self->generate_letter(@_);
8959 FS::Misc::generate_ps($file);
8962 =item print TEMPLATE
8964 Prints the filled in template.
8966 TEMPLATE is the name of a L<Text::Template> to fill in and print.
8970 sub queueable_print {
8973 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
8974 or die "invalid customer number: " . $opt{custvnum};
8976 my $error = $self->print( $opt{template} );
8977 die $error if $error;
8981 my ($self, $template) = (shift, shift);
8982 do_print [ $self->print_ps($template) ];
8985 #these three subs should just go away once agent stuff is all config overrides
8987 sub agent_template {
8989 $self->_agent_plandata('agent_templatename');
8992 sub agent_invoice_from {
8994 $self->_agent_plandata('agent_invoice_from');
8997 sub _agent_plandata {
8998 my( $self, $option ) = @_;
9000 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
9001 #agent-specific Conf
9003 use FS::part_event::Condition;
9005 my $agentnum = $self->agentnum;
9007 my $regexp = regexp_sql();
9009 my $part_event_option =
9011 'select' => 'part_event_option.*',
9012 'table' => 'part_event_option',
9014 LEFT JOIN part_event USING ( eventpart )
9015 LEFT JOIN part_event_option AS peo_agentnum
9016 ON ( part_event.eventpart = peo_agentnum.eventpart
9017 AND peo_agentnum.optionname = 'agentnum'
9018 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
9020 LEFT JOIN part_event_condition
9021 ON ( part_event.eventpart = part_event_condition.eventpart
9022 AND part_event_condition.conditionname = 'cust_bill_age'
9024 LEFT JOIN part_event_condition_option
9025 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
9026 AND part_event_condition_option.optionname = 'age'
9029 #'hashref' => { 'optionname' => $option },
9030 #'hashref' => { 'part_event_option.optionname' => $option },
9032 " WHERE part_event_option.optionname = ". dbh->quote($option).
9033 " AND action = 'cust_bill_send_agent' ".
9034 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
9035 " AND peo_agentnum.optionname = 'agentnum' ".
9036 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
9038 CASE WHEN part_event_condition_option.optionname IS NULL
9040 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
9042 , part_event.weight".
9046 unless ( $part_event_option ) {
9047 return $self->agent->invoice_template || ''
9048 if $option eq 'agent_templatename';
9052 $part_event_option->optionvalue;
9056 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
9058 Subroutine (not a method), designed to be called from the queue.
9060 Takes a list of options and values.
9062 Pulls up the customer record via the custnum option and calls bill_and_collect.
9067 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
9069 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
9070 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
9072 $cust_main->bill_and_collect( %args );
9075 sub process_bill_and_collect {
9077 my $param = thaw(decode_base64(shift));
9078 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
9079 or die "custnum '$param->{custnum}' not found!\n";
9080 $param->{'job'} = $job;
9081 $param->{'fatal'} = 1; # runs from job queue, will be caught
9082 $param->{'retry'} = 1;
9084 $cust_main->bill_and_collect( %$param );
9087 sub _upgrade_data { #class method
9088 my ($class, %opts) = @_;
9090 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
9091 my $sth = dbh->prepare($sql) or die dbh->errstr;
9092 $sth->execute or die $sth->errstr;
9094 local($ignore_expired_card) = 1;
9095 local($skip_fuzzyfiles) = 1;
9096 $class->_upgrade_otaker(%opts);
9106 The delete method should possibly take an FS::cust_main object reference
9107 instead of a scalar customer number.
9109 Bill and collect options should probably be passed as references instead of a
9112 There should probably be a configuration file with a list of allowed credit
9115 No multiple currency support (probably a larger project than just this module).
9117 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
9119 Birthdates rely on negative epoch values.
9121 The payby for card/check batches is broken. With mixed batching, bad
9124 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
9128 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
9129 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
9130 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.