5 use base qw( FS::otaker_Mixin
10 use vars qw( @EXPORT_OK $DEBUG $me $conf
12 $import $ignore_expired_card
13 $skip_fuzzyfiles @fuzzyfields
16 use vars qw( $realtime_bop_decline_quiet ); #ugh
20 use Scalar::Util qw( blessed );
21 use List::Util qw( min );
22 use Time::Local qw(timelocal);
23 use Storable qw(thaw);
27 use Digest::MD5 qw(md5_base64);
30 use File::Temp qw( tempfile );
31 use String::Approx qw(amatch);
32 use Business::CreditCard 0.28;
34 use FS::UID qw( getotaker dbh driver_name );
35 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
36 use FS::Misc qw( generate_email send_email generate_ps do_print );
37 use FS::Msgcat qw(gettext);
43 use FS::cust_bill_pkg;
44 use FS::cust_bill_pkg_display;
45 use FS::cust_bill_pkg_tax_location;
46 use FS::cust_bill_pkg_tax_rate_location;
48 use FS::cust_pay_pending;
49 use FS::cust_pay_void;
50 use FS::cust_pay_batch;
53 use FS::part_referral;
54 use FS::cust_main_county;
55 use FS::cust_location;
57 use FS::cust_main_exemption;
58 use FS::cust_tax_adjustment;
60 use FS::tax_rate_location;
61 use FS::cust_tax_location;
62 use FS::part_pkg_taxrate;
64 use FS::cust_main_invoice;
66 use FS::cust_credit_bill;
67 use FS::cust_bill_pay;
68 use FS::prepay_credit;
72 use FS::part_event_condition;
76 use FS::payment_gateway;
77 use FS::agent_payment_gateway;
81 @EXPORT_OK = qw( smart_search );
83 $realtime_bop_decline_quiet = 0;
85 # 1 is mostly method/subroutine entry and options
86 # 2 traces progress of some operations
87 # 3 is even more information including possibly sensitive data
89 $me = '[FS::cust_main]';
92 $ignore_expired_card = 0;
95 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
97 @encrypted_fields = ('payinfo', 'paycvv');
98 sub nohistory_fields { ('payinfo', 'paycvv'); }
100 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
102 #ask FS::UID to run this stuff for us later
103 #$FS::UID::callback{'FS::cust_main'} = sub {
104 install_callback FS::UID sub {
105 $conf = new FS::Conf;
106 #yes, need it for stuff below (prolly should be cached)
111 my ( $hashref, $cache ) = @_;
112 if ( exists $hashref->{'pkgnum'} ) {
113 #@{ $self->{'_pkgnum'} } = ();
114 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
115 $self->{'_pkgnum'} = $subcache;
116 #push @{ $self->{'_pkgnum'} },
117 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
123 FS::cust_main - Object methods for cust_main records
129 $record = new FS::cust_main \%hash;
130 $record = new FS::cust_main { 'column' => 'value' };
132 $error = $record->insert;
134 $error = $new_record->replace($old_record);
136 $error = $record->delete;
138 $error = $record->check;
140 @cust_pkg = $record->all_pkgs;
142 @cust_pkg = $record->ncancelled_pkgs;
144 @cust_pkg = $record->suspended_pkgs;
146 $error = $record->bill;
147 $error = $record->bill %options;
148 $error = $record->bill 'time' => $time;
150 $error = $record->collect;
151 $error = $record->collect %options;
152 $error = $record->collect 'invoice_time' => $time,
157 An FS::cust_main object represents a customer. FS::cust_main inherits from
158 FS::Record. The following fields are currently supported:
164 Primary key (assigned automatically for new customers)
168 Agent (see L<FS::agent>)
172 Advertising source (see L<FS::part_referral>)
184 Cocial security number (optional)
200 (optional, see L<FS::cust_main_county>)
204 (see L<FS::cust_main_county>)
210 (see L<FS::cust_main_county>)
246 (optional, see L<FS::cust_main_county>)
250 (see L<FS::cust_main_county>)
256 (see L<FS::cust_main_county>)
272 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
276 Payment Information (See L<FS::payinfo_Mixin> for data format)
280 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
284 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
288 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
292 Start date month (maestro/solo cards only)
296 Start date year (maestro/solo cards only)
300 Issue number (maestro/solo cards only)
304 Name on card or billing name
308 IP address from which payment information was received
312 Tax exempt, empty or `Y'
316 Order taker (see L<FS::access_user>)
322 =item referral_custnum
324 Referring customer number
328 Enable individual CDR spooling, empty or `Y'
332 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
336 Discourage individual CDR printing, empty or `Y'
346 Creates a new customer. To add the customer to the database, see L<"insert">.
348 Note that this stores the hash reference, not a distinct copy of the hash it
349 points to. You can ask the object for a copy with the I<hash> method.
353 sub table { 'cust_main'; }
355 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
357 Adds this customer to the database. If there is an error, returns the error,
358 otherwise returns false.
360 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
361 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
362 are inserted atomicly, or the transaction is rolled back. Passing an empty
363 hash reference is equivalent to not supplying this parameter. There should be
364 a better explanation of this, but until then, here's an example:
367 tie %hash, 'Tie::RefHash'; #this part is important
369 $cust_pkg => [ $svc_acct ],
372 $cust_main->insert( \%hash );
374 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
375 be set as the invoicing list (see L<"invoicing_list">). Errors return as
376 expected and rollback the entire transaction; it is not necessary to call
377 check_invoicing_list first. The invoicing_list is set after the records in the
378 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
379 invoicing_list destination to the newly-created svc_acct. Here's an example:
381 $cust_main->insert( {}, [ $email, 'POST' ] );
383 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
385 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
386 on the supplied jobnum (they will not run until the specific job completes).
387 This can be used to defer provisioning until some action completes (such
388 as running the customer's credit card successfully).
390 The I<noexport> option is deprecated. If I<noexport> is set true, no
391 provisioning jobs (exports) are scheduled. (You can schedule them later with
392 the B<reexport> method.)
394 The I<tax_exemption> option can be set to an arrayref of tax names.
395 FS::cust_main_exemption records will be created and inserted.
401 my $cust_pkgs = @_ ? shift : {};
402 my $invoicing_list = @_ ? shift : '';
404 warn "$me insert called with options ".
405 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
408 local $SIG{HUP} = 'IGNORE';
409 local $SIG{INT} = 'IGNORE';
410 local $SIG{QUIT} = 'IGNORE';
411 local $SIG{TERM} = 'IGNORE';
412 local $SIG{TSTP} = 'IGNORE';
413 local $SIG{PIPE} = 'IGNORE';
415 my $oldAutoCommit = $FS::UID::AutoCommit;
416 local $FS::UID::AutoCommit = 0;
419 my $prepay_identifier = '';
420 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
422 if ( $self->payby eq 'PREPAY' ) {
424 $self->payby('BILL');
425 $prepay_identifier = $self->payinfo;
428 warn " looking up prepaid card $prepay_identifier\n"
431 my $error = $self->get_prepay( $prepay_identifier,
432 'amount_ref' => \$amount,
433 'seconds_ref' => \$seconds,
434 'upbytes_ref' => \$upbytes,
435 'downbytes_ref' => \$downbytes,
436 'totalbytes_ref' => \$totalbytes,
439 $dbh->rollback if $oldAutoCommit;
440 #return "error applying prepaid card (transaction rolled back): $error";
444 $payby = 'PREP' if $amount;
446 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
449 $self->payby('BILL');
450 $amount = $self->paid;
454 warn " inserting $self\n"
457 $self->signupdate(time) unless $self->signupdate;
459 $self->auto_agent_custid()
460 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
462 my $error = $self->SUPER::insert;
464 $dbh->rollback if $oldAutoCommit;
465 #return "inserting cust_main record (transaction rolled back): $error";
469 warn " setting invoicing list\n"
472 if ( $invoicing_list ) {
473 $error = $self->check_invoicing_list( $invoicing_list );
475 $dbh->rollback if $oldAutoCommit;
476 #return "checking invoicing_list (transaction rolled back): $error";
479 $self->invoicing_list( $invoicing_list );
482 warn " setting customer tags\n"
485 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
486 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
487 'custnum' => $self->custnum };
488 my $error = $cust_tag->insert;
490 $dbh->rollback if $oldAutoCommit;
495 if ( $invoicing_list ) {
496 $error = $self->check_invoicing_list( $invoicing_list );
498 $dbh->rollback if $oldAutoCommit;
499 #return "checking invoicing_list (transaction rolled back): $error";
502 $self->invoicing_list( $invoicing_list );
506 warn " setting cust_main_exemption\n"
509 my $tax_exemption = delete $options{'tax_exemption'};
510 if ( $tax_exemption ) {
511 foreach my $taxname ( @$tax_exemption ) {
512 my $cust_main_exemption = new FS::cust_main_exemption {
513 'custnum' => $self->custnum,
514 'taxname' => $taxname,
516 my $error = $cust_main_exemption->insert;
518 $dbh->rollback if $oldAutoCommit;
519 return "inserting cust_main_exemption (transaction rolled back): $error";
524 if ( $conf->config('cust_main-skeleton_tables')
525 && $conf->config('cust_main-skeleton_custnum') ) {
527 warn " inserting skeleton records\n"
530 my $error = $self->start_copy_skel;
532 $dbh->rollback if $oldAutoCommit;
538 warn " ordering packages\n"
541 $error = $self->order_pkgs( $cust_pkgs,
543 'seconds_ref' => \$seconds,
544 'upbytes_ref' => \$upbytes,
545 'downbytes_ref' => \$downbytes,
546 'totalbytes_ref' => \$totalbytes,
549 $dbh->rollback if $oldAutoCommit;
554 $dbh->rollback if $oldAutoCommit;
555 return "No svc_acct record to apply pre-paid time";
557 if ( $upbytes || $downbytes || $totalbytes ) {
558 $dbh->rollback if $oldAutoCommit;
559 return "No svc_acct record to apply pre-paid data";
563 warn " inserting initial $payby payment of $amount\n"
565 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
567 $dbh->rollback if $oldAutoCommit;
568 return "inserting payment (transaction rolled back): $error";
572 unless ( $import || $skip_fuzzyfiles ) {
573 warn " queueing fuzzyfiles update\n"
575 $error = $self->queue_fuzzyfiles_update;
577 $dbh->rollback if $oldAutoCommit;
578 return "updating fuzzy search cache: $error";
583 warn " exporting\n" if $DEBUG > 1;
585 my $export_args = $options{'export_args'} || [];
588 map qsearch( 'part_export', {exportnum=>$_} ),
589 $conf->config('cust_main-exports'); #, $agentnum
591 foreach my $part_export ( @part_export ) {
592 my $error = $part_export->export_insert($self, @$export_args);
594 $dbh->rollback if $oldAutoCommit;
595 return "exporting to ". $part_export->exporttype.
596 " (transaction rolled back): $error";
600 #foreach my $depend_jobnum ( @$depend_jobnums ) {
601 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
603 # foreach my $jobnum ( @jobnums ) {
604 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
605 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
607 # my $error = $queue->depend_insert($depend_jobnum);
609 # $dbh->rollback if $oldAutoCommit;
610 # return "error queuing job dependancy: $error";
617 #if ( exists $options{'jobnums'} ) {
618 # push @{ $options{'jobnums'} }, @jobnums;
621 warn " insert complete; committing transaction\n"
624 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
629 use File::CounterFile;
630 sub auto_agent_custid {
633 my $format = $conf->config('cust_main-auto_agent_custid');
635 if ( $format eq '1YMMXXXXXXXX' ) {
637 my $counter = new File::CounterFile 'cust_main.agent_custid';
640 my $ym = 100000000000 + time2str('%y%m00000000', time);
641 if ( $ym > $counter->value ) {
642 $counter->{'value'} = $agent_custid = $ym;
643 $counter->{'updated'} = 1;
645 $agent_custid = $counter->inc;
651 die "Unknown cust_main-auto_agent_custid format: $format";
654 $self->agent_custid($agent_custid);
658 sub start_copy_skel {
661 #'mg_user_preference' => {},
662 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
663 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
664 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
665 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
666 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
669 _copy_skel( 'cust_main', #tablename
670 $conf->config('cust_main-skeleton_custnum'), #sourceid
671 $self->custnum, #destid
672 @tables, #child tables
676 #recursive subroutine, not a method
678 my( $table, $sourceid, $destid, %child_tables ) = @_;
681 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
682 ( $table, $primary_key ) = ( $1, $2 );
684 my $dbdef_table = dbdef->table($table);
685 $primary_key = $dbdef_table->primary_key
686 or return "$table has no primary key".
687 " (or do you need to run dbdef-create?)";
690 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
691 join (', ', keys %child_tables). "\n"
694 foreach my $child_table_def ( keys %child_tables ) {
698 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
699 ( $child_table, $child_pkey ) = ( $1, $2 );
701 $child_table = $child_table_def;
703 $child_pkey = dbdef->table($child_table)->primary_key;
704 # or return "$table has no primary key".
705 # " (or do you need to run dbdef-create?)\n";
709 if ( keys %{ $child_tables{$child_table_def} } ) {
711 return "$child_table has no primary key".
712 " (run dbdef-create or try specifying it?)\n"
715 #false laziness w/Record::insert and only works on Pg
716 #refactor the proper last-inserted-id stuff out of Record::insert if this
717 # ever gets use for anything besides a quick kludge for one customer
718 my $default = dbdef->table($child_table)->column($child_pkey)->default;
719 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
720 or return "can't parse $child_table.$child_pkey default value ".
721 " for sequence name: $default";
726 my @sel_columns = grep { $_ ne $primary_key }
727 dbdef->table($child_table)->columns;
728 my $sel_columns = join(', ', @sel_columns );
730 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
731 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
732 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
734 my $sel_st = "SELECT $sel_columns FROM $child_table".
735 " WHERE $primary_key = $sourceid";
738 my $sel_sth = dbh->prepare( $sel_st )
739 or return dbh->errstr;
741 $sel_sth->execute or return $sel_sth->errstr;
743 while ( my $row = $sel_sth->fetchrow_hashref ) {
745 warn " selected row: ".
746 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
750 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
751 my $ins_sth =dbh->prepare($statement)
752 or return dbh->errstr;
753 my @param = ( $destid, map $row->{$_}, @ins_columns );
754 warn " $statement: [ ". join(', ', @param). " ]\n"
756 $ins_sth->execute( @param )
757 or return $ins_sth->errstr;
759 #next unless keys %{ $child_tables{$child_table} };
760 next unless $sequence;
762 #another section of that laziness
763 my $seq_sql = "SELECT currval('$sequence')";
764 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
765 $seq_sth->execute or return $seq_sth->errstr;
766 my $insertid = $seq_sth->fetchrow_arrayref->[0];
768 # don't drink soap! recurse! recurse! okay!
770 _copy_skel( $child_table_def,
771 $row->{$child_pkey}, #sourceid
773 %{ $child_tables{$child_table_def} },
775 return $error if $error;
785 =item order_pkg HASHREF | OPTION => VALUE ...
787 Orders a single package.
789 Options may be passed as a list of key/value pairs or as a hash reference.
800 Optional FS::cust_location object
804 Optional arryaref of FS::svc_* service objects.
808 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
809 jobs will have a dependancy on the supplied job (they will not run until the
810 specific job completes). This can be used to defer provisioning until some
811 action completes (such as running the customer's credit card successfully).
815 Optional subject for a ticket created and attached to this customer
819 Optional queue name for ticket additions
827 my $opt = ref($_[0]) ? shift : { @_ };
829 warn "$me order_pkg called with options ".
830 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
833 my $cust_pkg = $opt->{'cust_pkg'};
834 my $svcs = $opt->{'svcs'} || [];
836 my %svc_options = ();
837 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
838 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
840 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
841 qw( ticket_subject ticket_queue );
843 local $SIG{HUP} = 'IGNORE';
844 local $SIG{INT} = 'IGNORE';
845 local $SIG{QUIT} = 'IGNORE';
846 local $SIG{TERM} = 'IGNORE';
847 local $SIG{TSTP} = 'IGNORE';
848 local $SIG{PIPE} = 'IGNORE';
850 my $oldAutoCommit = $FS::UID::AutoCommit;
851 local $FS::UID::AutoCommit = 0;
854 if ( $opt->{'cust_location'} &&
855 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
856 my $error = $opt->{'cust_location'}->insert;
858 $dbh->rollback if $oldAutoCommit;
859 return "inserting cust_location (transaction rolled back): $error";
861 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
864 $cust_pkg->custnum( $self->custnum );
866 my $error = $cust_pkg->insert( %insert_params );
868 $dbh->rollback if $oldAutoCommit;
869 return "inserting cust_pkg (transaction rolled back): $error";
872 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
873 if ( $svc_something->svcnum ) {
874 my $old_cust_svc = $svc_something->cust_svc;
875 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
876 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
877 $error = $new_cust_svc->replace($old_cust_svc);
879 $svc_something->pkgnum( $cust_pkg->pkgnum );
880 if ( $svc_something->isa('FS::svc_acct') ) {
881 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
882 qw( seconds upbytes downbytes totalbytes ) ) {
883 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
884 ${ $opt->{$_.'_ref'} } = 0;
887 $error = $svc_something->insert(%svc_options);
890 $dbh->rollback if $oldAutoCommit;
891 return "inserting svc_ (transaction rolled back): $error";
895 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
900 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
901 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
903 Like the insert method on an existing record, this method orders multiple
904 packages and included services atomicaly. Pass a Tie::RefHash data structure
905 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
906 There should be a better explanation of this, but until then, here's an
910 tie %hash, 'Tie::RefHash'; #this part is important
912 $cust_pkg => [ $svc_acct ],
915 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
917 Services can be new, in which case they are inserted, or existing unaudited
918 services, in which case they are linked to the newly-created package.
920 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
921 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
923 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
924 on the supplied jobnum (they will not run until the specific job completes).
925 This can be used to defer provisioning until some action completes (such
926 as running the customer's credit card successfully).
928 The I<noexport> option is deprecated. If I<noexport> is set true, no
929 provisioning jobs (exports) are scheduled. (You can schedule them later with
930 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
931 on the cust_main object is not recommended, as existing services will also be
934 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
935 provided, the scalars (provided by references) will be incremented by the
936 values of the prepaid card.`
942 my $cust_pkgs = shift;
943 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
945 $seconds_ref ||= $options{'seconds_ref'};
947 warn "$me order_pkgs called with options ".
948 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
951 local $SIG{HUP} = 'IGNORE';
952 local $SIG{INT} = 'IGNORE';
953 local $SIG{QUIT} = 'IGNORE';
954 local $SIG{TERM} = 'IGNORE';
955 local $SIG{TSTP} = 'IGNORE';
956 local $SIG{PIPE} = 'IGNORE';
958 my $oldAutoCommit = $FS::UID::AutoCommit;
959 local $FS::UID::AutoCommit = 0;
962 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
964 foreach my $cust_pkg ( keys %$cust_pkgs ) {
966 my $error = $self->order_pkg(
967 'cust_pkg' => $cust_pkg,
968 'svcs' => $cust_pkgs->{$cust_pkg},
969 'seconds_ref' => $seconds_ref,
970 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
975 $dbh->rollback if $oldAutoCommit;
981 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
985 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
987 Recharges this (existing) customer with the specified prepaid card (see
988 L<FS::prepay_credit>), specified either by I<identifier> or as an
989 FS::prepay_credit object. If there is an error, returns the error, otherwise
992 Optionally, five scalar references can be passed as well. They will have their
993 values filled in with the amount, number of seconds, and number of upload,
994 download, and total bytes applied by this prepaid card.
998 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
999 #the only place that uses these args
1000 sub recharge_prepay {
1001 my( $self, $prepay_credit, $amountref, $secondsref,
1002 $upbytesref, $downbytesref, $totalbytesref ) = @_;
1004 local $SIG{HUP} = 'IGNORE';
1005 local $SIG{INT} = 'IGNORE';
1006 local $SIG{QUIT} = 'IGNORE';
1007 local $SIG{TERM} = 'IGNORE';
1008 local $SIG{TSTP} = 'IGNORE';
1009 local $SIG{PIPE} = 'IGNORE';
1011 my $oldAutoCommit = $FS::UID::AutoCommit;
1012 local $FS::UID::AutoCommit = 0;
1015 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
1017 my $error = $self->get_prepay( $prepay_credit,
1018 'amount_ref' => \$amount,
1019 'seconds_ref' => \$seconds,
1020 'upbytes_ref' => \$upbytes,
1021 'downbytes_ref' => \$downbytes,
1022 'totalbytes_ref' => \$totalbytes,
1024 || $self->increment_seconds($seconds)
1025 || $self->increment_upbytes($upbytes)
1026 || $self->increment_downbytes($downbytes)
1027 || $self->increment_totalbytes($totalbytes)
1028 || $self->insert_cust_pay_prepay( $amount,
1030 ? $prepay_credit->identifier
1035 $dbh->rollback if $oldAutoCommit;
1039 if ( defined($amountref) ) { $$amountref = $amount; }
1040 if ( defined($secondsref) ) { $$secondsref = $seconds; }
1041 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1042 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1043 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1045 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1050 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1052 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1053 specified either by I<identifier> or as an FS::prepay_credit object.
1055 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
1056 incremented by the values of the prepaid card.
1058 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1059 check or set this customer's I<agentnum>.
1061 If there is an error, returns the error, otherwise returns false.
1067 my( $self, $prepay_credit, %opt ) = @_;
1069 local $SIG{HUP} = 'IGNORE';
1070 local $SIG{INT} = 'IGNORE';
1071 local $SIG{QUIT} = 'IGNORE';
1072 local $SIG{TERM} = 'IGNORE';
1073 local $SIG{TSTP} = 'IGNORE';
1074 local $SIG{PIPE} = 'IGNORE';
1076 my $oldAutoCommit = $FS::UID::AutoCommit;
1077 local $FS::UID::AutoCommit = 0;
1080 unless ( ref($prepay_credit) ) {
1082 my $identifier = $prepay_credit;
1084 $prepay_credit = qsearchs(
1086 { 'identifier' => $prepay_credit },
1091 unless ( $prepay_credit ) {
1092 $dbh->rollback if $oldAutoCommit;
1093 return "Invalid prepaid card: ". $identifier;
1098 if ( $prepay_credit->agentnum ) {
1099 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1100 $dbh->rollback if $oldAutoCommit;
1101 return "prepaid card not valid for agent ". $self->agentnum;
1103 $self->agentnum($prepay_credit->agentnum);
1106 my $error = $prepay_credit->delete;
1108 $dbh->rollback if $oldAutoCommit;
1109 return "removing prepay_credit (transaction rolled back): $error";
1112 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1113 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1115 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1120 =item increment_upbytes SECONDS
1122 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1123 the specified number of upbytes. If there is an error, returns the error,
1124 otherwise returns false.
1128 sub increment_upbytes {
1129 _increment_column( shift, 'upbytes', @_);
1132 =item increment_downbytes SECONDS
1134 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1135 the specified number of downbytes. If there is an error, returns the error,
1136 otherwise returns false.
1140 sub increment_downbytes {
1141 _increment_column( shift, 'downbytes', @_);
1144 =item increment_totalbytes SECONDS
1146 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1147 the specified number of totalbytes. If there is an error, returns the error,
1148 otherwise returns false.
1152 sub increment_totalbytes {
1153 _increment_column( shift, 'totalbytes', @_);
1156 =item increment_seconds SECONDS
1158 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1159 the specified number of seconds. If there is an error, returns the error,
1160 otherwise returns false.
1164 sub increment_seconds {
1165 _increment_column( shift, 'seconds', @_);
1168 =item _increment_column AMOUNT
1170 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1171 the specified number of seconds or bytes. If there is an error, returns
1172 the error, otherwise returns false.
1176 sub _increment_column {
1177 my( $self, $column, $amount ) = @_;
1178 warn "$me increment_column called: $column, $amount\n"
1181 return '' unless $amount;
1183 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1184 $self->ncancelled_pkgs;
1186 if ( ! @cust_pkg ) {
1187 return 'No packages with primary or single services found'.
1188 ' to apply pre-paid time';
1189 } elsif ( scalar(@cust_pkg) > 1 ) {
1190 #maybe have a way to specify the package/account?
1191 return 'Multiple packages found to apply pre-paid time';
1194 my $cust_pkg = $cust_pkg[0];
1195 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1199 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1201 if ( ! @cust_svc ) {
1202 return 'No account found to apply pre-paid time';
1203 } elsif ( scalar(@cust_svc) > 1 ) {
1204 return 'Multiple accounts found to apply pre-paid time';
1207 my $svc_acct = $cust_svc[0]->svc_x;
1208 warn " found service svcnum ". $svc_acct->pkgnum.
1209 ' ('. $svc_acct->email. ")\n"
1212 $column = "increment_$column";
1213 $svc_acct->$column($amount);
1217 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1219 Inserts a prepayment in the specified amount for this customer. An optional
1220 second argument can specify the prepayment identifier for tracking purposes.
1221 If there is an error, returns the error, otherwise returns false.
1225 sub insert_cust_pay_prepay {
1226 shift->insert_cust_pay('PREP', @_);
1229 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1231 Inserts a cash payment in the specified amount for this customer. An optional
1232 second argument can specify the payment identifier for tracking purposes.
1233 If there is an error, returns the error, otherwise returns false.
1237 sub insert_cust_pay_cash {
1238 shift->insert_cust_pay('CASH', @_);
1241 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1243 Inserts a Western Union payment in the specified amount for this customer. An
1244 optional second argument can specify the prepayment identifier for tracking
1245 purposes. If there is an error, returns the error, otherwise returns false.
1249 sub insert_cust_pay_west {
1250 shift->insert_cust_pay('WEST', @_);
1253 sub insert_cust_pay {
1254 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1255 my $payinfo = scalar(@_) ? shift : '';
1257 my $cust_pay = new FS::cust_pay {
1258 'custnum' => $self->custnum,
1259 'paid' => sprintf('%.2f', $amount),
1260 #'_date' => #date the prepaid card was purchased???
1262 'payinfo' => $payinfo,
1270 This method is deprecated. See the I<depend_jobnum> option to the insert and
1271 order_pkgs methods for a better way to defer provisioning.
1273 Re-schedules all exports by calling the B<reexport> method of all associated
1274 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1275 otherwise returns false.
1282 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1283 "use the depend_jobnum option to insert or order_pkgs to delay export";
1285 local $SIG{HUP} = 'IGNORE';
1286 local $SIG{INT} = 'IGNORE';
1287 local $SIG{QUIT} = 'IGNORE';
1288 local $SIG{TERM} = 'IGNORE';
1289 local $SIG{TSTP} = 'IGNORE';
1290 local $SIG{PIPE} = 'IGNORE';
1292 my $oldAutoCommit = $FS::UID::AutoCommit;
1293 local $FS::UID::AutoCommit = 0;
1296 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1297 my $error = $cust_pkg->reexport;
1299 $dbh->rollback if $oldAutoCommit;
1304 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1309 =item delete [ OPTION => VALUE ... ]
1311 This deletes the customer. If there is an error, returns the error, otherwise
1314 This will completely remove all traces of the customer record. This is not
1315 what you want when a customer cancels service; for that, cancel all of the
1316 customer's packages (see L</cancel>).
1318 If the customer has any uncancelled packages, you need to pass a new (valid)
1319 customer number for those packages to be transferred to, as the "new_customer"
1320 option. Cancelled packages will be deleted. Did I mention that this is NOT
1321 what you want when a customer cancels service and that you really should be
1322 looking at L<FS::cust_pkg/cancel>?
1324 You can't delete a customer with invoices (see L<FS::cust_bill>),
1325 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1326 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1327 set the "delete_financials" option to a true value.
1332 my( $self, %opt ) = @_;
1334 local $SIG{HUP} = 'IGNORE';
1335 local $SIG{INT} = 'IGNORE';
1336 local $SIG{QUIT} = 'IGNORE';
1337 local $SIG{TERM} = 'IGNORE';
1338 local $SIG{TSTP} = 'IGNORE';
1339 local $SIG{PIPE} = 'IGNORE';
1341 my $oldAutoCommit = $FS::UID::AutoCommit;
1342 local $FS::UID::AutoCommit = 0;
1345 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1346 $dbh->rollback if $oldAutoCommit;
1347 return "Can't delete a master agent customer";
1350 #use FS::access_user
1351 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1352 $dbh->rollback if $oldAutoCommit;
1353 return "Can't delete a master employee customer";
1356 tie my %financial_tables, 'Tie::IxHash',
1357 'cust_bill' => 'invoices',
1358 'cust_statement' => 'statements',
1359 'cust_credit' => 'credits',
1360 'cust_pay' => 'payments',
1361 'cust_refund' => 'refunds',
1364 foreach my $table ( keys %financial_tables ) {
1366 my @records = $self->$table();
1368 if ( @records && ! $opt{'delete_financials'} ) {
1369 $dbh->rollback if $oldAutoCommit;
1370 return "Can't delete a customer with ". $financial_tables{$table};
1373 foreach my $record ( @records ) {
1374 my $error = $record->delete;
1376 $dbh->rollback if $oldAutoCommit;
1377 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1383 my @cust_pkg = $self->ncancelled_pkgs;
1385 my $new_custnum = $opt{'new_custnum'};
1386 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1387 $dbh->rollback if $oldAutoCommit;
1388 return "Invalid new customer number: $new_custnum";
1390 foreach my $cust_pkg ( @cust_pkg ) {
1391 my %hash = $cust_pkg->hash;
1392 $hash{'custnum'} = $new_custnum;
1393 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1394 my $error = $new_cust_pkg->replace($cust_pkg,
1395 options => { $cust_pkg->options },
1398 $dbh->rollback if $oldAutoCommit;
1403 my @cancelled_cust_pkg = $self->all_pkgs;
1404 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1405 my $error = $cust_pkg->delete;
1407 $dbh->rollback if $oldAutoCommit;
1412 #cust_tax_adjustment in financials?
1413 #cust_pay_pending? ouch
1415 foreach my $table (qw(
1416 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1417 cust_location cust_main_note cust_tax_adjustment
1418 cust_pay_void cust_pay_batch queue cust_tax_exempt
1420 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1421 my $error = $record->delete;
1423 $dbh->rollback if $oldAutoCommit;
1429 my $sth = $dbh->prepare(
1430 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1432 my $errstr = $dbh->errstr;
1433 $dbh->rollback if $oldAutoCommit;
1436 $sth->execute($self->custnum) or do {
1437 my $errstr = $sth->errstr;
1438 $dbh->rollback if $oldAutoCommit;
1444 my $ticket_dbh = '';
1445 if ($conf->config('ticket_system') eq 'RT_Internal') {
1447 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1448 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1449 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1450 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1453 if ( $ticket_dbh ) {
1455 my $ticket_sth = $ticket_dbh->prepare(
1456 'DELETE FROM Links WHERE Target = ?'
1458 my $errstr = $ticket_dbh->errstr;
1459 $dbh->rollback if $oldAutoCommit;
1462 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1464 my $errstr = $ticket_sth->errstr;
1465 $dbh->rollback if $oldAutoCommit;
1469 #check and see if the customer is the only link on the ticket, and
1470 #if so, set the ticket to deleted status in RT?
1471 #maybe someday, for now this will at least fix tickets not displaying
1475 #delete the customer record
1477 my $error = $self->SUPER::delete;
1479 $dbh->rollback if $oldAutoCommit;
1483 # cust_main exports!
1485 #my $export_args = $options{'export_args'} || [];
1488 map qsearch( 'part_export', {exportnum=>$_} ),
1489 $conf->config('cust_main-exports'); #, $agentnum
1491 foreach my $part_export ( @part_export ) {
1492 my $error = $part_export->export_delete( $self ); #, @$export_args);
1494 $dbh->rollback if $oldAutoCommit;
1495 return "exporting to ". $part_export->exporttype.
1496 " (transaction rolled back): $error";
1500 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1505 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1508 Replaces the OLD_RECORD with this one in the database. If there is an error,
1509 returns the error, otherwise returns false.
1511 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1512 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1513 expected and rollback the entire transaction; it is not necessary to call
1514 check_invoicing_list first. Here's an example:
1516 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1518 Currently available options are: I<tax_exemption>.
1520 The I<tax_exemption> option can be set to an arrayref of tax names.
1521 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1528 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1530 : $self->replace_old;
1534 warn "$me replace called\n"
1537 my $curuser = $FS::CurrentUser::CurrentUser;
1538 if ( $self->payby eq 'COMP'
1539 && $self->payby ne $old->payby
1540 && ! $curuser->access_right('Complimentary customer')
1543 return "You are not permitted to create complimentary accounts.";
1546 local($ignore_expired_card) = 1
1547 if $old->payby =~ /^(CARD|DCRD)$/
1548 && $self->payby =~ /^(CARD|DCRD)$/
1549 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1551 local $SIG{HUP} = 'IGNORE';
1552 local $SIG{INT} = 'IGNORE';
1553 local $SIG{QUIT} = 'IGNORE';
1554 local $SIG{TERM} = 'IGNORE';
1555 local $SIG{TSTP} = 'IGNORE';
1556 local $SIG{PIPE} = 'IGNORE';
1558 my $oldAutoCommit = $FS::UID::AutoCommit;
1559 local $FS::UID::AutoCommit = 0;
1562 my $error = $self->SUPER::replace($old);
1565 $dbh->rollback if $oldAutoCommit;
1569 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1570 my $invoicing_list = shift @param;
1571 $error = $self->check_invoicing_list( $invoicing_list );
1573 $dbh->rollback if $oldAutoCommit;
1576 $self->invoicing_list( $invoicing_list );
1579 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1581 #this could be more efficient than deleting and re-inserting, if it matters
1582 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1583 my $error = $cust_tag->delete;
1585 $dbh->rollback if $oldAutoCommit;
1589 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1590 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1591 'custnum' => $self->custnum };
1592 my $error = $cust_tag->insert;
1594 $dbh->rollback if $oldAutoCommit;
1601 my %options = @param;
1603 my $tax_exemption = delete $options{'tax_exemption'};
1604 if ( $tax_exemption ) {
1606 my %cust_main_exemption =
1607 map { $_->taxname => $_ }
1608 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1610 foreach my $taxname ( @$tax_exemption ) {
1612 next if delete $cust_main_exemption{$taxname};
1614 my $cust_main_exemption = new FS::cust_main_exemption {
1615 'custnum' => $self->custnum,
1616 'taxname' => $taxname,
1618 my $error = $cust_main_exemption->insert;
1620 $dbh->rollback if $oldAutoCommit;
1621 return "inserting cust_main_exemption (transaction rolled back): $error";
1625 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1626 my $error = $cust_main_exemption->delete;
1628 $dbh->rollback if $oldAutoCommit;
1629 return "deleting cust_main_exemption (transaction rolled back): $error";
1635 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1636 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1637 && $self->get('payinfo') !~ /^99\d{14}$/
1639 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1644 # card/check/lec info has changed, want to retry realtime_ invoice events
1645 my $error = $self->retry_realtime;
1647 $dbh->rollback if $oldAutoCommit;
1652 unless ( $import || $skip_fuzzyfiles ) {
1653 $error = $self->queue_fuzzyfiles_update;
1655 $dbh->rollback if $oldAutoCommit;
1656 return "updating fuzzy search cache: $error";
1660 # cust_main exports!
1662 my $export_args = $options{'export_args'} || [];
1665 map qsearch( 'part_export', {exportnum=>$_} ),
1666 $conf->config('cust_main-exports'); #, $agentnum
1668 foreach my $part_export ( @part_export ) {
1669 my $error = $part_export->export_replace( $self, $old, @$export_args);
1671 $dbh->rollback if $oldAutoCommit;
1672 return "exporting to ". $part_export->exporttype.
1673 " (transaction rolled back): $error";
1677 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1682 =item queue_fuzzyfiles_update
1684 Used by insert & replace to update the fuzzy search cache
1688 sub queue_fuzzyfiles_update {
1691 local $SIG{HUP} = 'IGNORE';
1692 local $SIG{INT} = 'IGNORE';
1693 local $SIG{QUIT} = 'IGNORE';
1694 local $SIG{TERM} = 'IGNORE';
1695 local $SIG{TSTP} = 'IGNORE';
1696 local $SIG{PIPE} = 'IGNORE';
1698 my $oldAutoCommit = $FS::UID::AutoCommit;
1699 local $FS::UID::AutoCommit = 0;
1702 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1703 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1705 $dbh->rollback if $oldAutoCommit;
1706 return "queueing job (transaction rolled back): $error";
1709 if ( $self->ship_last ) {
1710 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1711 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1713 $dbh->rollback if $oldAutoCommit;
1714 return "queueing job (transaction rolled back): $error";
1718 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1725 Checks all fields to make sure this is a valid customer record. If there is
1726 an error, returns the error, otherwise returns false. Called by the insert
1727 and replace methods.
1734 warn "$me check BEFORE: \n". $self->_dump
1738 $self->ut_numbern('custnum')
1739 || $self->ut_number('agentnum')
1740 || $self->ut_textn('agent_custid')
1741 || $self->ut_number('refnum')
1742 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1743 || $self->ut_textn('custbatch')
1744 || $self->ut_name('last')
1745 || $self->ut_name('first')
1746 || $self->ut_snumbern('birthdate')
1747 || $self->ut_snumbern('signupdate')
1748 || $self->ut_textn('company')
1749 || $self->ut_text('address1')
1750 || $self->ut_textn('address2')
1751 || $self->ut_text('city')
1752 || $self->ut_textn('county')
1753 || $self->ut_textn('state')
1754 || $self->ut_country('country')
1755 || $self->ut_anything('comments')
1756 || $self->ut_numbern('referral_custnum')
1757 || $self->ut_textn('stateid')
1758 || $self->ut_textn('stateid_state')
1759 || $self->ut_textn('invoice_terms')
1760 || $self->ut_alphan('geocode')
1761 || $self->ut_floatn('cdr_termination_percentage')
1764 #barf. need message catalogs. i18n. etc.
1765 $error .= "Please select an advertising source."
1766 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1767 return $error if $error;
1769 return "Unknown agent"
1770 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1772 return "Unknown refnum"
1773 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1775 return "Unknown referring custnum: ". $self->referral_custnum
1776 unless ! $self->referral_custnum
1777 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1779 if ( $self->censustract ne '' ) {
1780 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1781 or return "Illegal census tract: ". $self->censustract;
1783 $self->censustract("$1.$2");
1786 if ( $self->ss eq '' ) {
1791 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1792 or return "Illegal social security number: ". $self->ss;
1793 $self->ss("$1-$2-$3");
1797 # bad idea to disable, causes billing to fail because of no tax rates later
1798 # except we don't fail any more
1799 unless ( $import ) {
1800 unless ( qsearch('cust_main_county', {
1801 'country' => $self->country,
1804 return "Unknown state/county/country: ".
1805 $self->state. "/". $self->county. "/". $self->country
1806 unless qsearch('cust_main_county',{
1807 'state' => $self->state,
1808 'county' => $self->county,
1809 'country' => $self->country,
1815 $self->ut_phonen('daytime', $self->country)
1816 || $self->ut_phonen('night', $self->country)
1817 || $self->ut_phonen('fax', $self->country)
1818 || $self->ut_zip('zip', $self->country)
1820 return $error if $error;
1822 if ( $conf->exists('cust_main-require_phone')
1823 && ! length($self->daytime) && ! length($self->night)
1826 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1828 : FS::Msgcat::_gettext('daytime');
1829 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1831 : FS::Msgcat::_gettext('night');
1833 return "$daytime_label or $night_label is required"
1837 if ( $self->has_ship_address
1838 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1839 $self->addr_fields )
1843 $self->ut_name('ship_last')
1844 || $self->ut_name('ship_first')
1845 || $self->ut_textn('ship_company')
1846 || $self->ut_text('ship_address1')
1847 || $self->ut_textn('ship_address2')
1848 || $self->ut_text('ship_city')
1849 || $self->ut_textn('ship_county')
1850 || $self->ut_textn('ship_state')
1851 || $self->ut_country('ship_country')
1853 return $error if $error;
1855 #false laziness with above
1856 unless ( qsearchs('cust_main_county', {
1857 'country' => $self->ship_country,
1860 return "Unknown ship_state/ship_county/ship_country: ".
1861 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1862 unless qsearch('cust_main_county',{
1863 'state' => $self->ship_state,
1864 'county' => $self->ship_county,
1865 'country' => $self->ship_country,
1871 $self->ut_phonen('ship_daytime', $self->ship_country)
1872 || $self->ut_phonen('ship_night', $self->ship_country)
1873 || $self->ut_phonen('ship_fax', $self->ship_country)
1874 || $self->ut_zip('ship_zip', $self->ship_country)
1876 return $error if $error;
1878 return "Unit # is required."
1879 if $self->ship_address2 =~ /^\s*$/
1880 && $conf->exists('cust_main-require_address2');
1882 } else { # ship_ info eq billing info, so don't store dup info in database
1884 $self->setfield("ship_$_", '')
1885 foreach $self->addr_fields;
1887 return "Unit # is required."
1888 if $self->address2 =~ /^\s*$/
1889 && $conf->exists('cust_main-require_address2');
1893 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1894 # or return "Illegal payby: ". $self->payby;
1896 FS::payby->can_payby($self->table, $self->payby)
1897 or return "Illegal payby: ". $self->payby;
1899 $error = $self->ut_numbern('paystart_month')
1900 || $self->ut_numbern('paystart_year')
1901 || $self->ut_numbern('payissue')
1902 || $self->ut_textn('paytype')
1904 return $error if $error;
1906 if ( $self->payip eq '' ) {
1909 $error = $self->ut_ip('payip');
1910 return $error if $error;
1913 # If it is encrypted and the private key is not availaible then we can't
1914 # check the credit card.
1915 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1917 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1919 my $payinfo = $self->payinfo;
1920 $payinfo =~ s/\D//g;
1921 $payinfo =~ /^(\d{13,16})$/
1922 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1924 $self->payinfo($payinfo);
1926 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1928 return gettext('unknown_card_type')
1929 if $self->payinfo !~ /^99\d{14}$/ #token
1930 && cardtype($self->payinfo) eq "Unknown";
1932 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1934 return 'Banned credit card: banned on '.
1935 time2str('%a %h %o at %r', $ban->_date).
1936 ' by '. $ban->otaker.
1937 ' (ban# '. $ban->bannum. ')';
1940 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1941 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1942 $self->paycvv =~ /^(\d{4})$/
1943 or return "CVV2 (CID) for American Express cards is four digits.";
1946 $self->paycvv =~ /^(\d{3})$/
1947 or return "CVV2 (CVC2/CID) is three digits.";
1954 my $cardtype = cardtype($payinfo);
1955 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1957 return "Start date or issue number is required for $cardtype cards"
1958 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1960 return "Start month must be between 1 and 12"
1961 if $self->paystart_month
1962 and $self->paystart_month < 1 || $self->paystart_month > 12;
1964 return "Start year must be 1990 or later"
1965 if $self->paystart_year
1966 and $self->paystart_year < 1990;
1968 return "Issue number must be beween 1 and 99"
1970 and $self->payissue < 1 || $self->payissue > 99;
1973 $self->paystart_month('');
1974 $self->paystart_year('');
1975 $self->payissue('');
1978 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1980 my $payinfo = $self->payinfo;
1981 $payinfo =~ s/[^\d\@]//g;
1982 if ( $conf->exists('echeck-nonus') ) {
1983 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1984 $payinfo = "$1\@$2";
1986 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1987 $payinfo = "$1\@$2";
1989 $self->payinfo($payinfo);
1992 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1994 return 'Banned ACH account: banned on '.
1995 time2str('%a %h %o at %r', $ban->_date).
1996 ' by '. $ban->otaker.
1997 ' (ban# '. $ban->bannum. ')';
2000 } elsif ( $self->payby eq 'LECB' ) {
2002 my $payinfo = $self->payinfo;
2003 $payinfo =~ s/\D//g;
2004 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2006 $self->payinfo($payinfo);
2009 } elsif ( $self->payby eq 'BILL' ) {
2011 $error = $self->ut_textn('payinfo');
2012 return "Illegal P.O. number: ". $self->payinfo if $error;
2015 } elsif ( $self->payby eq 'COMP' ) {
2017 my $curuser = $FS::CurrentUser::CurrentUser;
2018 if ( ! $self->custnum
2019 && ! $curuser->access_right('Complimentary customer')
2022 return "You are not permitted to create complimentary accounts."
2025 $error = $self->ut_textn('payinfo');
2026 return "Illegal comp account issuer: ". $self->payinfo if $error;
2029 } elsif ( $self->payby eq 'PREPAY' ) {
2031 my $payinfo = $self->payinfo;
2032 $payinfo =~ s/\W//g; #anything else would just confuse things
2033 $self->payinfo($payinfo);
2034 $error = $self->ut_alpha('payinfo');
2035 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2036 return "Unknown prepayment identifier"
2037 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2042 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2043 return "Expiration date required"
2044 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2048 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2049 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2050 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2051 ( $m, $y ) = ( $2, "19$1" );
2052 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2053 ( $m, $y ) = ( $3, "20$2" );
2055 return "Illegal expiration date: ". $self->paydate;
2057 $self->paydate("$y-$m-01");
2058 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2059 return gettext('expired_card')
2061 && !$ignore_expired_card
2062 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2065 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2066 ( ! $conf->exists('require_cardname')
2067 || $self->payby !~ /^(CARD|DCRD)$/ )
2069 $self->payname( $self->first. " ". $self->getfield('last') );
2071 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2072 or return gettext('illegal_name'). " payname: ". $self->payname;
2076 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2077 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2081 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2083 warn "$me check AFTER: \n". $self->_dump
2086 $self->SUPER::check;
2091 Returns a list of fields which have ship_ duplicates.
2096 qw( last first company
2097 address1 address2 city county state zip country
2102 =item has_ship_address
2104 Returns true if this customer record has a separate shipping address.
2108 sub has_ship_address {
2110 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2115 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2116 city, county, state, zip, country. The shipping address is used if present.
2120 #geocode? dependent on tax-ship_address config, not available in cust_location
2121 #mostly. not yet then.
2125 my $prefix = $self->has_ship_address ? 'ship_' : '';
2127 map { $_ => $self->get($prefix.$_) }
2128 qw( address1 address2 city county state zip country geocode );
2129 #fields that cust_location has
2132 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2134 Returns all packages (see L<FS::cust_pkg>) for this customer.
2140 my $extra_qsearch = ref($_[0]) ? shift : {};
2142 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
2145 if ( $self->{'_pkgnum'} ) {
2146 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2148 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2151 sort sort_packages @cust_pkg;
2156 Synonym for B<all_pkgs>.
2161 shift->all_pkgs(@_);
2166 Returns all locations (see L<FS::cust_location>) for this customer.
2172 qsearch('cust_location', { 'custnum' => $self->custnum } );
2175 =item location_label [ OPTION => VALUE ... ]
2177 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2185 used to separate the address elements (defaults to ', ')
2187 =item escape_function
2189 a callback used for escaping the text of the address elements
2195 # false laziness with FS::cust_location::line
2197 sub location_label {
2201 my $separator = $opt{join_string} || ', ';
2202 my $escape = $opt{escape_function} || sub{ shift };
2204 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2205 my $prefix = length($self->ship_last) ? 'ship_' : '';
2208 foreach (qw ( address1 address2 ) ) {
2209 my $method = "$prefix$_";
2210 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2215 foreach (qw ( city county state zip ) ) {
2216 my $method = "$prefix$_";
2217 if ( $self->$method ) {
2218 $line .= ' (' if $method eq 'county';
2219 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2220 $line .= ' )' if $method eq 'county';
2224 $line .= $separator. &$escape(code2country($self->country))
2225 if $self->country ne $cydefault;
2230 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2232 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2236 sub ncancelled_pkgs {
2238 my $extra_qsearch = ref($_[0]) ? shift : {};
2240 return $self->num_ncancelled_pkgs unless wantarray;
2243 if ( $self->{'_pkgnum'} ) {
2245 warn "$me ncancelled_pkgs: returning cached objects"
2248 @cust_pkg = grep { ! $_->getfield('cancel') }
2249 values %{ $self->{'_pkgnum'}->cache };
2253 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2254 $self->custnum. "\n"
2257 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2259 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2263 sort sort_packages @cust_pkg;
2269 my $extra_qsearch = ref($_[0]) ? shift : {};
2271 $extra_qsearch->{'select'} ||= '*';
2272 $extra_qsearch->{'select'} .=
2273 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2277 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2282 'table' => 'cust_pkg',
2283 'hashref' => { 'custnum' => $self->custnum },
2288 # This should be generalized to use config options to determine order.
2291 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2292 return $locationsort if $locationsort;
2294 if ( $a->get('cancel') xor $b->get('cancel') ) {
2295 return -1 if $b->get('cancel');
2296 return 1 if $a->get('cancel');
2297 #shouldn't get here...
2300 my $a_num_cust_svc = $a->num_cust_svc;
2301 my $b_num_cust_svc = $b->num_cust_svc;
2302 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2303 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2304 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2305 my @a_cust_svc = $a->cust_svc;
2306 my @b_cust_svc = $b->cust_svc;
2307 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2308 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2309 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
2310 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2315 =item suspended_pkgs
2317 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2321 sub suspended_pkgs {
2323 grep { $_->susp } $self->ncancelled_pkgs;
2326 =item unflagged_suspended_pkgs
2328 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2329 customer (thouse packages without the `manual_flag' set).
2333 sub unflagged_suspended_pkgs {
2335 return $self->suspended_pkgs
2336 unless dbdef->table('cust_pkg')->column('manual_flag');
2337 grep { ! $_->manual_flag } $self->suspended_pkgs;
2340 =item unsuspended_pkgs
2342 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2347 sub unsuspended_pkgs {
2349 grep { ! $_->susp } $self->ncancelled_pkgs;
2352 =item next_bill_date
2354 Returns the next date this customer will be billed, as a UNIX timestamp, or
2355 undef if no active package has a next bill date.
2359 sub next_bill_date {
2361 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2364 =item num_cancelled_pkgs
2366 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2371 sub num_cancelled_pkgs {
2372 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2375 sub num_ncancelled_pkgs {
2376 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2380 my( $self ) = shift;
2381 my $sql = scalar(@_) ? shift : '';
2382 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2383 my $sth = dbh->prepare(
2384 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2385 ) or die dbh->errstr;
2386 $sth->execute($self->custnum) or die $sth->errstr;
2387 $sth->fetchrow_arrayref->[0];
2392 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2393 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2394 on success or a list of errors.
2400 grep { $_->unsuspend } $self->suspended_pkgs;
2405 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2407 Returns a list: an empty list on success or a list of errors.
2413 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2416 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2418 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2419 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2420 of a list of pkgparts; the hashref has the following keys:
2424 =item pkgparts - listref of pkgparts
2426 =item (other options are passed to the suspend method)
2431 Returns a list: an empty list on success or a list of errors.
2435 sub suspend_if_pkgpart {
2437 my (@pkgparts, %opt);
2438 if (ref($_[0]) eq 'HASH'){
2439 @pkgparts = @{$_[0]{pkgparts}};
2444 grep { $_->suspend(%opt) }
2445 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2446 $self->unsuspended_pkgs;
2449 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2451 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2452 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2453 instead of a list of pkgparts; the hashref has the following keys:
2457 =item pkgparts - listref of pkgparts
2459 =item (other options are passed to the suspend method)
2463 Returns a list: an empty list on success or a list of errors.
2467 sub suspend_unless_pkgpart {
2469 my (@pkgparts, %opt);
2470 if (ref($_[0]) eq 'HASH'){
2471 @pkgparts = @{$_[0]{pkgparts}};
2476 grep { $_->suspend(%opt) }
2477 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2478 $self->unsuspended_pkgs;
2481 =item cancel [ OPTION => VALUE ... ]
2483 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2485 Available options are:
2489 =item quiet - can be set true to supress email cancellation notices.
2491 =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.
2493 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2495 =item nobill - can be set true to skip billing if it might otherwise be done.
2499 Always returns a list: an empty list on success or a list of errors.
2503 # nb that dates are not specified as valid options to this method
2506 my( $self, %opt ) = @_;
2508 warn "$me cancel called on customer ". $self->custnum. " with options ".
2509 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2512 return ( 'access denied' )
2513 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2515 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2517 #should try decryption (we might have the private key)
2518 # and if not maybe queue a job for the server that does?
2519 return ( "Can't (yet) ban encrypted credit cards" )
2520 if $self->is_encrypted($self->payinfo);
2522 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2523 my $error = $ban->insert;
2524 return ( $error ) if $error;
2528 my @pkgs = $self->ncancelled_pkgs;
2530 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2532 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2533 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2537 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2538 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2541 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2544 sub _banned_pay_hashref {
2555 'payby' => $payby2ban{$self->payby},
2556 'payinfo' => md5_base64($self->payinfo),
2557 #don't ever *search* on reason! #'reason' =>
2563 Returns all notes (see L<FS::cust_main_note>) for this customer.
2570 qsearch( 'cust_main_note',
2571 { 'custnum' => $self->custnum },
2573 'ORDER BY _DATE DESC'
2579 Returns the agent (see L<FS::agent>) for this customer.
2585 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2590 Returns the agent name (see L<FS::agent>) for this customer.
2596 $self->agent->agent;
2601 Returns any tags associated with this customer, as FS::cust_tag objects,
2602 or an empty list if there are no tags.
2608 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2613 Returns any tags associated with this customer, as FS::part_tag objects,
2614 or an empty list if there are no tags.
2620 map $_->part_tag, $self->cust_tag;
2626 Returns the customer class, as an FS::cust_class object, or the empty string
2627 if there is no customer class.
2633 if ( $self->classnum ) {
2634 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2642 Returns the customer category name, or the empty string if there is no customer
2649 my $cust_class = $self->cust_class;
2651 ? $cust_class->categoryname
2657 Returns the customer class name, or the empty string if there is no customer
2664 my $cust_class = $self->cust_class;
2666 ? $cust_class->classname
2671 =item bill_and_collect
2673 Cancels and suspends any packages due, generates bills, applies payments and
2674 credits, and applies collection events to run cards, send bills and notices,
2677 By default, warns on errors and continues with the next operation (but see the
2678 "fatal" flag below).
2680 Options are passed as name-value pairs. Currently available options are:
2686 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:
2690 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2694 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.
2698 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2702 If set true, re-charges setup fees.
2706 If set any errors prevent subsequent operations from continusing. If set
2707 specifically to "return", returns the error (or false, if there is no error).
2708 Any other true value causes errors to die.
2712 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)
2716 Optional FS::queue entry to receive status updates.
2720 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2721 options of those methods are also available.
2725 sub bill_and_collect {
2726 my( $self, %options ) = @_;
2730 #$options{actual_time} not $options{time} because freeside-daily -d is for
2731 #pre-printing invoices
2733 $options{'actual_time'} ||= time;
2734 my $job = $options{'job'};
2736 $job->update_statustext('0,cleaning expired packages') if $job;
2737 $error = $self->cancel_expired_pkgs( $options{actual_time} );
2739 $error = "Error expiring custnum ". $self->custnum. ": $error";
2740 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2741 elsif ( $options{fatal} ) { die $error; }
2742 else { warn $error; }
2745 $error = $self->suspend_adjourned_pkgs( $options{actual_time} );
2747 $error = "Error adjourning custnum ". $self->custnum. ": $error";
2748 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2749 elsif ( $options{fatal} ) { die $error; }
2750 else { warn $error; }
2753 $job->update_statustext('20,billing packages') if $job;
2754 $error = $self->bill( %options );
2756 $error = "Error billing custnum ". $self->custnum. ": $error";
2757 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2758 elsif ( $options{fatal} ) { die $error; }
2759 else { warn $error; }
2762 $job->update_statustext('50,applying payments and credits') if $job;
2763 $error = $self->apply_payments_and_credits;
2765 $error = "Error applying custnum ". $self->custnum. ": $error";
2766 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2767 elsif ( $options{fatal} ) { die $error; }
2768 else { warn $error; }
2771 $job->update_statustext('70,running collection events') if $job;
2772 unless ( $conf->exists('cancelled_cust-noevents')
2773 && ! $self->num_ncancelled_pkgs
2775 $error = $self->collect( %options );
2777 $error = "Error collecting custnum ". $self->custnum. ": $error";
2778 if ($options{fatal} && $options{fatal} eq 'return') { return $error; }
2779 elsif ($options{fatal} ) { die $error; }
2780 else { warn $error; }
2783 $job->update_statustext('100,finished') if $job;
2789 sub cancel_expired_pkgs {
2790 my ( $self, $time, %options ) = @_;
2792 my @cancel_pkgs = $self->ncancelled_pkgs( {
2793 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2798 foreach my $cust_pkg ( @cancel_pkgs ) {
2799 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2800 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2801 'reason_otaker' => $cpr->otaker
2805 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2808 scalar(@errors) ? join(' / ', @errors) : '';
2812 sub suspend_adjourned_pkgs {
2813 my ( $self, $time, %options ) = @_;
2815 my @susp_pkgs = $self->ncancelled_pkgs( {
2817 " AND ( susp IS NULL OR susp = 0 )
2818 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
2819 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2824 #only because there's no SQL test for is_prepaid :/
2826 grep { ( $_->part_pkg->is_prepaid
2831 && $_->adjourn <= $time
2839 foreach my $cust_pkg ( @susp_pkgs ) {
2840 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2841 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2842 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2843 'reason_otaker' => $cpr->otaker
2847 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2850 scalar(@errors) ? join(' / ', @errors) : '';
2856 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2857 conjunction with the collect method by calling B<bill_and_collect>.
2859 If there is an error, returns the error, otherwise returns false.
2861 Options are passed as name-value pairs. Currently available options are:
2867 If set true, re-charges setup fees.
2871 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:
2875 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2879 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2881 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2885 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2889 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.
2893 This boolean value informs the us that the package is being cancelled. This
2894 typically might mean not charging the normal recurring fee but only usage
2895 fees since the last billing. Setup charges may be charged. Not all package
2896 plans support this feature (they tend to charge 0).
2900 Optional terms to be printed on this invoice. Otherwise, customer-specific
2901 terms or the default terms are used.
2908 my( $self, %options ) = @_;
2909 return '' if $self->payby eq 'COMP';
2910 warn "$me bill customer ". $self->custnum. "\n"
2913 my $time = $options{'time'} || time;
2914 my $invoice_time = $options{'invoice_time'} || $time;
2916 $options{'not_pkgpart'} ||= {};
2917 $options{'not_pkgpart'} = { map { $_ => 1 }
2918 split(/\s*,\s*/, $options{'not_pkgpart'})
2920 unless ref($options{'not_pkgpart'});
2922 local $SIG{HUP} = 'IGNORE';
2923 local $SIG{INT} = 'IGNORE';
2924 local $SIG{QUIT} = 'IGNORE';
2925 local $SIG{TERM} = 'IGNORE';
2926 local $SIG{TSTP} = 'IGNORE';
2927 local $SIG{PIPE} = 'IGNORE';
2929 my $oldAutoCommit = $FS::UID::AutoCommit;
2930 local $FS::UID::AutoCommit = 0;
2933 warn "$me acquiring lock on customer ". $self->custnum. "\n"
2936 $self->select_for_update; #mutex
2938 warn "$me running pre-bill events for customer ". $self->custnum. "\n"
2941 my $error = $self->do_cust_event(
2942 'debug' => ( $options{'debug'} || 0 ),
2943 'time' => $invoice_time,
2944 'check_freq' => $options{'check_freq'},
2945 'stage' => 'pre-bill',
2948 $dbh->rollback if $oldAutoCommit;
2952 warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
2955 #keep auto-charge and non-auto-charge line items separate
2956 my @passes = ( '', 'no_auto' );
2958 my %cust_bill_pkg = map { $_ => [] } @passes;
2961 # find the packages which are due for billing, find out how much they are
2962 # & generate invoice database.
2965 my %total_setup = map { my $z = 0; $_ => \$z; } @passes;
2966 my %total_recur = map { my $z = 0; $_ => \$z; } @passes;
2968 my %taxlisthash = map { $_ => {} } @passes;
2970 my @precommit_hooks = ();
2972 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
2973 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2975 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2977 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2979 #? to avoid use of uninitialized value errors... ?
2980 $cust_pkg->setfield('bill', '')
2981 unless defined($cust_pkg->bill);
2983 #my $part_pkg = $cust_pkg->part_pkg;
2985 my $real_pkgpart = $cust_pkg->pkgpart;
2986 my %hash = $cust_pkg->hash;
2988 # we could implement this bit as FS::part_pkg::has_hidden, but we already
2989 # suffer from performance issues
2990 $options{has_hidden} = 0;
2991 my @part_pkg = $cust_pkg->part_pkg->self_and_bill_linked;
2992 $options{has_hidden} = 1 if ($part_pkg[1] && $part_pkg[1]->hidden);
2994 foreach my $part_pkg ( @part_pkg ) {
2996 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2998 my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
3001 $self->_make_lines( 'part_pkg' => $part_pkg,
3002 'cust_pkg' => $cust_pkg,
3003 'precommit_hooks' => \@precommit_hooks,
3004 'line_items' => $cust_bill_pkg{$pass},
3005 'setup' => $total_setup{$pass},
3006 'recur' => $total_recur{$pass},
3007 'tax_matrix' => $taxlisthash{$pass},
3009 'real_pkgpart' => $real_pkgpart,
3010 'options' => \%options,
3013 $dbh->rollback if $oldAutoCommit;
3017 } #foreach my $part_pkg
3019 } #foreach my $cust_pkg
3021 #if the customer isn't on an automatic payby, everything can go on a single
3023 #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
3024 #merge everything into one list
3027 foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
3029 my @cust_bill_pkg = _omit_zero_value_bundles(@{ $cust_bill_pkg{$pass} });
3031 next unless @cust_bill_pkg; #don't create an invoice w/o line items
3033 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
3034 !$conf->exists('postal_invoice-recurring_only')
3038 my $postal_pkg = $self->charge_postal_fee();
3039 if ( $postal_pkg && !ref( $postal_pkg ) ) {
3041 $dbh->rollback if $oldAutoCommit;
3042 return "can't charge postal invoice fee for customer ".
3043 $self->custnum. ": $postal_pkg";
3045 } elsif ( $postal_pkg ) {
3047 my $real_pkgpart = $postal_pkg->pkgpart;
3048 # we could implement this bit as FS::part_pkg::has_hidden, but we already
3049 # suffer from performance issues
3050 $options{has_hidden} = 0;
3051 my @part_pkg = $postal_pkg->part_pkg->self_and_bill_linked;
3052 $options{has_hidden} = 1 if ($part_pkg[1] && $part_pkg[1]->hidden);
3054 foreach my $part_pkg ( @part_pkg ) {
3055 my %postal_options = %options;
3056 delete $postal_options{cancel};
3058 $self->_make_lines( 'part_pkg' => $part_pkg,
3059 'cust_pkg' => $postal_pkg,
3060 'precommit_hooks' => \@precommit_hooks,
3061 'line_items' => \@cust_bill_pkg,
3062 'setup' => $total_setup{$pass},
3063 'recur' => $total_recur{$pass},
3064 'tax_matrix' => $taxlisthash{$pass},
3066 'real_pkgpart' => $real_pkgpart,
3067 'options' => \%postal_options,
3070 $dbh->rollback if $oldAutoCommit;
3075 # it's silly to have a zero value postal_pkg, but....
3076 @cust_bill_pkg = _omit_zero_value_bundles(@cust_bill_pkg);
3082 my $listref_or_error =
3083 $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
3085 unless ( ref( $listref_or_error ) ) {
3086 $dbh->rollback if $oldAutoCommit;
3087 return $listref_or_error;
3090 foreach my $taxline ( @$listref_or_error ) {
3091 ${ $total_setup{$pass} } =
3092 sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
3093 push @cust_bill_pkg, $taxline;
3096 #add tax adjustments
3097 warn "adding tax adjustments...\n" if $DEBUG > 2;
3098 foreach my $cust_tax_adjustment (
3099 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
3105 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
3107 my $itemdesc = $cust_tax_adjustment->taxname;
3108 $itemdesc = '' if $itemdesc eq 'Tax';
3110 push @cust_bill_pkg, new FS::cust_bill_pkg {
3116 'itemdesc' => $itemdesc,
3117 'itemcomment' => $cust_tax_adjustment->comment,
3118 'cust_tax_adjustment' => $cust_tax_adjustment,
3119 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3124 my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
3126 my @cust_bill = $self->cust_bill;
3127 my $balance = $self->balance;
3128 my $previous_balance = scalar(@cust_bill)
3129 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
3132 $previous_balance += $cust_bill[$#cust_bill]->charged
3133 if scalar(@cust_bill);
3134 #my $balance_adjustments =
3135 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
3137 #create the new invoice
3138 my $cust_bill = new FS::cust_bill ( {
3139 'custnum' => $self->custnum,
3140 '_date' => ( $invoice_time ),
3141 'charged' => $charged,
3142 'billing_balance' => $balance,
3143 'previous_balance' => $previous_balance,
3144 'invoice_terms' => $options{'invoice_terms'},
3146 $error = $cust_bill->insert;
3148 $dbh->rollback if $oldAutoCommit;
3149 return "can't create invoice for customer #". $self->custnum. ": $error";
3152 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
3153 $cust_bill_pkg->invnum($cust_bill->invnum);
3154 my $error = $cust_bill_pkg->insert;
3156 $dbh->rollback if $oldAutoCommit;
3157 return "can't create invoice line item: $error";
3161 } #foreach my $pass ( keys %cust_bill_pkg )
3163 foreach my $hook ( @precommit_hooks ) {
3165 &{$hook}; #($self) ?
3168 $dbh->rollback if $oldAutoCommit;
3169 return "$@ running precommit hook $hook\n";
3173 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3177 #discard bundled packages of 0 value
3178 sub _omit_zero_value_bundles {
3180 my @cust_bill_pkg = ();
3181 my @cust_bill_pkg_bundle = ();
3184 foreach my $cust_bill_pkg ( @_ ) {
3185 if (scalar(@cust_bill_pkg_bundle) && !$cust_bill_pkg->pkgpart_override) {
3186 push @cust_bill_pkg, @cust_bill_pkg_bundle if $sum > 0;
3187 @cust_bill_pkg_bundle = ();
3190 $sum += $cust_bill_pkg->setup + $cust_bill_pkg->recur;
3191 push @cust_bill_pkg_bundle, $cust_bill_pkg;
3193 push @cust_bill_pkg, @cust_bill_pkg_bundle if $sum > 0;
3199 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
3201 This is a weird one. Perhaps it should not even be exposed.
3203 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
3204 Usually used internally by bill method B<bill>.
3206 If there is an error, returns the error, otherwise returns reference to a
3207 list of line items suitable for insertion.
3213 An array ref of the line items being billed.
3217 A strange beast. The keys to this hash are internal identifiers consisting
3218 of the name of the tax object type, a space, and its unique identifier ( e.g.
3219 'cust_main_county 23' ). The values of the hash are listrefs. The first
3220 item in the list is the tax object. The remaining items are either line
3221 items or floating point values (currency amounts).
3223 The taxes are calculated on this entity. Calculated exemption records are
3224 transferred to the LINEITEMREF items on the assumption that they are related.
3230 This specifies the date appearing on the associated invoice. Some
3231 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
3236 sub calculate_taxes {
3237 my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
3239 my @tax_line_items = ();
3241 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
3243 # keys are tax names (as printed on invoices / itemdesc )
3244 # values are listrefs of taxlisthash keys (internal identifiers)
3247 # keys are taxlisthash keys (internal identifiers)
3248 # values are (cumulative) amounts
3251 # keys are taxlisthash keys (internal identifiers)
3252 # values are listrefs of cust_bill_pkg_tax_location hashrefs
3253 my %tax_location = ();
3255 # keys are taxlisthash keys (internal identifiers)
3256 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
3257 my %tax_rate_location = ();
3259 foreach my $tax ( keys %$taxlisthash ) {
3260 my $tax_object = shift @{ $taxlisthash->{$tax} };
3261 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
3262 warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
3263 my $hashref_or_error =
3264 $tax_object->taxline( $taxlisthash->{$tax},
3265 'custnum' => $self->custnum,
3266 'invoice_time' => $invoice_time
3268 return $hashref_or_error unless ref($hashref_or_error);
3270 unshift @{ $taxlisthash->{$tax} }, $tax_object;
3272 my $name = $hashref_or_error->{'name'};
3273 my $amount = $hashref_or_error->{'amount'};
3275 #warn "adding $amount as $name\n";
3276 $taxname{ $name } ||= [];
3277 push @{ $taxname{ $name } }, $tax;
3279 $tax{ $tax } += $amount;
3281 $tax_location{ $tax } ||= [];
3282 if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
3283 push @{ $tax_location{ $tax } },
3285 'taxnum' => $tax_object->taxnum,
3286 'taxtype' => ref($tax_object),
3287 'pkgnum' => $tax_object->get('pkgnum'),
3288 'locationnum' => $tax_object->get('locationnum'),
3289 'amount' => sprintf('%.2f', $amount ),
3293 $tax_rate_location{ $tax } ||= [];
3294 if ( ref($tax_object) eq 'FS::tax_rate' ) {
3295 my $taxratelocationnum =
3296 $tax_object->tax_rate_location->taxratelocationnum;
3297 push @{ $tax_rate_location{ $tax } },
3299 'taxnum' => $tax_object->taxnum,
3300 'taxtype' => ref($tax_object),
3301 'amount' => sprintf('%.2f', $amount ),
3302 'locationtaxid' => $tax_object->location,
3303 'taxratelocationnum' => $taxratelocationnum,
3309 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
3310 my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
3311 foreach my $tax ( keys %$taxlisthash ) {
3312 foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
3313 next unless ref($_) eq 'FS::cust_bill_pkg';
3315 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
3316 splice( @{ $_->_cust_tax_exempt_pkg } );
3320 #consolidate and create tax line items
3321 warn "consolidating and generating...\n" if $DEBUG > 2;
3322 foreach my $taxname ( keys %taxname ) {
3325 my @cust_bill_pkg_tax_location = ();
3326 my @cust_bill_pkg_tax_rate_location = ();
3327 warn "adding $taxname\n" if $DEBUG > 1;
3328 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
3329 next if $seen{$taxitem}++;
3330 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
3331 $tax += $tax{$taxitem};
3332 push @cust_bill_pkg_tax_location,
3333 map { new FS::cust_bill_pkg_tax_location $_ }
3334 @{ $tax_location{ $taxitem } };
3335 push @cust_bill_pkg_tax_rate_location,
3336 map { new FS::cust_bill_pkg_tax_rate_location $_ }
3337 @{ $tax_rate_location{ $taxitem } };
3341 $tax = sprintf('%.2f', $tax );
3343 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
3349 if ( $pkg_category and
3350 $conf->config('invoice_latexsummary') ||
3351 $conf->config('invoice_htmlsummary')
3355 my %hash = ( 'section' => $pkg_category->categoryname );
3356 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3360 push @tax_line_items, new FS::cust_bill_pkg {
3366 'itemdesc' => $taxname,
3367 'display' => \@display,
3368 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3369 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
3378 my ($self, %params) = @_;
3380 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
3381 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
3382 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
3383 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
3384 my $total_setup = $params{setup} or die "no setup accumulator specified";
3385 my $total_recur = $params{recur} or die "no recur accumulator specified";
3386 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
3387 my $time = $params{'time'} or die "no time specified";
3388 my (%options) = %{$params{options}};
3391 my $real_pkgpart = $params{real_pkgpart};
3392 my %hash = $cust_pkg->hash;
3393 my $old_cust_pkg = new FS::cust_pkg \%hash;
3399 $cust_pkg->pkgpart($part_pkg->pkgpart);
3407 if ( $options{'resetup'}
3408 || ( ! $cust_pkg->setup
3409 && ( ! $cust_pkg->start_date
3410 || $cust_pkg->start_date <= $time
3412 && ( ! $conf->exists('disable_setup_suspended_pkgs')
3413 || ( $conf->exists('disable_setup_suspended_pkgs') &&
3414 ! $cust_pkg->getfield('susp')
3421 warn " bill setup\n" if $DEBUG > 1;
3424 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
3425 return "$@ running calc_setup for $cust_pkg\n"
3428 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
3430 $cust_pkg->setfield('setup', $time)
3431 unless $cust_pkg->setup;
3432 #do need it, but it won't get written to the db
3433 #|| $cust_pkg->pkgpart != $real_pkgpart;
3435 $cust_pkg->setfield('start_date', '')
3436 if $cust_pkg->start_date;
3441 # bill recurring fee
3444 #XXX unit stuff here too
3448 if ( ! $cust_pkg->get('susp')
3449 and ! $cust_pkg->get('start_date')
3450 and ( $part_pkg->getfield('freq') ne '0'
3451 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3453 || ( $part_pkg->plan eq 'voip_cdr'
3454 && $part_pkg->option('bill_every_call')
3456 || ( $options{cancel} )
3459 # XXX should this be a package event? probably. events are called
3460 # at collection time at the moment, though...
3461 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
3462 if $part_pkg->can('reset_usage');
3463 #don't want to reset usage just cause we want a line item??
3464 #&& $part_pkg->pkgpart == $real_pkgpart;
3466 warn " bill recur\n" if $DEBUG > 1;
3469 # XXX shared with $recur_prog
3470 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
3474 #over two params! lets at least switch to a hashref for the rest...
3475 my $increment_next_bill = ( $part_pkg->freq ne '0'
3476 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3477 && !$options{cancel}
3479 my %param = ( 'precommit_hooks' => $precommit_hooks,
3480 'increment_next_bill' => $increment_next_bill,
3481 'discounts' => \@discounts,
3482 'real_pkgpart' => $real_pkgpart,
3485 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
3486 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
3487 return "$@ running $method for $cust_pkg\n"
3490 if ( $increment_next_bill ) {
3492 my $next_bill = $part_pkg->add_freq($sdate);
3493 return "unparsable frequency: ". $part_pkg->freq
3494 if $next_bill == -1;
3496 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
3497 # only for figuring next bill date, nothing else, so, reset $sdate again
3499 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
3500 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
3501 $cust_pkg->last_bill($sdate);
3503 $cust_pkg->setfield('bill', $next_bill );
3509 warn "\$setup is undefined" unless defined($setup);
3510 warn "\$recur is undefined" unless defined($recur);
3511 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
3514 # If there's line items, create em cust_bill_pkg records
3515 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
3518 if ( $lineitems || $options{has_hidden} ) {
3520 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
3521 # hmm.. and if just the options are modified in some weird price plan?
3523 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
3526 my $error = $cust_pkg->replace( $old_cust_pkg,
3527 'options' => { $cust_pkg->options },
3529 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
3530 if $error; #just in case
3533 $setup = sprintf( "%.2f", $setup );
3534 $recur = sprintf( "%.2f", $recur );
3535 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
3536 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3538 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3539 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3544 !$part_pkg->hidden && $options{has_hidden} ) #include some $0 lines
3547 warn " charges (setup=$setup, recur=$recur); adding line items\n"
3550 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3552 warn " adding customer package invoice detail: $_\n"
3553 foreach @cust_pkg_detail;
3555 push @details, @cust_pkg_detail;
3557 my $cust_bill_pkg = new FS::cust_bill_pkg {
3558 'pkgnum' => $cust_pkg->pkgnum,
3560 'unitsetup' => $unitsetup,
3562 'unitrecur' => $unitrecur,
3563 'quantity' => $cust_pkg->quantity,
3564 'details' => \@details,
3565 'discounts' => \@discounts,
3566 'hidden' => $part_pkg->hidden,
3569 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3570 $cust_bill_pkg->sdate( $hash{last_bill} );
3571 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
3572 $cust_bill_pkg->edate( $time ) if $options{cancel};
3573 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3574 $cust_bill_pkg->sdate( $sdate );
3575 $cust_bill_pkg->edate( $cust_pkg->bill );
3576 #$cust_bill_pkg->edate( $time ) if $options{cancel};
3579 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3580 unless $part_pkg->pkgpart == $real_pkgpart;
3582 $$total_setup += $setup;
3583 $$total_recur += $recur;
3590 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3591 return $error if $error;
3593 push @$cust_bill_pkgs, $cust_bill_pkg;
3595 } #if $setup != 0 || $recur != 0
3605 my $part_pkg = shift;
3606 my $taxlisthash = shift;
3607 my $cust_bill_pkg = shift;
3608 my $cust_pkg = shift;
3609 my $invoice_time = shift;
3610 my $real_pkgpart = shift;
3611 my $options = shift;
3613 my %cust_bill_pkg = ();
3617 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3618 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3619 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3620 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3622 if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3624 if ( $conf->exists('enable_taxproducts')
3625 && ( scalar($part_pkg->part_pkg_taxoverride)
3626 || $part_pkg->has_taxproduct
3631 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3632 return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3635 foreach my $class (@classes) {
3636 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3637 return $err_or_ref unless ref($err_or_ref);
3638 $taxes{$class} = $err_or_ref;
3641 unless (exists $taxes{''}) {
3642 my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3643 return $err_or_ref unless ref($err_or_ref);
3644 $taxes{''} = $err_or_ref;
3649 my @loc_keys = qw( city county state country );
3651 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3652 my $cust_location = $cust_pkg->cust_location;
3653 %taxhash = map { $_ => $cust_location->$_() } @loc_keys;
3656 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3659 %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3662 $taxhash{'taxclass'} = $part_pkg->taxclass;
3665 my %taxhash_elim = %taxhash;
3666 my @elim = qw( city county state );
3669 #first try a match with taxclass
3670 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3672 if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
3673 #then try a match without taxclass
3674 my %no_taxclass = %taxhash_elim;
3675 $no_taxclass{ 'taxclass' } = '';
3676 @taxes = qsearch( 'cust_main_county', \%no_taxclass );
3679 $taxhash_elim{ shift(@elim) } = '';
3681 } while ( !scalar(@taxes) && scalar(@elim) );
3683 @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3685 if $self->cust_main_exemption; #just to be safe
3687 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3689 $_->set('pkgnum', $cust_pkg->pkgnum );
3690 $_->set('locationnum', $cust_pkg->locationnum );
3694 $taxes{''} = [ @taxes ];
3695 $taxes{'setup'} = [ @taxes ];
3696 $taxes{'recur'} = [ @taxes ];
3697 $taxes{$_} = [ @taxes ] foreach (@classes);
3699 # # maybe eliminate this entirely, along with all the 0% records
3700 # unless ( @taxes ) {
3702 # "fatal: can't find tax rate for state/county/country/taxclass ".
3703 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
3706 } #if $conf->exists('enable_taxproducts') ...
3711 my $separate = $conf->exists('separate_usage');
3712 my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3713 my $usage_mandate = $temp_pkg->part_pkg->option('usage_mandate', 'Hush!');
3714 my $section = $temp_pkg->part_pkg->categoryname;
3715 if ( $separate || $section || $usage_mandate ) {
3717 my %hash = ( 'section' => $section );
3719 $section = $temp_pkg->part_pkg->option('usage_section', 'Hush!');
3720 my $summary = $temp_pkg->part_pkg->option('summarize_usage', 'Hush!');
3722 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3723 push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3725 push @display, new FS::cust_bill_pkg_display
3728 ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3732 if ($separate && $section && $summary) {
3733 push @display, new FS::cust_bill_pkg_display { type => 'U',
3738 if ($usage_mandate || $section && $summary) {
3739 $hash{post_total} = 'Y';
3742 if ($separate || $usage_mandate) {
3743 $hash{section} = $section if ($separate || $usage_mandate);
3744 push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3748 $cust_bill_pkg->set('display', \@display);
3750 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3751 foreach my $key (keys %tax_cust_bill_pkg) {
3752 my @taxes = @{ $taxes{$key} || [] };
3753 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3755 my %localtaxlisthash = ();
3756 foreach my $tax ( @taxes ) {
3758 my $taxname = ref( $tax ). ' '. $tax->taxnum;
3759 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3760 # ' locationnum'. $cust_pkg->locationnum
3761 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3763 $taxlisthash->{ $taxname } ||= [ $tax ];
3764 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
3766 $localtaxlisthash{ $taxname } ||= [ $tax ];
3767 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
3771 warn "finding taxed taxes...\n" if $DEBUG > 2;
3772 foreach my $tax ( keys %localtaxlisthash ) {
3773 my $tax_object = shift @{ $localtaxlisthash{$tax} };
3774 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3776 next unless $tax_object->can('tax_on_tax');
3778 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3779 my $totname = ref( $tot ). ' '. $tot->taxnum;
3781 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3783 next unless exists( $localtaxlisthash{ $totname } ); # only increase
3785 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3786 my $hashref_or_error =
3787 $tax_object->taxline( $localtaxlisthash{$tax},
3788 'custnum' => $self->custnum,
3789 'invoice_time' => $invoice_time,
3791 return $hashref_or_error
3792 unless ref($hashref_or_error);
3794 $taxlisthash->{ $totname } ||= [ $tot ];
3795 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
3807 my $part_pkg = shift;
3811 my $geocode = $self->geocode('cch');
3813 my @taxclassnums = map { $_->taxclassnum }
3814 $part_pkg->part_pkg_taxoverride($class);
3816 unless (@taxclassnums) {
3817 @taxclassnums = map { $_->taxclassnum }
3818 grep { $_->taxable eq 'Y' }
3819 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3821 warn "Found taxclassnum values of ". join(',', @taxclassnums)
3826 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3828 @taxes = qsearch({ 'table' => 'tax_rate',
3829 'hashref' => { 'geocode' => $geocode, },
3830 'extra_sql' => $extra_sql,
3832 if scalar(@taxclassnums);
3834 warn "Found taxes ".
3835 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
3842 =item collect [ HASHREF | OPTION => VALUE ... ]
3844 (Attempt to) collect money for this customer's outstanding invoices (see
3845 L<FS::cust_bill>). Usually used after the bill method.
3847 Actions are now triggered by billing events; see L<FS::part_event> and the
3848 billing events web interface. Old-style invoice events (see
3849 L<FS::part_bill_event>) have been deprecated.
3851 If there is an error, returns the error, otherwise returns false.
3853 Options are passed as name-value pairs.
3855 Currently available options are:
3861 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.
3865 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3869 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3873 set true to surpress email card/ACH decline notices.
3877 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)
3883 # allows for one time override of normal customer billing method
3888 my( $self, %options ) = @_;
3889 my $invoice_time = $options{'invoice_time'} || time;
3892 local $SIG{HUP} = 'IGNORE';
3893 local $SIG{INT} = 'IGNORE';
3894 local $SIG{QUIT} = 'IGNORE';
3895 local $SIG{TERM} = 'IGNORE';
3896 local $SIG{TSTP} = 'IGNORE';
3897 local $SIG{PIPE} = 'IGNORE';
3899 my $oldAutoCommit = $FS::UID::AutoCommit;
3900 local $FS::UID::AutoCommit = 0;
3903 $self->select_for_update; #mutex
3906 my $balance = $self->balance;
3907 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3910 if ( exists($options{'retry_card'}) ) {
3911 carp 'retry_card option passed to collect is deprecated; use retry';
3912 $options{'retry'} ||= $options{'retry_card'};
3914 if ( exists($options{'retry'}) && $options{'retry'} ) {
3915 my $error = $self->retry_realtime;
3917 $dbh->rollback if $oldAutoCommit;
3922 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3924 #never want to roll back an event just because it returned an error
3925 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3927 $self->do_cust_event(
3928 'debug' => ( $options{'debug'} || 0 ),
3929 'time' => $invoice_time,
3930 'check_freq' => $options{'check_freq'},
3931 'stage' => 'collect',
3936 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3938 Runs billing events; see L<FS::part_event> and the billing events web
3941 If there is an error, returns the error, otherwise returns false.
3943 Options are passed as name-value pairs.
3945 Currently available options are:
3951 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.
3955 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3959 "collect" (the default) or "pre-bill"
3963 set true to surpress email card/ACH decline notices.
3967 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)
3973 # allows for one time override of normal customer billing method
3977 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3980 my( $self, %options ) = @_;
3981 my $time = $options{'time'} || time;
3984 local $SIG{HUP} = 'IGNORE';
3985 local $SIG{INT} = 'IGNORE';
3986 local $SIG{QUIT} = 'IGNORE';
3987 local $SIG{TERM} = 'IGNORE';
3988 local $SIG{TSTP} = 'IGNORE';
3989 local $SIG{PIPE} = 'IGNORE';
3991 my $oldAutoCommit = $FS::UID::AutoCommit;
3992 local $FS::UID::AutoCommit = 0;
3995 $self->select_for_update; #mutex
3998 my $balance = $self->balance;
3999 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
4002 # if ( exists($options{'retry_card'}) ) {
4003 # carp 'retry_card option passed to collect is deprecated; use retry';
4004 # $options{'retry'} ||= $options{'retry_card'};
4006 # if ( exists($options{'retry'}) && $options{'retry'} ) {
4007 # my $error = $self->retry_realtime;
4009 # $dbh->rollback if $oldAutoCommit;
4014 # false laziness w/pay_batch::import_results
4016 my $due_cust_event = $self->due_cust_event(
4017 'debug' => ( $options{'debug'} || 0 ),
4019 'check_freq' => $options{'check_freq'},
4020 'stage' => ( $options{'stage'} || 'collect' ),
4022 unless( ref($due_cust_event) ) {
4023 $dbh->rollback if $oldAutoCommit;
4024 return $due_cust_event;
4027 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4028 #never want to roll back an event just because it or a different one
4030 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
4032 foreach my $cust_event ( @$due_cust_event ) {
4036 #re-eval event conditions (a previous event could have changed things)
4037 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
4038 #don't leave stray "new/locked" records around
4039 my $error = $cust_event->delete;
4040 return $error if $error;
4045 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
4046 warn " running cust_event ". $cust_event->eventnum. "\n"
4049 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
4050 if ( my $error = $cust_event->do_event() ) {
4051 #XXX wtf is this? figure out a proper dealio with return value
4063 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
4065 Inserts database records for and returns an ordered listref of new events due
4066 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
4067 events are due, an empty listref is returned. If there is an error, returns a
4068 scalar error message.
4070 To actually run the events, call each event's test_condition method, and if
4071 still true, call the event's do_event method.
4073 Options are passed as a hashref or as a list of name-value pairs. Available
4080 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.
4084 "collect" (the default) or "pre-bill"
4088 "Current time" for the events.
4092 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)
4096 Only return events for the specified eventtable (by default, events of all eventtables are returned)
4100 Explicitly pass the objects to be tested (typically used with eventtable).
4104 Set to true to return the objects, but not actually insert them into the
4111 sub due_cust_event {
4113 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
4116 #my $DEBUG = $opt{'debug'}
4117 local($DEBUG) = $opt{'debug'}
4118 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
4120 warn "$me due_cust_event called with options ".
4121 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
4124 $opt{'time'} ||= time;
4126 local $SIG{HUP} = 'IGNORE';
4127 local $SIG{INT} = 'IGNORE';
4128 local $SIG{QUIT} = 'IGNORE';
4129 local $SIG{TERM} = 'IGNORE';
4130 local $SIG{TSTP} = 'IGNORE';
4131 local $SIG{PIPE} = 'IGNORE';
4133 my $oldAutoCommit = $FS::UID::AutoCommit;
4134 local $FS::UID::AutoCommit = 0;
4137 $self->select_for_update #mutex
4138 unless $opt{testonly};
4141 # find possible events (initial search)
4144 my @cust_event = ();
4146 my @eventtable = $opt{'eventtable'}
4147 ? ( $opt{'eventtable'} )
4148 : FS::part_event->eventtables_runorder;
4150 foreach my $eventtable ( @eventtable ) {
4153 if ( $opt{'objects'} ) {
4155 @objects = @{ $opt{'objects'} };
4159 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
4160 @objects = ( $eventtable eq 'cust_main' )
4162 : ( $self->$eventtable() );
4166 my @e_cust_event = ();
4168 my $cross = "CROSS JOIN $eventtable";
4169 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
4170 unless $eventtable eq 'cust_main';
4172 foreach my $object ( @objects ) {
4174 #this first search uses the condition_sql magic for optimization.
4175 #the more possible events we can eliminate in this step the better
4177 my $cross_where = '';
4178 my $pkey = $object->primary_key;
4179 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
4181 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
4183 FS::part_event_condition->where_conditions_sql( $eventtable,
4184 'time'=>$opt{'time'}
4186 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
4188 $extra_sql = "AND $extra_sql" if $extra_sql;
4190 #here is the agent virtualization
4191 $extra_sql .= " AND ( part_event.agentnum IS NULL
4192 OR part_event.agentnum = ". $self->agentnum. ' )';
4194 $extra_sql .= " $order";
4196 warn "searching for events for $eventtable ". $object->$pkey. "\n"
4197 if $opt{'debug'} > 2;
4198 my @part_event = qsearch( {
4199 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
4200 'select' => 'part_event.*',
4201 'table' => 'part_event',
4202 'addl_from' => "$cross $join",
4203 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
4204 'eventtable' => $eventtable,
4207 'extra_sql' => "AND $cross_where $extra_sql",
4211 my $pkey = $object->primary_key;
4212 warn " ". scalar(@part_event).
4213 " possible events found for $eventtable ". $object->$pkey(). "\n";
4216 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
4220 warn " ". scalar(@e_cust_event).
4221 " subtotal possible cust events found for $eventtable\n"
4224 push @cust_event, @e_cust_event;
4228 warn " ". scalar(@cust_event).
4229 " total possible cust events found in initial search\n"
4237 $opt{stage} ||= 'collect';
4239 grep { my $stage = $_->part_event->event_stage;
4240 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
4250 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
4251 'stats_hashref' => \%unsat ),
4254 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
4257 warn " invalid conditions not eliminated with condition_sql:\n".
4258 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
4259 if keys %unsat && $DEBUG; # > 1;
4265 unless( $opt{testonly} ) {
4266 foreach my $cust_event ( @cust_event ) {
4268 my $error = $cust_event->insert();
4270 $dbh->rollback if $oldAutoCommit;
4277 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4283 warn " returning events: ". Dumper(@cust_event). "\n"
4290 =item retry_realtime
4292 Schedules realtime / batch credit card / electronic check / LEC billing
4293 events for for retry. Useful if card information has changed or manual
4294 retry is desired. The 'collect' method must be called to actually retry
4297 Implementation details: For either this customer, or for each of this
4298 customer's open invoices, changes the status of the first "done" (with
4299 statustext error) realtime processing event to "failed".
4303 sub retry_realtime {
4306 local $SIG{HUP} = 'IGNORE';
4307 local $SIG{INT} = 'IGNORE';
4308 local $SIG{QUIT} = 'IGNORE';
4309 local $SIG{TERM} = 'IGNORE';
4310 local $SIG{TSTP} = 'IGNORE';
4311 local $SIG{PIPE} = 'IGNORE';
4313 my $oldAutoCommit = $FS::UID::AutoCommit;
4314 local $FS::UID::AutoCommit = 0;
4317 #a little false laziness w/due_cust_event (not too bad, really)
4319 my $join = FS::part_event_condition->join_conditions_sql;
4320 my $order = FS::part_event_condition->order_conditions_sql;
4323 . join ( ' OR ' , map {
4324 "( part_event.eventtable = " . dbh->quote($_)
4325 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
4326 } FS::part_event->eventtables)
4329 #here is the agent virtualization
4330 my $agent_virt = " ( part_event.agentnum IS NULL
4331 OR part_event.agentnum = ". $self->agentnum. ' )';
4333 #XXX this shouldn't be hardcoded, actions should declare it...
4334 my @realtime_events = qw(
4335 cust_bill_realtime_card
4336 cust_bill_realtime_check
4337 cust_bill_realtime_lec
4341 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
4346 my @cust_event = qsearchs({
4347 'table' => 'cust_event',
4348 'select' => 'cust_event.*',
4349 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
4350 'hashref' => { 'status' => 'done' },
4351 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
4352 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
4355 my %seen_invnum = ();
4356 foreach my $cust_event (@cust_event) {
4358 #max one for the customer, one for each open invoice
4359 my $cust_X = $cust_event->cust_X;
4360 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
4364 or $cust_event->part_event->eventtable eq 'cust_bill'
4367 my $error = $cust_event->retry;
4369 $dbh->rollback if $oldAutoCommit;
4370 return "error scheduling event for retry: $error";
4375 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4383 =item realtime_collect [ OPTION => VALUE ... ]
4385 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4386 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4387 gateway. See L<http://420.am/business-onlinepayment> and
4388 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4390 On failure returns an error message.
4392 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.
4394 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4396 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
4397 then it is deduced from the customer record.
4399 If no I<amount> is specified, then the customer balance is used.
4401 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4402 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4403 if set, will override the value from the customer record.
4405 I<description> is a free-text field passed to the gateway. It defaults to
4406 the value defined by the business-onlinepayment-description configuration
4407 option, or "Internet services" if that is unset.
4409 If an I<invnum> is specified, this payment (if successful) is applied to the
4410 specified invoice. If you don't specify an I<invnum> you might want to
4411 call the B<apply_payments> method or set the I<apply> option.
4413 I<apply> can be set to true to apply a resulting payment.
4415 I<quiet> can be set true to surpress email decline notices.
4417 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4418 resulting paynum, if any.
4420 I<payunique> is a unique identifier for this payment.
4422 I<session_id> is a session identifier associated with this payment.
4424 I<depend_jobnum> allows payment capture to unlock export jobs
4428 sub realtime_collect {
4429 my( $self, %options ) = @_;
4432 warn "$me realtime_collect:\n";
4433 warn " $_ => $options{$_}\n" foreach keys %options;
4436 $options{amount} = $self->balance unless exists( $options{amount} );
4437 $options{method} = FS::payby->payby2bop($self->payby)
4438 unless exists( $options{method} );
4440 return $self->realtime_bop({%options});
4444 =item realtime_bop { [ ARG => VALUE ... ] }
4446 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4447 via a Business::OnlinePayment realtime gateway. See
4448 L<http://420.am/business-onlinepayment> for supported gateways.
4450 Required arguments in the hashref are I<method>, and I<amount>
4452 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4454 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4456 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4457 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4458 if set, will override the value from the customer record.
4460 I<description> is a free-text field passed to the gateway. It defaults to
4461 the value defined by the business-onlinepayment-description configuration
4462 option, or "Internet services" if that is unset.
4464 If an I<invnum> is specified, this payment (if successful) is applied to the
4465 specified invoice. If you don't specify an I<invnum> you might want to
4466 call the B<apply_payments> method or set the I<apply> option.
4468 I<apply> can be set to true to apply a resulting payment.
4470 I<quiet> can be set true to surpress email decline notices.
4472 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4473 resulting paynum, if any.
4475 I<payunique> is a unique identifier for this payment.
4477 I<session_id> is a session identifier associated with this payment.
4479 I<depend_jobnum> allows payment capture to unlock export jobs
4481 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4485 # some helper routines
4486 sub _bop_recurring_billing {
4487 my( $self, %opt ) = @_;
4489 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
4491 if ( defined($method) && $method eq 'transaction_is_recur' ) {
4493 return 1 if $opt{'trans_is_recur'};
4497 my %hash = ( 'custnum' => $self->custnum,
4502 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4503 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4513 sub _payment_gateway {
4514 my ($self, $options) = @_;
4516 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4517 unless exists($options->{payment_gateway});
4519 $options->{payment_gateway};
4523 my ($self, $options) = @_;
4526 'login' => $options->{payment_gateway}->gateway_username,
4527 'password' => $options->{payment_gateway}->gateway_password,
4532 my ($self, $options) = @_;
4534 $options->{payment_gateway}->gatewaynum
4535 ? $options->{payment_gateway}->options
4536 : @{ $options->{payment_gateway}->get('options') };
4541 my ($self, $options) = @_;
4543 unless ( $options->{'description'} ) {
4544 if ( $conf->exists('business-onlinepayment-description') ) {
4545 my $dtempl = $conf->config('business-onlinepayment-description');
4547 my $agent = $self->agent->agent;
4549 $options->{'description'} = eval qq("$dtempl");
4551 $options->{'description'} = 'Internet services';
4555 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4556 $options->{invnum} ||= '';
4557 $options->{payname} = $self->payname unless exists( $options->{payname} );
4561 my ($self, $options) = @_;
4564 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4565 $content{customer_ip} = $payip if length($payip);
4567 $content{invoice_number} = $options->{'invnum'}
4568 if exists($options->{'invnum'}) && length($options->{'invnum'});
4570 $content{email_customer} =
4571 ( $conf->exists('business-onlinepayment-email_customer')
4572 || $conf->exists('business-onlinepayment-email-override') );
4574 my ($payname, $payfirst, $paylast);
4575 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
4576 ($payname = $options->{payname}) =~
4577 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4578 or return "Illegal payname $payname";
4579 ($payfirst, $paylast) = ($1, $2);
4581 $payfirst = $self->getfield('first');
4582 $paylast = $self->getfield('last');
4583 $payname = "$payfirst $paylast";
4586 $content{last_name} = $paylast;
4587 $content{first_name} = $payfirst;
4589 $content{name} = $payname;
4591 $content{address} = exists($options->{'address1'})
4592 ? $options->{'address1'}
4594 my $address2 = exists($options->{'address2'})
4595 ? $options->{'address2'}
4597 $content{address} .= ", ". $address2 if length($address2);
4599 $content{city} = exists($options->{city})
4602 $content{state} = exists($options->{state})
4605 $content{zip} = exists($options->{zip})
4608 $content{country} = exists($options->{country})
4609 ? $options->{country}
4612 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4613 $content{phone} = $self->daytime || $self->night;
4618 my %bop_method2payby = (
4628 if (ref($_[0]) eq 'HASH') {
4629 %options = %{$_[0]};
4631 my ( $method, $amount ) = ( shift, shift );
4633 $options{method} = $method;
4634 $options{amount} = $amount;
4638 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
4639 warn " $_ => $options{$_}\n" foreach keys %options;
4642 return $self->fake_bop(%options) if $options{'fake'};
4644 $self->_bop_defaults(\%options);
4647 # set trans_is_recur based on invnum if there is one
4650 my $trans_is_recur = 0;
4651 if ( $options{'invnum'} ) {
4653 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
4654 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
4657 map { $_->part_pkg }
4659 map { $_->cust_pkg }
4660 $cust_bill->cust_bill_pkg;
4663 if grep { $_->freq ne '0' } @part_pkg;
4671 my $payment_gateway = $self->_payment_gateway( \%options );
4672 my $namespace = $payment_gateway->gateway_namespace;
4674 eval "use $namespace";
4678 # check for banned credit card/ACH
4681 my $ban = qsearchs('banned_pay', {
4682 'payby' => $bop_method2payby{$options{method}},
4683 'payinfo' => md5_base64($options{payinfo}),
4685 return "Banned credit card" if $ban;
4691 my $bop_content = $self->_bop_content(\%options);
4692 return $bop_content unless ref($bop_content);
4694 my @invoicing_list = $self->invoicing_list_emailonly;
4695 if ( $conf->exists('emailinvoiceautoalways')
4696 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4697 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4698 push @invoicing_list, $self->all_emails;
4701 my $email = ($conf->exists('business-onlinepayment-email-override'))
4702 ? $conf->config('business-onlinepayment-email-override')
4703 : $invoicing_list[0];
4707 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
4709 $content{card_number} = $options{payinfo};
4710 $paydate = exists($options{'paydate'})
4711 ? $options{'paydate'}
4713 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4714 $content{expiration} = "$2/$1";
4716 my $paycvv = exists($options{'paycvv'})
4717 ? $options{'paycvv'}
4719 $content{cvv2} = $paycvv
4722 my $paystart_month = exists($options{'paystart_month'})
4723 ? $options{'paystart_month'}
4724 : $self->paystart_month;
4726 my $paystart_year = exists($options{'paystart_year'})
4727 ? $options{'paystart_year'}
4728 : $self->paystart_year;
4730 $content{card_start} = "$paystart_month/$paystart_year"
4731 if $paystart_month && $paystart_year;
4733 my $payissue = exists($options{'payissue'})
4734 ? $options{'payissue'}
4736 $content{issue_number} = $payissue if $payissue;
4738 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
4739 'trans_is_recur' => $trans_is_recur,
4743 $content{recurring_billing} = 'YES';
4744 $content{acct_code} = 'rebill'
4745 if $conf->exists('credit_card-recurring_billing_acct_code');
4748 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
4749 ( $content{account_number}, $content{routing_code} ) =
4750 split('@', $options{payinfo});
4751 $content{bank_name} = $options{payname};
4752 $content{bank_state} = exists($options{'paystate'})
4753 ? $options{'paystate'}
4754 : $self->getfield('paystate');
4755 $content{account_type} = exists($options{'paytype'})
4756 ? uc($options{'paytype'}) || 'CHECKING'
4757 : uc($self->getfield('paytype')) || 'CHECKING';
4758 $content{account_name} = $self->getfield('first'). ' '.
4759 $self->getfield('last');
4761 $content{customer_org} = $self->company ? 'B' : 'I';
4762 $content{state_id} = exists($options{'stateid'})
4763 ? $options{'stateid'}
4764 : $self->getfield('stateid');
4765 $content{state_id_state} = exists($options{'stateid_state'})
4766 ? $options{'stateid_state'}
4767 : $self->getfield('stateid_state');
4768 $content{customer_ssn} = exists($options{'ss'})
4771 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
4772 $content{phone} = $options{payinfo};
4773 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4780 # run transaction(s)
4783 my $balance = exists( $options{'balance'} )
4784 ? $options{'balance'}
4787 $self->select_for_update; #mutex ... just until we get our pending record in
4789 #the checks here are intended to catch concurrent payments
4790 #double-form-submission prevention is taken care of in cust_pay_pending::check
4793 return "The customer's balance has changed; $options{method} transaction aborted."
4794 if $self->balance < $balance;
4795 #&& $self->balance < $options{amount}; #might as well anyway?
4797 #also check and make sure there aren't *other* pending payments for this cust
4799 my @pending = qsearch('cust_pay_pending', {
4800 'custnum' => $self->custnum,
4801 'status' => { op=>'!=', value=>'done' }
4803 return "A payment is already being processed for this customer (".
4804 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4805 "); $options{method} transaction aborted."
4806 if scalar(@pending);
4808 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4810 my $cust_pay_pending = new FS::cust_pay_pending {
4811 'custnum' => $self->custnum,
4812 #'invnum' => $options{'invnum'},
4813 'paid' => $options{amount},
4815 'payby' => $bop_method2payby{$options{method}},
4816 'payinfo' => $options{payinfo},
4817 'paydate' => $paydate,
4818 'recurring_billing' => $content{recurring_billing},
4819 'pkgnum' => $options{'pkgnum'},
4821 'gatewaynum' => $payment_gateway->gatewaynum || '',
4822 'session_id' => $options{session_id} || '',
4823 'jobnum' => $options{depend_jobnum} || '',
4825 $cust_pay_pending->payunique( $options{payunique} )
4826 if defined($options{payunique}) && length($options{payunique});
4827 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4828 return $cpp_new_err if $cpp_new_err;
4830 my( $action1, $action2 ) =
4831 split( /\s*\,\s*/, $payment_gateway->gateway_action );
4833 my $transaction = new $namespace( $payment_gateway->gateway_module,
4834 $self->_bop_options(\%options),
4837 $transaction->content(
4838 'type' => $options{method},
4839 $self->_bop_auth(\%options),
4840 'action' => $action1,
4841 'description' => $options{'description'},
4842 'amount' => $options{amount},
4843 #'invoice_number' => $options{'invnum'},
4844 'customer_id' => $self->custnum,
4846 'reference' => $cust_pay_pending->paypendingnum, #for now
4851 $cust_pay_pending->status('pending');
4852 my $cpp_pending_err = $cust_pay_pending->replace;
4853 return $cpp_pending_err if $cpp_pending_err;
4856 my $BOP_TESTING = 0;
4857 my $BOP_TESTING_SUCCESS = 1;
4859 unless ( $BOP_TESTING ) {
4860 $transaction->test_transaction(1)
4861 if $conf->exists('business-onlinepayment-test_transaction');
4862 $transaction->submit();
4864 if ( $BOP_TESTING_SUCCESS ) {
4865 $transaction->is_success(1);
4866 $transaction->authorization('fake auth');
4868 $transaction->is_success(0);
4869 $transaction->error_message('fake failure');
4873 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4875 return { reference => $cust_pay_pending->paypendingnum,
4876 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
4878 } elsif ( $transaction->is_success() && $action2 ) {
4880 $cust_pay_pending->status('authorized');
4881 my $cpp_authorized_err = $cust_pay_pending->replace;
4882 return $cpp_authorized_err if $cpp_authorized_err;
4884 my $auth = $transaction->authorization;
4885 my $ordernum = $transaction->can('order_number')
4886 ? $transaction->order_number
4890 new Business::OnlinePayment( $payment_gateway->gateway_module,
4891 $self->_bop_options(\%options),
4896 type => $options{method},
4898 $self->_bop_auth(\%options),
4899 order_number => $ordernum,
4900 amount => $options{amount},
4901 authorization => $auth,
4902 description => $options{'description'},
4905 foreach my $field (qw( authorization_source_code returned_ACI
4906 transaction_identifier validation_code
4907 transaction_sequence_num local_transaction_date
4908 local_transaction_time AVS_result_code )) {
4909 $capture{$field} = $transaction->$field() if $transaction->can($field);
4912 $capture->content( %capture );
4914 $capture->test_transaction(1)
4915 if $conf->exists('business-onlinepayment-test_transaction');
4918 unless ( $capture->is_success ) {
4919 my $e = "Authorization successful but capture failed, custnum #".
4920 $self->custnum. ': '. $capture->result_code.
4921 ": ". $capture->error_message;
4929 # remove paycvv after initial transaction
4932 #false laziness w/misc/process/payment.cgi - check both to make sure working
4934 if ( length($self->paycvv)
4935 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
4937 my $error = $self->remove_cvv;
4939 warn "WARNING: error removing cvv: $error\n";
4948 if ( $transaction->can('card_token') && $transaction->card_token ) {
4950 $self->card_token($transaction->card_token);
4952 if ( $options{'payinfo'} eq $self->payinfo ) {
4953 $self->payinfo($transaction->card_token);
4954 my $error = $self->replace;
4956 warn "WARNING: error storing token: $error, but proceeding anyway\n";
4966 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
4978 if (ref($_[0]) eq 'HASH') {
4979 %options = %{$_[0]};
4981 my ( $method, $amount ) = ( shift, shift );
4983 $options{method} = $method;
4984 $options{amount} = $amount;
4987 if ( $options{'fake_failure'} ) {
4988 return "Error: No error; test failure requested with fake_failure";
4992 #if ( $payment_gateway->gatewaynum ) { # agent override
4993 # $paybatch = $payment_gateway->gatewaynum. '-';
4996 #$paybatch .= "$processor:". $transaction->authorization;
4998 #$paybatch .= ':'. $transaction->order_number
4999 # if $transaction->can('order_number')
5000 # && length($transaction->order_number);
5002 my $paybatch = 'FakeProcessor:54:32';
5004 my $cust_pay = new FS::cust_pay ( {
5005 'custnum' => $self->custnum,
5006 'invnum' => $options{'invnum'},
5007 'paid' => $options{amount},
5009 'payby' => $bop_method2payby{$options{method}},
5010 #'payinfo' => $payinfo,
5011 'payinfo' => '4111111111111111',
5012 'paybatch' => $paybatch,
5013 #'paydate' => $paydate,
5014 'paydate' => '2012-05-01',
5016 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
5018 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
5021 $cust_pay->invnum(''); #try again with no specific invnum
5022 my $error2 = $cust_pay->insert( $options{'manual'} ?
5023 ( 'manual' => 1 ) : ()
5026 # gah, even with transactions.
5027 my $e = 'WARNING: Card/ACH debited but database not updated - '.
5028 "error inserting (fake!) payment: $error2".
5029 " (previously tried insert with invnum #$options{'invnum'}" .
5036 if ( $options{'paynum_ref'} ) {
5037 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5040 return ''; #no error
5045 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
5047 # Wraps up processing of a realtime credit card, ACH (electronic check) or
5048 # phone bill transaction.
5050 sub _realtime_bop_result {
5051 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
5053 warn "$me _realtime_bop_result: pending transaction ".
5054 $cust_pay_pending->paypendingnum. "\n";
5055 warn " $_ => $options{$_}\n" foreach keys %options;
5058 my $payment_gateway = $options{payment_gateway}
5059 or return "no payment gateway in arguments to _realtime_bop_result";
5061 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
5062 my $cpp_captured_err = $cust_pay_pending->replace;
5063 return $cpp_captured_err if $cpp_captured_err;
5065 if ( $transaction->is_success() ) {
5068 if ( $payment_gateway->gatewaynum ) { # agent override
5069 $paybatch = $payment_gateway->gatewaynum. '-';
5072 $paybatch .= $payment_gateway->gateway_module. ":".
5073 $transaction->authorization;
5075 $paybatch .= ':'. $transaction->order_number
5076 if $transaction->can('order_number')
5077 && length($transaction->order_number);
5079 my $cust_pay = new FS::cust_pay ( {
5080 'custnum' => $self->custnum,
5081 'invnum' => $options{'invnum'},
5082 'paid' => $cust_pay_pending->paid,
5084 'payby' => $cust_pay_pending->payby,
5085 'payinfo' => $options{'payinfo'},
5086 'paybatch' => $paybatch,
5087 'paydate' => $cust_pay_pending->paydate,
5088 'pkgnum' => $cust_pay_pending->pkgnum,
5090 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
5091 $cust_pay->payunique( $options{payunique} )
5092 if defined($options{payunique}) && length($options{payunique});
5094 my $oldAutoCommit = $FS::UID::AutoCommit;
5095 local $FS::UID::AutoCommit = 0;
5098 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
5100 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
5103 $cust_pay->invnum(''); #try again with no specific invnum
5104 my $error2 = $cust_pay->insert( $options{'manual'} ?
5105 ( 'manual' => 1 ) : ()
5108 # gah. but at least we have a record of the state we had to abort in
5109 # from cust_pay_pending now.
5110 my $e = "WARNING: $options{method} captured but payment not recorded -".
5111 " error inserting payment (". $payment_gateway->gateway_module.
5113 " (previously tried insert with invnum #$options{'invnum'}" .
5114 ": $error ) - pending payment saved as paypendingnum ".
5115 $cust_pay_pending->paypendingnum. "\n";
5121 my $jobnum = $cust_pay_pending->jobnum;
5123 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5125 unless ( $placeholder ) {
5126 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5127 my $e = "WARNING: $options{method} captured but job $jobnum not ".
5128 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
5133 $error = $placeholder->delete;
5136 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5137 my $e = "WARNING: $options{method} captured but could not delete ".
5138 "job $jobnum for paypendingnum ".
5139 $cust_pay_pending->paypendingnum. ": $error\n";
5146 if ( $options{'paynum_ref'} ) {
5147 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5150 $cust_pay_pending->status('done');
5151 $cust_pay_pending->statustext('captured');
5152 $cust_pay_pending->paynum($cust_pay->paynum);
5153 my $cpp_done_err = $cust_pay_pending->replace;
5155 if ( $cpp_done_err ) {
5157 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5158 my $e = "WARNING: $options{method} captured but payment not recorded - ".
5159 "error updating status for paypendingnum ".
5160 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5166 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5168 if ( $options{'apply'} ) {
5169 my $apply_error = $self->apply_payments_and_credits;
5170 if ( $apply_error ) {
5171 warn "WARNING: error applying payment: $apply_error\n";
5172 #but we still should return no error cause the payment otherwise went
5177 return ''; #no error
5183 my $perror = $payment_gateway->gateway_module. " error: ".
5184 $transaction->error_message;
5186 my $jobnum = $cust_pay_pending->jobnum;
5188 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5190 if ( $placeholder ) {
5191 my $error = $placeholder->depended_delete;
5192 $error ||= $placeholder->delete;
5193 warn "error removing provisioning jobs after declined paypendingnum ".
5194 $cust_pay_pending->paypendingnum. "\n";
5196 my $e = "error finding job $jobnum for declined paypendingnum ".
5197 $cust_pay_pending->paypendingnum. "\n";
5203 unless ( $transaction->error_message ) {
5206 if ( $transaction->can('response_page') ) {
5208 'page' => ( $transaction->can('response_page')
5209 ? $transaction->response_page
5212 'code' => ( $transaction->can('response_code')
5213 ? $transaction->response_code
5216 'headers' => ( $transaction->can('response_headers')
5217 ? $transaction->response_headers
5223 "No additional debugging information available for ".
5224 $payment_gateway->gateway_module;
5227 $perror .= "No error_message returned from ".
5228 $payment_gateway->gateway_module. " -- ".
5229 ( ref($t_response) ? Dumper($t_response) : $t_response );
5233 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
5234 && $conf->exists('emaildecline')
5235 && grep { $_ ne 'POST' } $self->invoicing_list
5236 && ! grep { $transaction->error_message =~ /$_/ }
5237 $conf->config('emaildecline-exclude')
5240 # Send a decline alert to the customer.
5241 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
5244 # include the raw error message in the transaction state
5245 $cust_pay_pending->setfield('error', $transaction->error_message);
5246 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
5247 $error = $msg_template->send( 'cust_main' => $self,
5248 'object' => $cust_pay_pending );
5252 my @templ = $conf->config('declinetemplate');
5253 my $template = new Text::Template (
5255 SOURCE => [ map "$_\n", @templ ],
5256 ) or return "($perror) can't create template: $Text::Template::ERROR";
5257 $template->compile()
5258 or return "($perror) can't compile template: $Text::Template::ERROR";
5262 scalar( $conf->config('company_name', $self->agentnum ) ),
5263 'company_address' =>
5264 join("\n", $conf->config('company_address', $self->agentnum ) ),
5265 'error' => $transaction->error_message,
5268 my $error = send_email(
5269 'from' => $conf->config('invoice_from', $self->agentnum ),
5270 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
5271 'subject' => 'Your payment could not be processed',
5272 'body' => [ $template->fill_in(HASH => $templ_hash) ],
5276 $perror .= " (also received error sending decline notification: $error)"
5281 $cust_pay_pending->status('done');
5282 $cust_pay_pending->statustext("declined: $perror");
5283 my $cpp_done_err = $cust_pay_pending->replace;
5284 if ( $cpp_done_err ) {
5285 my $e = "WARNING: $options{method} declined but pending payment not ".
5286 "resolved - error updating status for paypendingnum ".
5287 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5289 $perror = "$e ($perror)";
5297 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
5299 Verifies successful third party processing of a realtime credit card,
5300 ACH (electronic check) or phone bill transaction via a
5301 Business::OnlineThirdPartyPayment realtime gateway. See
5302 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
5304 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
5306 The additional options I<payname>, I<city>, I<state>,
5307 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5308 if set, will override the value from the customer record.
5310 I<description> is a free-text field passed to the gateway. It defaults to
5311 "Internet services".
5313 If an I<invnum> is specified, this payment (if successful) is applied to the
5314 specified invoice. If you don't specify an I<invnum> you might want to
5315 call the B<apply_payments> method.
5317 I<quiet> can be set true to surpress email decline notices.
5319 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
5320 resulting paynum, if any.
5322 I<payunique> is a unique identifier for this payment.
5324 Returns a hashref containing elements bill_error (which will be undefined
5325 upon success) and session_id of any associated session.
5329 sub realtime_botpp_capture {
5330 my( $self, $cust_pay_pending, %options ) = @_;
5332 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5333 warn " $_ => $options{$_}\n" foreach keys %options;
5336 eval "use Business::OnlineThirdPartyPayment";
5340 # select the gateway
5343 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5345 my $payment_gateway = $cust_pay_pending->gatewaynum
5346 ? qsearchs( 'payment_gateway',
5347 { gatewaynum => $cust_pay_pending->gatewaynum }
5349 : $self->agent->payment_gateway( 'method' => $method,
5350 # 'invnum' => $cust_pay_pending->invnum,
5351 # 'payinfo' => $cust_pay_pending->payinfo,
5354 $options{payment_gateway} = $payment_gateway; # for the helper subs
5360 my @invoicing_list = $self->invoicing_list_emailonly;
5361 if ( $conf->exists('emailinvoiceautoalways')
5362 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5363 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5364 push @invoicing_list, $self->all_emails;
5367 my $email = ($conf->exists('business-onlinepayment-email-override'))
5368 ? $conf->config('business-onlinepayment-email-override')
5369 : $invoicing_list[0];
5373 $content{email_customer} =
5374 ( $conf->exists('business-onlinepayment-email_customer')
5375 || $conf->exists('business-onlinepayment-email-override') );
5378 # run transaction(s)
5382 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5383 $self->_bop_options(\%options),
5386 $transaction->reference({ %options });
5388 $transaction->content(
5390 $self->_bop_auth(\%options),
5391 'action' => 'Post Authorization',
5392 'description' => $options{'description'},
5393 'amount' => $cust_pay_pending->paid,
5394 #'invoice_number' => $options{'invnum'},
5395 'customer_id' => $self->custnum,
5396 'referer' => 'http://cleanwhisker.420.am/',
5397 'reference' => $cust_pay_pending->paypendingnum,
5399 'phone' => $self->daytime || $self->night,
5401 # plus whatever is required for bogus capture avoidance
5404 $transaction->submit();
5407 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5410 bill_error => $error,
5411 session_id => $cust_pay_pending->session_id,
5416 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5420 sub default_payment_gateway {
5421 my( $self, $method ) = @_;
5423 die "Real-time processing not enabled\n"
5424 unless $conf->exists('business-onlinepayment');
5426 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5429 my $bop_config = 'business-onlinepayment';
5430 $bop_config .= '-ach'
5431 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5432 my ( $processor, $login, $password, $action, @bop_options ) =
5433 $conf->config($bop_config);
5434 $action ||= 'normal authorization';
5435 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5436 die "No real-time processor is enabled - ".
5437 "did you set the business-onlinepayment configuration value?\n"
5440 ( $processor, $login, $password, $action, @bop_options )
5445 Removes the I<paycvv> field from the database directly.
5447 If there is an error, returns the error, otherwise returns false.
5453 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5454 or return dbh->errstr;
5455 $sth->execute($self->custnum)
5456 or return $sth->errstr;
5461 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5463 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5464 via a Business::OnlinePayment realtime gateway. See
5465 L<http://420.am/business-onlinepayment> for supported gateways.
5467 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5469 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5471 Most gateways require a reference to an original payment transaction to refund,
5472 so you probably need to specify a I<paynum>.
5474 I<amount> defaults to the original amount of the payment if not specified.
5476 I<reason> specifies a reason for the refund.
5478 I<paydate> specifies the expiration date for a credit card overriding the
5479 value from the customer record or the payment record. Specified as yyyy-mm-dd
5481 Implementation note: If I<amount> is unspecified or equal to the amount of the
5482 orignal payment, first an attempt is made to "void" the transaction via
5483 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5484 the normal attempt is made to "refund" ("credit") the transaction via the
5485 gateway is attempted.
5487 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5488 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5489 #if set, will override the value from the customer record.
5491 #If an I<invnum> is specified, this payment (if successful) is applied to the
5492 #specified invoice. If you don't specify an I<invnum> you might want to
5493 #call the B<apply_payments> method.
5497 #some false laziness w/realtime_bop, not enough to make it worth merging
5498 #but some useful small subs should be pulled out
5499 sub realtime_refund_bop {
5503 if (ref($_[0]) eq 'HASH') {
5504 %options = %{$_[0]};
5508 $options{method} = $method;
5512 warn "$me realtime_refund_bop (new): $options{method} refund\n";
5513 warn " $_ => $options{$_}\n" foreach keys %options;
5517 # look up the original payment and optionally a gateway for that payment
5521 my $amount = $options{'amount'};
5523 my( $processor, $login, $password, @bop_options, $namespace ) ;
5524 my( $auth, $order_number ) = ( '', '', '' );
5526 if ( $options{'paynum'} ) {
5528 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
5529 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5530 or return "Unknown paynum $options{'paynum'}";
5531 $amount ||= $cust_pay->paid;
5533 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5534 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5535 $cust_pay->paybatch;
5536 my $gatewaynum = '';
5537 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5539 if ( $gatewaynum ) { #gateway for the payment to be refunded
5541 my $payment_gateway =
5542 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5543 die "payment gateway $gatewaynum not found"
5544 unless $payment_gateway;
5546 $processor = $payment_gateway->gateway_module;
5547 $login = $payment_gateway->gateway_username;
5548 $password = $payment_gateway->gateway_password;
5549 $namespace = $payment_gateway->gateway_namespace;
5550 @bop_options = $payment_gateway->options;
5552 } else { #try the default gateway
5555 my $payment_gateway =
5556 $self->agent->payment_gateway('method' => $options{method});
5558 ( $conf_processor, $login, $password, $namespace ) =
5559 map { my $method = "gateway_$_"; $payment_gateway->$method }
5560 qw( module username password namespace );
5562 @bop_options = $payment_gateway->gatewaynum
5563 ? $payment_gateway->options
5564 : @{ $payment_gateway->get('options') };
5566 return "processor of payment $options{'paynum'} $processor does not".
5567 " match default processor $conf_processor"
5568 unless $processor eq $conf_processor;
5573 } else { # didn't specify a paynum, so look for agent gateway overrides
5574 # like a normal transaction
5576 my $payment_gateway =
5577 $self->agent->payment_gateway( 'method' => $options{method},
5578 #'payinfo' => $payinfo,
5580 my( $processor, $login, $password, $namespace ) =
5581 map { my $method = "gateway_$_"; $payment_gateway->$method }
5582 qw( module username password namespace );
5584 my @bop_options = $payment_gateway->gatewaynum
5585 ? $payment_gateway->options
5586 : @{ $payment_gateway->get('options') };
5589 return "neither amount nor paynum specified" unless $amount;
5591 eval "use $namespace";
5595 'type' => $options{method},
5597 'password' => $password,
5598 'order_number' => $order_number,
5599 'amount' => $amount,
5600 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5602 $content{authorization} = $auth
5603 if length($auth); #echeck/ACH transactions have an order # but no auth
5604 #(at least with authorize.net)
5606 my $disable_void_after;
5607 if ($conf->exists('disable_void_after')
5608 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5609 $disable_void_after = $1;
5612 #first try void if applicable
5613 if ( $cust_pay && $cust_pay->paid == $amount
5615 ( not defined($disable_void_after) )
5616 || ( time < ($cust_pay->_date + $disable_void_after ) )
5619 warn " attempting void\n" if $DEBUG > 1;
5620 my $void = new Business::OnlinePayment( $processor, @bop_options );
5621 if ( $void->can('info') ) {
5622 if ( $cust_pay->payby eq 'CARD'
5623 && $void->info('CC_void_requires_card') )
5625 $content{'card_number'} = $cust_pay->payinfo;
5626 } elsif ( $cust_pay->payby eq 'CHEK'
5627 && $void->info('ECHECK_void_requires_account') )
5629 ( $content{'account_number'}, $content{'routing_code'} ) =
5630 split('@', $cust_pay->payinfo);
5631 $content{'name'} = $self->get('first'). ' '. $self->get('last');
5634 $void->content( 'action' => 'void', %content );
5635 $void->test_transaction(1)
5636 if $conf->exists('business-onlinepayment-test_transaction');
5638 if ( $void->is_success ) {
5639 my $error = $cust_pay->void($options{'reason'});
5641 # gah, even with transactions.
5642 my $e = 'WARNING: Card/ACH voided but database not updated - '.
5643 "error voiding payment: $error";
5647 warn " void successful\n" if $DEBUG > 1;
5652 warn " void unsuccessful, trying refund\n"
5656 my $address = $self->address1;
5657 $address .= ", ". $self->address2 if $self->address2;
5659 my($payname, $payfirst, $paylast);
5660 if ( $self->payname && $options{method} ne 'ECHECK' ) {
5661 $payname = $self->payname;
5662 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5663 or return "Illegal payname $payname";
5664 ($payfirst, $paylast) = ($1, $2);
5666 $payfirst = $self->getfield('first');
5667 $paylast = $self->getfield('last');
5668 $payname = "$payfirst $paylast";
5671 my @invoicing_list = $self->invoicing_list_emailonly;
5672 if ( $conf->exists('emailinvoiceautoalways')
5673 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5674 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5675 push @invoicing_list, $self->all_emails;
5678 my $email = ($conf->exists('business-onlinepayment-email-override'))
5679 ? $conf->config('business-onlinepayment-email-override')
5680 : $invoicing_list[0];
5682 my $payip = exists($options{'payip'})
5685 $content{customer_ip} = $payip
5689 if ( $options{method} eq 'CC' ) {
5692 $content{card_number} = $payinfo = $cust_pay->payinfo;
5693 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
5694 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
5695 ($content{expiration} = "$2/$1"); # where available
5697 $content{card_number} = $payinfo = $self->payinfo;
5698 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
5699 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5700 $content{expiration} = "$2/$1";
5703 } elsif ( $options{method} eq 'ECHECK' ) {
5706 $payinfo = $cust_pay->payinfo;
5708 $payinfo = $self->payinfo;
5710 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
5711 $content{bank_name} = $self->payname;
5712 $content{account_type} = 'CHECKING';
5713 $content{account_name} = $payname;
5714 $content{customer_org} = $self->company ? 'B' : 'I';
5715 $content{customer_ssn} = $self->ss;
5716 } elsif ( $options{method} eq 'LEC' ) {
5717 $content{phone} = $payinfo = $self->payinfo;
5721 my $refund = new Business::OnlinePayment( $processor, @bop_options );
5722 my %sub_content = $refund->content(
5723 'action' => 'credit',
5724 'customer_id' => $self->custnum,
5725 'last_name' => $paylast,
5726 'first_name' => $payfirst,
5728 'address' => $address,
5729 'city' => $self->city,
5730 'state' => $self->state,
5731 'zip' => $self->zip,
5732 'country' => $self->country,
5734 'phone' => $self->daytime || $self->night,
5737 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
5739 $refund->test_transaction(1)
5740 if $conf->exists('business-onlinepayment-test_transaction');
5743 return "$processor error: ". $refund->error_message
5744 unless $refund->is_success();
5746 my $paybatch = "$processor:". $refund->authorization;
5747 $paybatch .= ':'. $refund->order_number
5748 if $refund->can('order_number') && $refund->order_number;
5750 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
5751 my @cust_bill_pay = $cust_pay->cust_bill_pay;
5752 last unless @cust_bill_pay;
5753 my $cust_bill_pay = pop @cust_bill_pay;
5754 my $error = $cust_bill_pay->delete;
5758 my $cust_refund = new FS::cust_refund ( {
5759 'custnum' => $self->custnum,
5760 'paynum' => $options{'paynum'},
5761 'refund' => $amount,
5763 'payby' => $bop_method2payby{$options{method}},
5764 'payinfo' => $payinfo,
5765 'paybatch' => $paybatch,
5766 'reason' => $options{'reason'} || 'card or ACH refund',
5768 my $error = $cust_refund->insert;
5770 $cust_refund->paynum(''); #try again with no specific paynum
5771 my $error2 = $cust_refund->insert;
5773 # gah, even with transactions.
5774 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
5775 "error inserting refund ($processor): $error2".
5776 " (previously tried insert with paynum #$options{'paynum'}" .
5787 =item batch_card OPTION => VALUE...
5789 Adds a payment for this invoice to the pending credit card batch (see
5790 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
5791 runs the payment using a realtime gateway.
5796 my ($self, %options) = @_;
5799 if (exists($options{amount})) {
5800 $amount = $options{amount};
5802 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
5804 return '' unless $amount > 0;
5806 my $invnum = delete $options{invnum};
5807 my $payby = $options{invnum} || $self->payby; #dubious
5809 if ($options{'realtime'}) {
5810 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
5816 my $oldAutoCommit = $FS::UID::AutoCommit;
5817 local $FS::UID::AutoCommit = 0;
5820 #this needs to handle mysql as well as Pg, like svc_acct.pm
5821 #(make it into a common function if folks need to do batching with mysql)
5822 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
5823 or return "Cannot lock pay_batch: " . $dbh->errstr;
5827 'payby' => FS::payby->payby2payment($payby),
5830 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
5832 unless ( $pay_batch ) {
5833 $pay_batch = new FS::pay_batch \%pay_batch;
5834 my $error = $pay_batch->insert;
5836 $dbh->rollback if $oldAutoCommit;
5837 die "error creating new batch: $error\n";
5841 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
5842 'batchnum' => $pay_batch->batchnum,
5843 'custnum' => $self->custnum,
5846 foreach (qw( address1 address2 city state zip country payby payinfo paydate
5848 $options{$_} = '' unless exists($options{$_});
5851 my $cust_pay_batch = new FS::cust_pay_batch ( {
5852 'batchnum' => $pay_batch->batchnum,
5853 'invnum' => $invnum || 0, # is there a better value?
5854 # this field should be
5856 # cust_bill_pay_batch now
5857 'custnum' => $self->custnum,
5858 'last' => $self->getfield('last'),
5859 'first' => $self->getfield('first'),
5860 'address1' => $options{address1} || $self->address1,
5861 'address2' => $options{address2} || $self->address2,
5862 'city' => $options{city} || $self->city,
5863 'state' => $options{state} || $self->state,
5864 'zip' => $options{zip} || $self->zip,
5865 'country' => $options{country} || $self->country,
5866 'payby' => $options{payby} || $self->payby,
5867 'payinfo' => $options{payinfo} || $self->payinfo,
5868 'exp' => $options{paydate} || $self->paydate,
5869 'payname' => $options{payname} || $self->payname,
5870 'amount' => $amount, # consolidating
5873 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
5874 if $old_cust_pay_batch;
5877 if ($old_cust_pay_batch) {
5878 $error = $cust_pay_batch->replace($old_cust_pay_batch)
5880 $error = $cust_pay_batch->insert;
5884 $dbh->rollback if $oldAutoCommit;
5888 my $unapplied = $self->total_unapplied_credits
5889 + $self->total_unapplied_payments
5890 + $self->in_transit_payments;
5891 foreach my $cust_bill ($self->open_cust_bill) {
5892 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
5893 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
5894 'invnum' => $cust_bill->invnum,
5895 'paybatchnum' => $cust_pay_batch->paybatchnum,
5896 'amount' => $cust_bill->owed,
5899 if ($unapplied >= $cust_bill_pay_batch->amount){
5900 $unapplied -= $cust_bill_pay_batch->amount;
5903 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
5904 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
5906 $error = $cust_bill_pay_batch->insert;
5908 $dbh->rollback if $oldAutoCommit;
5913 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5917 =item apply_payments_and_credits [ OPTION => VALUE ... ]
5919 Applies unapplied payments and credits.
5921 In most cases, this new method should be used in place of sequential
5922 apply_payments and apply_credits methods.
5924 A hash of optional arguments may be passed. Currently "manual" is supported.
5925 If true, a payment receipt is sent instead of a statement when
5926 'payment_receipt_email' configuration option is set.
5928 If there is an error, returns the error, otherwise returns false.
5932 sub apply_payments_and_credits {
5933 my( $self, %options ) = @_;
5935 local $SIG{HUP} = 'IGNORE';
5936 local $SIG{INT} = 'IGNORE';
5937 local $SIG{QUIT} = 'IGNORE';
5938 local $SIG{TERM} = 'IGNORE';
5939 local $SIG{TSTP} = 'IGNORE';
5940 local $SIG{PIPE} = 'IGNORE';
5942 my $oldAutoCommit = $FS::UID::AutoCommit;
5943 local $FS::UID::AutoCommit = 0;
5946 $self->select_for_update; #mutex
5948 foreach my $cust_bill ( $self->open_cust_bill ) {
5949 my $error = $cust_bill->apply_payments_and_credits(%options);
5951 $dbh->rollback if $oldAutoCommit;
5952 return "Error applying: $error";
5956 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5961 =item apply_credits OPTION => VALUE ...
5963 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
5964 to outstanding invoice balances in chronological order (or reverse
5965 chronological order if the I<order> option is set to B<newest>) and returns the
5966 value of any remaining unapplied credits available for refund (see
5967 L<FS::cust_refund>).
5969 Dies if there is an error.
5977 local $SIG{HUP} = 'IGNORE';
5978 local $SIG{INT} = 'IGNORE';
5979 local $SIG{QUIT} = 'IGNORE';
5980 local $SIG{TERM} = 'IGNORE';
5981 local $SIG{TSTP} = 'IGNORE';
5982 local $SIG{PIPE} = 'IGNORE';
5984 my $oldAutoCommit = $FS::UID::AutoCommit;
5985 local $FS::UID::AutoCommit = 0;
5988 $self->select_for_update; #mutex
5990 unless ( $self->total_unapplied_credits ) {
5991 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5995 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
5996 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
5998 my @invoices = $self->open_cust_bill;
5999 @invoices = sort { $b->_date <=> $a->_date } @invoices
6000 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
6002 if ( $conf->exists('pkg-balances') ) {
6003 # limit @credits to those w/ a pkgnum grepped from $self
6005 foreach my $i (@invoices) {
6006 foreach my $li ( $i->cust_bill_pkg ) {
6007 $pkgnums{$li->pkgnum} = 1;
6010 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
6015 foreach my $cust_bill ( @invoices ) {
6017 if ( !defined($credit) || $credit->credited == 0) {
6018 $credit = pop @credits or last;
6022 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
6023 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
6025 $owed = $cust_bill->owed;
6027 unless ( $owed > 0 ) {
6028 push @credits, $credit;
6032 my $amount = min( $credit->credited, $owed );
6034 my $cust_credit_bill = new FS::cust_credit_bill ( {
6035 'crednum' => $credit->crednum,
6036 'invnum' => $cust_bill->invnum,
6037 'amount' => $amount,
6039 $cust_credit_bill->pkgnum( $credit->pkgnum )
6040 if $conf->exists('pkg-balances') && $credit->pkgnum;
6041 my $error = $cust_credit_bill->insert;
6043 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6047 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6051 my $total_unapplied_credits = $self->total_unapplied_credits;
6053 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6055 return $total_unapplied_credits;
6058 =item apply_payments [ OPTION => VALUE ... ]
6060 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
6061 to outstanding invoice balances in chronological order.
6063 #and returns the value of any remaining unapplied payments.
6065 A hash of optional arguments may be passed. Currently "manual" is supported.
6066 If true, a payment receipt is sent instead of a statement when
6067 'payment_receipt_email' configuration option is set.
6069 Dies if there is an error.
6073 sub apply_payments {
6074 my( $self, %options ) = @_;
6076 local $SIG{HUP} = 'IGNORE';
6077 local $SIG{INT} = 'IGNORE';
6078 local $SIG{QUIT} = 'IGNORE';
6079 local $SIG{TERM} = 'IGNORE';
6080 local $SIG{TSTP} = 'IGNORE';
6081 local $SIG{PIPE} = 'IGNORE';
6083 my $oldAutoCommit = $FS::UID::AutoCommit;
6084 local $FS::UID::AutoCommit = 0;
6087 $self->select_for_update; #mutex
6091 my @payments = sort { $b->_date <=> $a->_date }
6092 grep { $_->unapplied > 0 }
6095 my @invoices = sort { $a->_date <=> $b->_date}
6096 grep { $_->owed > 0 }
6099 if ( $conf->exists('pkg-balances') ) {
6100 # limit @payments to those w/ a pkgnum grepped from $self
6102 foreach my $i (@invoices) {
6103 foreach my $li ( $i->cust_bill_pkg ) {
6104 $pkgnums{$li->pkgnum} = 1;
6107 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
6112 foreach my $cust_bill ( @invoices ) {
6114 if ( !defined($payment) || $payment->unapplied == 0 ) {
6115 $payment = pop @payments or last;
6119 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
6120 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
6122 $owed = $cust_bill->owed;
6124 unless ( $owed > 0 ) {
6125 push @payments, $payment;
6129 my $amount = min( $payment->unapplied, $owed );
6131 my $cust_bill_pay = new FS::cust_bill_pay ( {
6132 'paynum' => $payment->paynum,
6133 'invnum' => $cust_bill->invnum,
6134 'amount' => $amount,
6136 $cust_bill_pay->pkgnum( $payment->pkgnum )
6137 if $conf->exists('pkg-balances') && $payment->pkgnum;
6138 my $error = $cust_bill_pay->insert(%options);
6140 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6144 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6148 my $total_unapplied_payments = $self->total_unapplied_payments;
6150 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6152 return $total_unapplied_payments;
6157 Returns the total owed for this customer on all invoices
6158 (see L<FS::cust_bill/owed>).
6164 $self->total_owed_date(2145859200); #12/31/2037
6167 =item total_owed_date TIME
6169 Returns the total owed for this customer on all invoices with date earlier than
6170 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6171 see L<Time::Local> and L<Date::Parse> for conversion functions.
6175 sub total_owed_date {
6179 my $custnum = $self->custnum;
6181 my $owed_sql = FS::cust_bill->owed_sql;
6184 SELECT SUM($owed_sql) FROM cust_bill
6185 WHERE custnum = $custnum
6189 sprintf( "%.2f", $self->scalar_sql($sql) );
6193 =item total_owed_pkgnum PKGNUM
6195 Returns the total owed on all invoices for this customer's specific package
6196 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
6200 sub total_owed_pkgnum {
6201 my( $self, $pkgnum ) = @_;
6202 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
6205 =item total_owed_date_pkgnum TIME PKGNUM
6207 Returns the total owed for this customer's specific package when using
6208 experimental package balances on all invoices with date earlier than
6209 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6210 see L<Time::Local> and L<Date::Parse> for conversion functions.
6214 sub total_owed_date_pkgnum {
6215 my( $self, $time, $pkgnum ) = @_;
6218 foreach my $cust_bill (
6219 grep { $_->_date <= $time }
6220 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6222 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
6224 sprintf( "%.2f", $total_bill );
6230 Returns the total amount of all payments.
6237 $total += $_->paid foreach $self->cust_pay;
6238 sprintf( "%.2f", $total );
6241 =item total_unapplied_credits
6243 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6244 customer. See L<FS::cust_credit/credited>.
6246 =item total_credited
6248 Old name for total_unapplied_credits. Don't use.
6252 sub total_credited {
6253 #carp "total_credited deprecated, use total_unapplied_credits";
6254 shift->total_unapplied_credits(@_);
6257 sub total_unapplied_credits {
6260 my $custnum = $self->custnum;
6262 my $unapplied_sql = FS::cust_credit->unapplied_sql;
6265 SELECT SUM($unapplied_sql) FROM cust_credit
6266 WHERE custnum = $custnum
6269 sprintf( "%.2f", $self->scalar_sql($sql) );
6273 =item total_unapplied_credits_pkgnum PKGNUM
6275 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6276 customer. See L<FS::cust_credit/credited>.
6280 sub total_unapplied_credits_pkgnum {
6281 my( $self, $pkgnum ) = @_;
6282 my $total_credit = 0;
6283 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
6284 sprintf( "%.2f", $total_credit );
6288 =item total_unapplied_payments
6290 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
6291 See L<FS::cust_pay/unapplied>.
6295 sub total_unapplied_payments {
6298 my $custnum = $self->custnum;
6300 my $unapplied_sql = FS::cust_pay->unapplied_sql;
6303 SELECT SUM($unapplied_sql) FROM cust_pay
6304 WHERE custnum = $custnum
6307 sprintf( "%.2f", $self->scalar_sql($sql) );
6311 =item total_unapplied_payments_pkgnum PKGNUM
6313 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
6314 specific package when using experimental package balances. See
6315 L<FS::cust_pay/unapplied>.
6319 sub total_unapplied_payments_pkgnum {
6320 my( $self, $pkgnum ) = @_;
6321 my $total_unapplied = 0;
6322 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
6323 sprintf( "%.2f", $total_unapplied );
6327 =item total_unapplied_refunds
6329 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
6330 customer. See L<FS::cust_refund/unapplied>.
6334 sub total_unapplied_refunds {
6336 my $custnum = $self->custnum;
6338 my $unapplied_sql = FS::cust_refund->unapplied_sql;
6341 SELECT SUM($unapplied_sql) FROM cust_refund
6342 WHERE custnum = $custnum
6345 sprintf( "%.2f", $self->scalar_sql($sql) );
6351 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6352 total_unapplied_credits minus total_unapplied_payments).
6358 $self->balance_date_range;
6361 =item balance_date TIME
6363 Returns the balance for this customer, only considering invoices with date
6364 earlier than TIME (total_owed_date minus total_credited minus
6365 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
6366 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
6373 $self->balance_date_range(shift);
6376 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
6378 Returns the balance for this customer, optionally considering invoices with
6379 date earlier than START_TIME, and not later than END_TIME
6380 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
6382 Times are specified as SQL fragments or numeric
6383 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
6384 L<Date::Parse> for conversion functions. The empty string can be passed
6385 to disable that time constraint completely.
6387 Available options are:
6391 =item unapplied_date
6393 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)
6399 sub balance_date_range {
6401 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
6402 ') FROM cust_main WHERE custnum='. $self->custnum;
6403 sprintf( '%.2f', $self->scalar_sql($sql) );
6406 =item balance_pkgnum PKGNUM
6408 Returns the balance for this customer's specific package when using
6409 experimental package balances (total_owed plus total_unrefunded, minus
6410 total_unapplied_credits minus total_unapplied_payments)
6414 sub balance_pkgnum {
6415 my( $self, $pkgnum ) = @_;
6418 $self->total_owed_pkgnum($pkgnum)
6419 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6420 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
6421 - $self->total_unapplied_credits_pkgnum($pkgnum)
6422 - $self->total_unapplied_payments_pkgnum($pkgnum)
6426 =item in_transit_payments
6428 Returns the total of requests for payments for this customer pending in
6429 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
6433 sub in_transit_payments {
6435 my $in_transit_payments = 0;
6436 foreach my $pay_batch ( qsearch('pay_batch', {
6439 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6440 'batchnum' => $pay_batch->batchnum,
6441 'custnum' => $self->custnum,
6443 $in_transit_payments += $cust_pay_batch->amount;
6446 sprintf( "%.2f", $in_transit_payments );
6451 Returns a hash of useful information for making a payment.
6461 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6462 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6463 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6467 For credit card transactions:
6479 For electronic check transactions:
6494 $return{balance} = $self->balance;
6496 $return{payname} = $self->payname
6497 || ( $self->first. ' '. $self->get('last') );
6499 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6501 $return{payby} = $self->payby;
6502 $return{stateid_state} = $self->stateid_state;
6504 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6505 $return{card_type} = cardtype($self->payinfo);
6506 $return{payinfo} = $self->paymask;
6508 @return{'month', 'year'} = $self->paydate_monthyear;
6512 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6513 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6514 $return{payinfo1} = $payinfo1;
6515 $return{payinfo2} = $payinfo2;
6516 $return{paytype} = $self->paytype;
6517 $return{paystate} = $self->paystate;
6521 #doubleclick protection
6523 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6529 =item paydate_monthyear
6531 Returns a two-element list consisting of the month and year of this customer's
6532 paydate (credit card expiration date for CARD customers)
6536 sub paydate_monthyear {
6538 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6540 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6547 =item tax_exemption TAXNAME
6552 my( $self, $taxname ) = @_;
6554 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6555 'taxname' => $taxname,
6560 =item cust_main_exemption
6564 sub cust_main_exemption {
6566 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6569 =item invoicing_list [ ARRAYREF ]
6571 If an arguement is given, sets these email addresses as invoice recipients
6572 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
6573 (except as warnings), so use check_invoicing_list first.
6575 Returns a list of email addresses (with svcnum entries expanded).
6577 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
6578 check it without disturbing anything by passing nothing.
6580 This interface may change in the future.
6584 sub invoicing_list {
6585 my( $self, $arrayref ) = @_;
6588 my @cust_main_invoice;
6589 if ( $self->custnum ) {
6590 @cust_main_invoice =
6591 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6593 @cust_main_invoice = ();
6595 foreach my $cust_main_invoice ( @cust_main_invoice ) {
6596 #warn $cust_main_invoice->destnum;
6597 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6598 #warn $cust_main_invoice->destnum;
6599 my $error = $cust_main_invoice->delete;
6600 warn $error if $error;
6603 if ( $self->custnum ) {
6604 @cust_main_invoice =
6605 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6607 @cust_main_invoice = ();
6609 my %seen = map { $_->address => 1 } @cust_main_invoice;
6610 foreach my $address ( @{$arrayref} ) {
6611 next if exists $seen{$address} && $seen{$address};
6612 $seen{$address} = 1;
6613 my $cust_main_invoice = new FS::cust_main_invoice ( {
6614 'custnum' => $self->custnum,
6617 my $error = $cust_main_invoice->insert;
6618 warn $error if $error;
6622 if ( $self->custnum ) {
6624 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6631 =item check_invoicing_list ARRAYREF
6633 Checks these arguements as valid input for the invoicing_list method. If there
6634 is an error, returns the error, otherwise returns false.
6638 sub check_invoicing_list {
6639 my( $self, $arrayref ) = @_;
6641 foreach my $address ( @$arrayref ) {
6643 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6644 return 'Can\'t add FAX invoice destination with a blank FAX number.';
6647 my $cust_main_invoice = new FS::cust_main_invoice ( {
6648 'custnum' => $self->custnum,
6651 my $error = $self->custnum
6652 ? $cust_main_invoice->check
6653 : $cust_main_invoice->checkdest
6655 return $error if $error;
6659 return "Email address required"
6660 if $conf->exists('cust_main-require_invoicing_list_email')
6661 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6666 =item set_default_invoicing_list
6668 Sets the invoicing list to all accounts associated with this customer,
6669 overwriting any previous invoicing list.
6673 sub set_default_invoicing_list {
6675 $self->invoicing_list($self->all_emails);
6680 Returns the email addresses of all accounts provisioned for this customer.
6687 foreach my $cust_pkg ( $self->all_pkgs ) {
6688 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6690 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6691 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6693 $list{$_}=1 foreach map { $_->email } @svc_acct;
6698 =item invoicing_list_addpost
6700 Adds postal invoicing to this customer. If this customer is already configured
6701 to receive postal invoices, does nothing.
6705 sub invoicing_list_addpost {
6707 return if grep { $_ eq 'POST' } $self->invoicing_list;
6708 my @invoicing_list = $self->invoicing_list;
6709 push @invoicing_list, 'POST';
6710 $self->invoicing_list(\@invoicing_list);
6713 =item invoicing_list_emailonly
6715 Returns the list of email invoice recipients (invoicing_list without non-email
6716 destinations such as POST and FAX).
6720 sub invoicing_list_emailonly {
6722 warn "$me invoicing_list_emailonly called"
6724 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
6727 =item invoicing_list_emailonly_scalar
6729 Returns the list of email invoice recipients (invoicing_list without non-email
6730 destinations such as POST and FAX) as a comma-separated scalar.
6734 sub invoicing_list_emailonly_scalar {
6736 warn "$me invoicing_list_emailonly_scalar called"
6738 join(', ', $self->invoicing_list_emailonly);
6741 =item referral_custnum_cust_main
6743 Returns the customer who referred this customer (or the empty string, if
6744 this customer was not referred).
6746 Note the difference with referral_cust_main method: This method,
6747 referral_custnum_cust_main returns the single customer (if any) who referred
6748 this customer, while referral_cust_main returns an array of customers referred
6753 sub referral_custnum_cust_main {
6755 return '' unless $self->referral_custnum;
6756 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6759 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
6761 Returns an array of customers referred by this customer (referral_custnum set
6762 to this custnum). If DEPTH is given, recurses up to the given depth, returning
6763 customers referred by customers referred by this customer and so on, inclusive.
6764 The default behavior is DEPTH 1 (no recursion).
6766 Note the difference with referral_custnum_cust_main method: This method,
6767 referral_cust_main, returns an array of customers referred BY this customer,
6768 while referral_custnum_cust_main returns the single customer (if any) who
6769 referred this customer.
6773 sub referral_cust_main {
6775 my $depth = @_ ? shift : 1;
6776 my $exclude = @_ ? shift : {};
6779 map { $exclude->{$_->custnum}++; $_; }
6780 grep { ! $exclude->{ $_->custnum } }
6781 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
6785 map { $_->referral_cust_main($depth-1, $exclude) }
6792 =item referral_cust_main_ncancelled
6794 Same as referral_cust_main, except only returns customers with uncancelled
6799 sub referral_cust_main_ncancelled {
6801 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
6804 =item referral_cust_pkg [ DEPTH ]
6806 Like referral_cust_main, except returns a flat list of all unsuspended (and
6807 uncancelled) packages for each customer. The number of items in this list may
6808 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
6812 sub referral_cust_pkg {
6814 my $depth = @_ ? shift : 1;
6816 map { $_->unsuspended_pkgs }
6817 grep { $_->unsuspended_pkgs }
6818 $self->referral_cust_main($depth);
6821 =item referring_cust_main
6823 Returns the single cust_main record for the customer who referred this customer
6824 (referral_custnum), or false.
6828 sub referring_cust_main {
6830 return '' unless $self->referral_custnum;
6831 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6834 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
6836 Applies a credit to this customer. If there is an error, returns the error,
6837 otherwise returns false.
6839 REASON can be a text string, an FS::reason object, or a scalar reference to
6840 a reasonnum. If a text string, it will be automatically inserted as a new
6841 reason, and a 'reason_type' option must be passed to indicate the
6842 FS::reason_type for the new reason.
6844 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
6846 Any other options are passed to FS::cust_credit::insert.
6851 my( $self, $amount, $reason, %options ) = @_;
6853 my $cust_credit = new FS::cust_credit {
6854 'custnum' => $self->custnum,
6855 'amount' => $amount,
6858 if ( ref($reason) ) {
6860 if ( ref($reason) eq 'SCALAR' ) {
6861 $cust_credit->reasonnum( $$reason );
6863 $cust_credit->reasonnum( $reason->reasonnum );
6867 $cust_credit->set('reason', $reason)
6870 for (qw( addlinfo eventnum )) {
6871 $cust_credit->$_( delete $options{$_} )
6872 if exists($options{$_});
6875 $cust_credit->insert(%options);
6879 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
6881 Creates a one-time charge for this customer. If there is an error, returns
6882 the error, otherwise returns false.
6884 New-style, with a hashref of options:
6886 my $error = $cust_main->charge(
6890 'start_date' => str2time('7/4/2009'),
6891 'pkg' => 'Description',
6892 'comment' => 'Comment',
6893 'additional' => [], #extra invoice detail
6894 'classnum' => 1, #pkg_class
6896 'setuptax' => '', # or 'Y' for tax exempt
6899 'taxclass' => 'Tax class',
6902 'taxproduct' => 2, #part_pkg_taxproduct
6903 'override' => {}, #XXX describe
6905 #will be filled in with the new object
6906 'cust_pkg_ref' => \$cust_pkg,
6908 #generate an invoice immediately
6910 'invoice_terms' => '', #with these terms
6916 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
6922 my ( $amount, $quantity, $start_date, $classnum );
6923 my ( $pkg, $comment, $additional );
6924 my ( $setuptax, $taxclass ); #internal taxes
6925 my ( $taxproduct, $override ); #vendor (CCH) taxes
6927 my $cust_pkg_ref = '';
6928 my ( $bill_now, $invoice_terms ) = ( 0, '' );
6929 if ( ref( $_[0] ) ) {
6930 $amount = $_[0]->{amount};
6931 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
6932 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
6933 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
6934 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
6935 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
6936 : '$'. sprintf("%.2f",$amount);
6937 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
6938 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
6939 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
6940 $additional = $_[0]->{additional} || [];
6941 $taxproduct = $_[0]->{taxproductnum};
6942 $override = { '' => $_[0]->{tax_override} };
6943 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
6944 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
6945 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
6950 $pkg = @_ ? shift : 'One-time charge';
6951 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
6953 $taxclass = @_ ? shift : '';
6957 local $SIG{HUP} = 'IGNORE';
6958 local $SIG{INT} = 'IGNORE';
6959 local $SIG{QUIT} = 'IGNORE';
6960 local $SIG{TERM} = 'IGNORE';
6961 local $SIG{TSTP} = 'IGNORE';
6962 local $SIG{PIPE} = 'IGNORE';
6964 my $oldAutoCommit = $FS::UID::AutoCommit;
6965 local $FS::UID::AutoCommit = 0;
6968 my $part_pkg = new FS::part_pkg ( {
6970 'comment' => $comment,
6974 'classnum' => ( $classnum ? $classnum : '' ),
6975 'setuptax' => $setuptax,
6976 'taxclass' => $taxclass,
6977 'taxproductnum' => $taxproduct,
6980 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
6981 ( 0 .. @$additional - 1 )
6983 'additional_count' => scalar(@$additional),
6984 'setup_fee' => $amount,
6987 my $error = $part_pkg->insert( options => \%options,
6988 tax_overrides => $override,
6991 $dbh->rollback if $oldAutoCommit;
6995 my $pkgpart = $part_pkg->pkgpart;
6996 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
6997 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
6998 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
6999 $error = $type_pkgs->insert;
7001 $dbh->rollback if $oldAutoCommit;
7006 my $cust_pkg = new FS::cust_pkg ( {
7007 'custnum' => $self->custnum,
7008 'pkgpart' => $pkgpart,
7009 'quantity' => $quantity,
7010 'start_date' => $start_date,
7011 'no_auto' => $no_auto,
7014 $error = $cust_pkg->insert;
7016 $dbh->rollback if $oldAutoCommit;
7018 } elsif ( $cust_pkg_ref ) {
7019 ${$cust_pkg_ref} = $cust_pkg;
7023 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
7024 'pkg_list' => [ $cust_pkg ],
7027 $dbh->rollback if $oldAutoCommit;
7032 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
7037 #=item charge_postal_fee
7039 #Applies a one time charge this customer. If there is an error,
7040 #returns the error, returns the cust_pkg charge object or false
7041 #if there was no charge.
7045 # This should be a customer event. For that to work requires that bill
7046 # also be a customer event.
7048 sub charge_postal_fee {
7051 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
7052 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
7054 my $cust_pkg = new FS::cust_pkg ( {
7055 'custnum' => $self->custnum,
7056 'pkgpart' => $pkgpart,
7060 my $error = $cust_pkg->insert;
7061 $error ? $error : $cust_pkg;
7066 Returns all the invoices (see L<FS::cust_bill>) for this customer.
7072 map { $_ } #return $self->num_cust_bill unless wantarray;
7073 sort { $a->_date <=> $b->_date }
7074 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
7077 =item open_cust_bill
7079 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
7084 sub open_cust_bill {
7088 'table' => 'cust_bill',
7089 'hashref' => { 'custnum' => $self->custnum, },
7090 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
7091 'order_by' => 'ORDER BY _date ASC',
7096 =item cust_statements
7098 Returns all the statements (see L<FS::cust_statement>) for this customer.
7102 sub cust_statement {
7104 map { $_ } #return $self->num_cust_statement unless wantarray;
7105 sort { $a->_date <=> $b->_date }
7106 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
7111 Returns all the credits (see L<FS::cust_credit>) for this customer.
7117 map { $_ } #return $self->num_cust_credit unless wantarray;
7118 sort { $a->_date <=> $b->_date }
7119 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
7122 =item cust_credit_pkgnum
7124 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
7125 package when using experimental package balances.
7129 sub cust_credit_pkgnum {
7130 my( $self, $pkgnum ) = @_;
7131 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
7132 sort { $a->_date <=> $b->_date }
7133 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
7134 'pkgnum' => $pkgnum,
7141 Returns all the payments (see L<FS::cust_pay>) for this customer.
7147 return $self->num_cust_pay unless wantarray;
7148 sort { $a->_date <=> $b->_date }
7149 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
7154 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
7155 called automatically when the cust_pay method is used in a scalar context.
7161 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
7162 my $sth = dbh->prepare($sql) or die dbh->errstr;
7163 $sth->execute($self->custnum) or die $sth->errstr;
7164 $sth->fetchrow_arrayref->[0];
7167 =item cust_pay_pkgnum
7169 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
7170 package when using experimental package balances.
7174 sub cust_pay_pkgnum {
7175 my( $self, $pkgnum ) = @_;
7176 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
7177 sort { $a->_date <=> $b->_date }
7178 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
7179 'pkgnum' => $pkgnum,
7186 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
7192 map { $_ } #return $self->num_cust_pay_void unless wantarray;
7193 sort { $a->_date <=> $b->_date }
7194 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
7197 =item cust_pay_batch
7199 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
7203 sub cust_pay_batch {
7205 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
7206 sort { $a->paybatchnum <=> $b->paybatchnum }
7207 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
7210 =item cust_pay_pending
7212 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
7213 (without status "done").
7217 sub cust_pay_pending {
7219 return $self->num_cust_pay_pending unless wantarray;
7220 sort { $a->_date <=> $b->_date }
7221 qsearch( 'cust_pay_pending', {
7222 'custnum' => $self->custnum,
7223 'status' => { op=>'!=', value=>'done' },
7228 =item cust_pay_pending_attempt
7230 Returns all payment attempts / declined payments for this customer, as pending
7231 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
7232 a corresponding payment (see L<FS::cust_pay>).
7236 sub cust_pay_pending_attempt {
7238 return $self->num_cust_pay_pending_attempt unless wantarray;
7239 sort { $a->_date <=> $b->_date }
7240 qsearch( 'cust_pay_pending', {
7241 'custnum' => $self->custnum,
7248 =item num_cust_pay_pending
7250 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7251 customer (without status "done"). Also called automatically when the
7252 cust_pay_pending method is used in a scalar context.
7256 sub num_cust_pay_pending {
7259 " SELECT COUNT(*) FROM cust_pay_pending ".
7260 " WHERE custnum = ? AND status != 'done' ",
7265 =item num_cust_pay_pending_attempt
7267 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7268 customer, with status "done" but without a corresp. Also called automatically when the
7269 cust_pay_pending method is used in a scalar context.
7273 sub num_cust_pay_pending_attempt {
7276 " SELECT COUNT(*) FROM cust_pay_pending ".
7277 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
7284 Returns all the refunds (see L<FS::cust_refund>) for this customer.
7290 map { $_ } #return $self->num_cust_refund unless wantarray;
7291 sort { $a->_date <=> $b->_date }
7292 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
7295 =item display_custnum
7297 Returns the displayed customer number for this customer: agent_custid if
7298 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
7302 sub display_custnum {
7304 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
7305 return $self->agent_custid;
7307 return $self->custnum;
7313 Returns a name string for this customer, either "Company (Last, First)" or
7320 my $name = $self->contact;
7321 $name = $self->company. " ($name)" if $self->company;
7327 Returns a name string for this (service/shipping) contact, either
7328 "Company (Last, First)" or "Last, First".
7334 if ( $self->get('ship_last') ) {
7335 my $name = $self->ship_contact;
7336 $name = $self->ship_company. " ($name)" if $self->ship_company;
7345 Returns a name string for this customer, either "Company" or "First Last".
7351 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
7354 =item ship_name_short
7356 Returns a name string for this (service/shipping) contact, either "Company"
7361 sub ship_name_short {
7363 if ( $self->get('ship_last') ) {
7364 $self->ship_company !~ /^\s*$/
7365 ? $self->ship_company
7366 : $self->ship_contact_firstlast;
7368 $self->name_company_or_firstlast;
7374 Returns this customer's full (billing) contact name only, "Last, First"
7380 $self->get('last'). ', '. $self->first;
7385 Returns this customer's full (shipping) contact name only, "Last, First"
7391 $self->get('ship_last')
7392 ? $self->get('ship_last'). ', '. $self->ship_first
7396 =item contact_firstlast
7398 Returns this customers full (billing) contact name only, "First Last".
7402 sub contact_firstlast {
7404 $self->first. ' '. $self->get('last');
7407 =item ship_contact_firstlast
7409 Returns this customer's full (shipping) contact name only, "First Last".
7413 sub ship_contact_firstlast {
7415 $self->get('ship_last')
7416 ? $self->first. ' '. $self->get('ship_last')
7417 : $self->contact_firstlast;
7422 Returns this customer's full country name
7428 code2country($self->country);
7431 =item geocode DATA_VENDOR
7433 Returns a value for the customer location as encoded by DATA_VENDOR.
7434 Currently this only makes sense for "CCH" as DATA_VENDOR.
7439 my ($self, $data_vendor) = (shift, shift); #always cch for now
7441 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
7442 return $geocode if $geocode;
7444 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7448 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7449 if $self->country eq 'US';
7453 #CCH specific location stuff
7454 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7456 my @cust_tax_location =
7458 'table' => 'cust_tax_location',
7459 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7460 'extra_sql' => $extra_sql,
7461 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
7464 $geocode = $cust_tax_location[0]->geocode
7465 if scalar(@cust_tax_location);
7474 Returns a status string for this customer, currently:
7478 =item prospect - No packages have ever been ordered
7480 =item ordered - Recurring packages all are new (not yet billed).
7482 =item active - One or more recurring packages is active
7484 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7486 =item suspended - All non-cancelled recurring packages are suspended
7488 =item cancelled - All recurring packages are cancelled
7494 sub status { shift->cust_status(@_); }
7498 # prospect ordered active inactive suspended cancelled
7499 for my $status ( FS::cust_main->statuses() ) {
7500 my $method = $status.'_sql';
7501 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7502 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7503 $sth->execute( ($self->custnum) x $numnum )
7504 or die "Error executing 'SELECT $sql': ". $sth->errstr;
7505 return $status if $sth->fetchrow_arrayref->[0];
7509 =item ucfirst_cust_status
7511 =item ucfirst_status
7513 Returns the status with the first character capitalized.
7517 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7519 sub ucfirst_cust_status {
7521 ucfirst($self->cust_status);
7526 Returns a hex triplet color string for this customer's status.
7530 use vars qw(%statuscolor);
7531 tie %statuscolor, 'Tie::IxHash',
7532 'prospect' => '7e0079', #'000000', #black? naw, purple
7533 'active' => '00CC00', #green
7534 'ordered' => '009999', #teal? cyan?
7535 'inactive' => '0000CC', #blue
7536 'suspended' => 'FF9900', #yellow
7537 'cancelled' => 'FF0000', #red
7540 sub statuscolor { shift->cust_statuscolor(@_); }
7542 sub cust_statuscolor {
7544 $statuscolor{$self->cust_status};
7549 Returns an array of hashes representing the customer's RT tickets.
7556 my $num = $conf->config('cust_main-max_tickets') || 10;
7559 if ( $conf->config('ticket_system') ) {
7560 unless ( $conf->config('ticket_system-custom_priority_field') ) {
7562 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7566 foreach my $priority (
7567 $conf->config('ticket_system-custom_priority_field-values'), ''
7569 last if scalar(@tickets) >= $num;
7571 @{ FS::TicketSystem->customer_tickets( $self->custnum,
7572 $num - scalar(@tickets),
7582 # Return services representing svc_accts in customer support packages
7583 sub support_services {
7585 my %packages = map { $_ => 1 } $conf->config('support_packages');
7587 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7588 grep { $_->part_svc->svcdb eq 'svc_acct' }
7589 map { $_->cust_svc }
7590 grep { exists $packages{ $_->pkgpart } }
7591 $self->ncancelled_pkgs;
7595 # Return a list of latitude/longitude for one of the services (if any)
7596 sub service_coordinates {
7600 grep { $_->latitude && $_->longitude }
7602 map { $_->cust_svc }
7603 $self->ncancelled_pkgs;
7605 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7610 =head1 CLASS METHODS
7616 Class method that returns the list of possible status strings for customers
7617 (see L<the status method|/status>). For example:
7619 @statuses = FS::cust_main->statuses();
7624 #my $self = shift; #could be class...
7630 Returns an SQL expression identifying prospective cust_main records (customers
7631 with no packages ever ordered)
7635 use vars qw($select_count_pkgs);
7636 $select_count_pkgs =
7637 "SELECT COUNT(*) FROM cust_pkg
7638 WHERE cust_pkg.custnum = cust_main.custnum";
7640 sub select_count_pkgs_sql {
7645 " 0 = ( $select_count_pkgs ) ";
7650 Returns an SQL expression identifying ordered cust_main records (customers with
7651 recurring packages not yet setup).
7656 FS::cust_main->none_active_sql.
7657 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
7662 Returns an SQL expression identifying active cust_main records (customers with
7663 active recurring packages).
7668 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7671 =item none_active_sql
7673 Returns an SQL expression identifying cust_main records with no active
7674 recurring packages. This includes customers of status prospect, ordered,
7675 inactive, and suspended.
7679 sub none_active_sql {
7680 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7685 Returns an SQL expression identifying inactive cust_main records (customers with
7686 no active recurring packages, but otherwise unsuspended/uncancelled).
7691 FS::cust_main->none_active_sql.
7692 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
7698 Returns an SQL expression identifying suspended cust_main records.
7703 sub suspended_sql { susp_sql(@_); }
7705 FS::cust_main->none_active_sql.
7706 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
7712 Returns an SQL expression identifying cancelled cust_main records.
7716 sub cancelled_sql { cancel_sql(@_); }
7719 my $recurring_sql = FS::cust_pkg->recurring_sql;
7720 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7723 0 < ( $select_count_pkgs )
7724 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
7725 AND 0 = ( $select_count_pkgs AND $recurring_sql
7726 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7728 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7734 =item uncancelled_sql
7736 Returns an SQL expression identifying un-cancelled cust_main records.
7740 sub uncancelled_sql { uncancel_sql(@_); }
7741 sub uncancel_sql { "
7742 ( 0 < ( $select_count_pkgs
7743 AND ( cust_pkg.cancel IS NULL
7744 OR cust_pkg.cancel = 0
7747 OR 0 = ( $select_count_pkgs )
7753 Returns an SQL fragment to retreive the balance.
7758 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7759 WHERE cust_bill.custnum = cust_main.custnum )
7760 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
7761 WHERE cust_pay.custnum = cust_main.custnum )
7762 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
7763 WHERE cust_credit.custnum = cust_main.custnum )
7764 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
7765 WHERE cust_refund.custnum = cust_main.custnum )
7768 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
7770 Returns an SQL fragment to retreive the balance for this customer, optionally
7771 considering invoices with date earlier than START_TIME, and not
7772 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7773 total_unapplied_payments).
7775 Times are specified as SQL fragments or numeric
7776 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7777 L<Date::Parse> for conversion functions. The empty string can be passed
7778 to disable that time constraint completely.
7780 Available options are:
7784 =item unapplied_date
7786 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)
7791 set to true to remove all customer comparison clauses, for totals
7796 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
7801 JOIN clause (typically used with the total option)
7805 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
7806 time will be ignored. Note that START_TIME and END_TIME only limit the date
7807 range for invoices and I<unapplied> payments, credits, and refunds.
7813 sub balance_date_sql {
7814 my( $class, $start, $end, %opt ) = @_;
7816 my $cutoff = $opt{'cutoff'};
7818 my $owed = FS::cust_bill->owed_sql($cutoff);
7819 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
7820 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
7821 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7823 my $j = $opt{'join'} || '';
7825 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
7826 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
7827 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
7828 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
7830 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
7831 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
7832 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
7833 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
7838 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
7840 Returns an SQL fragment to retreive the total unapplied payments for this
7841 customer, only considering invoices with date earlier than START_TIME, and
7842 optionally not later than END_TIME.
7844 Times are specified as SQL fragments or numeric
7845 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7846 L<Date::Parse> for conversion functions. The empty string can be passed
7847 to disable that time constraint completely.
7849 Available options are:
7853 sub unapplied_payments_date_sql {
7854 my( $class, $start, $end, %opt ) = @_;
7856 my $cutoff = $opt{'cutoff'};
7858 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7860 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
7861 'unapplied_date'=>1 );
7863 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
7866 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7868 Helper method for balance_date_sql; name (and usage) subject to change
7869 (suggestions welcome).
7871 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
7872 cust_refund, cust_credit or cust_pay).
7874 If TABLE is "cust_bill" or the unapplied_date option is true, only
7875 considers records with date earlier than START_TIME, and optionally not
7876 later than END_TIME .
7880 sub _money_table_where {
7881 my( $class, $table, $start, $end, %opt ) = @_;
7884 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
7885 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
7886 push @where, "$table._date <= $start" if defined($start) && length($start);
7887 push @where, "$table._date > $end" if defined($end) && length($end);
7889 push @where, @{$opt{'where'}} if $opt{'where'};
7890 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
7896 =item search HASHREF
7900 Returns a qsearch hash expression to search for parameters specified in
7901 HASHREF. Valid parameters are
7909 =item cancelled_pkgs
7915 listref of start date, end date
7925 =item current_balance
7927 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
7931 =item flattened_pkgs
7940 my ($class, $params) = @_;
7951 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
7953 "cust_main.agentnum = $1";
7957 # do the same for user
7960 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
7962 "cust_main.usernum = $1";
7969 #prospect ordered active inactive suspended cancelled
7970 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
7971 my $method = $params->{'status'}. '_sql';
7972 #push @where, $class->$method();
7973 push @where, FS::cust_main->$method();
7977 # parse cancelled package checkbox
7982 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
7983 unless $params->{'cancelled_pkgs'};
7986 # parse without census tract checkbox
7989 push @where, "(censustract = '' or censustract is null)"
7990 if $params->{'no_censustract'};
7996 foreach my $field (qw( signupdate )) {
7998 next unless exists($params->{$field});
8000 my($beginning, $ending, $hour) = @{$params->{$field}};
8003 "cust_main.$field IS NOT NULL",
8004 "cust_main.$field >= $beginning",
8005 "cust_main.$field <= $ending";
8007 # XXX: do this for mysql and/or pull it out of here
8009 if ($dbh->{Driver}->{Name} eq 'Pg') {
8010 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
8013 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
8017 $orderby ||= "ORDER BY cust_main.$field";
8025 if ( $params->{'classnum'} ) {
8027 my @classnum = ref( $params->{'classnum'} )
8028 ? @{ $params->{'classnum'} }
8029 : ( $params->{'classnum'} );
8031 @classnum = grep /^(\d*)$/, @classnum;
8034 push @where, '( '. join(' OR ', map {
8035 $_ ? "cust_main.classnum = $_"
8036 : "cust_main.classnum IS NULL"
8049 if ( $params->{'payby'} ) {
8051 my @payby = ref( $params->{'payby'} )
8052 ? @{ $params->{'payby'} }
8053 : ( $params->{'payby'} );
8055 @payby = grep /^([A-Z]{4})$/, @payby;
8057 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
8063 # paydate_year / paydate_month
8066 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
8068 $params->{'paydate_month'} =~ /^(\d\d?)$/
8069 or die "paydate_year without paydate_month?";
8073 'paydate IS NOT NULL',
8075 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
8083 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
8085 if ( $1 eq 'NULL' ) {
8087 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
8090 "cust_main.invoice_terms IS NOT NULL",
8091 "cust_main.invoice_terms = '$1'";
8099 if ( $params->{'current_balance'} ) {
8101 #my $balance_sql = $class->balance_sql();
8102 my $balance_sql = FS::cust_main->balance_sql();
8104 my @current_balance =
8105 ref( $params->{'current_balance'} )
8106 ? @{ $params->{'current_balance'} }
8107 : ( $params->{'current_balance'} );
8109 push @where, map { s/current_balance/$balance_sql/; $_ }
8118 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
8120 "cust_main.custbatch = '$1'";
8124 # setup queries, subs, etc. for the search
8127 $orderby ||= 'ORDER BY custnum';
8129 # here is the agent virtualization
8130 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
8132 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
8134 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
8136 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
8138 my $select = join(', ',
8139 'cust_main.custnum',
8140 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
8143 my(@extra_headers) = ();
8144 my(@extra_fields) = ();
8146 if ($params->{'flattened_pkgs'}) {
8148 if ($dbh->{Driver}->{Name} eq 'Pg') {
8150 $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";
8152 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
8153 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
8154 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
8156 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
8157 "omitting packing information from report.";
8160 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";
8162 my $sth = dbh->prepare($header_query) or die dbh->errstr;
8163 $sth->execute() or die $sth->errstr;
8164 my $headerrow = $sth->fetchrow_arrayref;
8165 my $headercount = $headerrow ? $headerrow->[0] : 0;
8166 while($headercount) {
8167 unshift @extra_headers, "Package ". $headercount;
8168 unshift @extra_fields, eval q!sub {my $c = shift;
8169 my @a = split '\|', $c->magic;
8170 my $p = $a[!.--$headercount. q!];
8178 'table' => 'cust_main',
8179 'select' => $select,
8181 'extra_sql' => $extra_sql,
8182 'order_by' => $orderby,
8183 'count_query' => $count_query,
8184 'extra_headers' => \@extra_headers,
8185 'extra_fields' => \@extra_fields,
8190 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
8192 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
8193 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
8194 specified (the appropriate ship_ field is also searched).
8196 Additional options are the same as FS::Record::qsearch
8201 my( $self, $fuzzy, $hash, @opt) = @_;
8206 check_and_rebuild_fuzzyfiles();
8207 foreach my $field ( keys %$fuzzy ) {
8209 my $all = $self->all_X($field);
8210 next unless scalar(@$all);
8213 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
8216 foreach ( keys %match ) {
8217 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
8218 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
8221 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
8224 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
8226 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
8234 Returns a masked version of the named field
8239 my ($self,$field) = @_;
8243 'x'x(length($self->getfield($field))-4).
8244 substr($self->getfield($field), (length($self->getfield($field))-4));
8254 =item smart_search OPTION => VALUE ...
8256 Accepts the following options: I<search>, the string to search for. The string
8257 will be searched for as a customer number, phone number, name or company name,
8258 as an exact, or, in some cases, a substring or fuzzy match (see the source code
8259 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
8260 skip fuzzy matching when an exact match is found.
8262 Any additional options are treated as an additional qualifier on the search
8265 Returns a (possibly empty) array of FS::cust_main objects.
8272 #here is the agent virtualization
8273 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8277 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
8278 my $search = delete $options{'search'};
8279 ( my $alphanum_search = $search ) =~ s/\W//g;
8281 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8283 #false laziness w/Record::ut_phone
8284 my $phonen = "$1-$2-$3";
8285 $phonen .= " x$4" if $4;
8287 push @cust_main, qsearch( {
8288 'table' => 'cust_main',
8289 'hashref' => { %options },
8290 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8292 join(' OR ', map "$_ = '$phonen'",
8293 qw( daytime night fax
8294 ship_daytime ship_night ship_fax )
8297 " AND $agentnums_sql", #agent virtualization
8300 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8301 #try looking for matches with extensions unless one was specified
8303 push @cust_main, qsearch( {
8304 'table' => 'cust_main',
8305 'hashref' => { %options },
8306 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8308 join(' OR ', map "$_ LIKE '$phonen\%'",
8310 ship_daytime ship_night )
8313 " AND $agentnums_sql", #agent virtualization
8318 # custnum search (also try agent_custid), with some tweaking options if your
8319 # legacy cust "numbers" have letters
8322 if ( $search =~ /^\s*(\d+)\s*$/
8323 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8324 && $search =~ /^\s*(\w\w?\d+)\s*$/
8326 || ( $conf->exists('address1-search' )
8327 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
8334 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
8335 push @cust_main, qsearch( {
8336 'table' => 'cust_main',
8337 'hashref' => { 'custnum' => $num, %options },
8338 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8342 push @cust_main, qsearch( {
8343 'table' => 'cust_main',
8344 'hashref' => { 'agent_custid' => $num, %options },
8345 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8348 if ( $conf->exists('address1-search') ) {
8349 my $len = length($num);
8351 foreach my $prefix ( '', 'ship_' ) {
8352 push @cust_main, qsearch( {
8353 'table' => 'cust_main',
8354 'hashref' => { %options, },
8356 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8357 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
8358 " AND $agentnums_sql",
8363 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8365 my($company, $last, $first) = ( $1, $2, $3 );
8367 # "Company (Last, First)"
8368 #this is probably something a browser remembered,
8369 #so just do an exact search (but case-insensitive, so USPS standardization
8370 #doesn't throw a wrench in the works)
8372 foreach my $prefix ( '', 'ship_' ) {
8373 push @cust_main, qsearch( {
8374 'table' => 'cust_main',
8375 'hashref' => { %options },
8377 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8379 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
8380 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
8381 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
8387 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8388 # try (ship_){last,company}
8392 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8393 # # full strings the browser remembers won't work
8394 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8396 use Lingua::EN::NameParse;
8397 my $NameParse = new Lingua::EN::NameParse(
8399 allow_reversed => 1,
8402 my($last, $first) = ( '', '' );
8403 #maybe disable this too and just rely on NameParse?
8404 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8406 ($last, $first) = ( $1, $2 );
8408 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
8409 } elsif ( ! $NameParse->parse($value) ) {
8411 my %name = $NameParse->components;
8412 $first = $name{'given_name_1'};
8413 $last = $name{'surname_1'};
8417 if ( $first && $last ) {
8419 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8422 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8424 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8425 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8428 push @cust_main, qsearch( {
8429 'table' => 'cust_main',
8430 'hashref' => \%options,
8431 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8434 # or it just be something that was typed in... (try that in a sec)
8438 my $q_value = dbh->quote($value);
8441 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8442 $sql .= " ( LOWER(last) = $q_value
8443 OR LOWER(company) = $q_value
8444 OR LOWER(ship_last) = $q_value
8445 OR LOWER(ship_company) = $q_value
8447 $sql .= " OR LOWER(address1) = $q_value
8448 OR LOWER(ship_address1) = $q_value
8450 if $conf->exists('address1-search');
8453 push @cust_main, qsearch( {
8454 'table' => 'cust_main',
8455 'hashref' => \%options,
8456 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8459 #no exact match, trying substring/fuzzy
8460 #always do substring & fuzzy (unless they're explicity config'ed off)
8461 #getting complaints searches are not returning enough
8462 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8464 #still some false laziness w/search (was search/cust_main.cgi)
8469 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
8470 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8473 if ( $first && $last ) {
8476 { 'first' => { op=>'ILIKE', value=>"%$first%" },
8477 'last' => { op=>'ILIKE', value=>"%$last%" },
8479 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
8480 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
8487 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
8488 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
8492 if ( $conf->exists('address1-search') ) {
8494 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
8495 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
8499 foreach my $hashref ( @hashrefs ) {
8501 push @cust_main, qsearch( {
8502 'table' => 'cust_main',
8503 'hashref' => { %$hashref,
8506 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8515 " AND $agentnums_sql", #extra_sql #agent virtualization
8518 if ( $first && $last ) {
8519 push @cust_main, FS::cust_main->fuzzy_search(
8520 { 'last' => $last, #fuzzy hashref
8521 'first' => $first }, #
8525 foreach my $field ( 'last', 'company' ) {
8527 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8529 if ( $conf->exists('address1-search') ) {
8531 FS::cust_main->fuzzy_search( { 'address1' => $value }, @fuzopts );
8538 #eliminate duplicates
8540 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8548 Accepts the following options: I<email>, the email address to search for. The
8549 email address will be searched for as an email invoice destination and as an
8552 #Any additional options are treated as an additional qualifier on the search
8553 #(i.e. I<agentnum>).
8555 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8565 my $email = delete $options{'email'};
8567 #we're only being used by RT at the moment... no agent virtualization yet
8568 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8572 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8574 my ( $user, $domain ) = ( $1, $2 );
8576 warn "$me smart_search: searching for $user in domain $domain"
8582 'table' => 'cust_main_invoice',
8583 'hashref' => { 'dest' => $email },
8590 map $_->cust_svc->cust_pkg,
8592 'table' => 'svc_acct',
8593 'hashref' => { 'username' => $user, },
8595 'AND ( SELECT domain FROM svc_domain
8596 WHERE svc_acct.domsvc = svc_domain.svcnum
8597 ) = '. dbh->quote($domain),
8603 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8605 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8612 =item check_and_rebuild_fuzzyfiles
8616 sub check_and_rebuild_fuzzyfiles {
8617 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8618 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8621 =item rebuild_fuzzyfiles
8625 sub rebuild_fuzzyfiles {
8627 use Fcntl qw(:flock);
8629 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8630 mkdir $dir, 0700 unless -d $dir;
8632 foreach my $fuzzy ( @fuzzyfields ) {
8634 open(LOCK,">>$dir/cust_main.$fuzzy")
8635 or die "can't open $dir/cust_main.$fuzzy: $!";
8637 or die "can't lock $dir/cust_main.$fuzzy: $!";
8639 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8640 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8642 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8643 my $sth = dbh->prepare("SELECT $field FROM cust_main".
8644 " WHERE $field != '' AND $field IS NOT NULL");
8645 $sth->execute or die $sth->errstr;
8647 while ( my $row = $sth->fetchrow_arrayref ) {
8648 print CACHE $row->[0]. "\n";
8653 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8655 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8666 my( $self, $field ) = @_;
8667 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8668 open(CACHE,"<$dir/cust_main.$field")
8669 or die "can't open $dir/cust_main.$field: $!";
8670 my @array = map { chomp; $_; } <CACHE>;
8675 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
8679 sub append_fuzzyfiles {
8680 #my( $first, $last, $company ) = @_;
8682 &check_and_rebuild_fuzzyfiles;
8684 use Fcntl qw(:flock);
8686 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8688 foreach my $field (@fuzzyfields) {
8693 open(CACHE,">>$dir/cust_main.$field")
8694 or die "can't open $dir/cust_main.$field: $!";
8695 flock(CACHE,LOCK_EX)
8696 or die "can't lock $dir/cust_main.$field: $!";
8698 print CACHE "$value\n";
8700 flock(CACHE,LOCK_UN)
8701 or die "can't unlock $dir/cust_main.$field: $!";
8716 #warn join('-',keys %$param);
8717 my $fh = $param->{filehandle};
8718 my $agentnum = $param->{agentnum};
8719 my $format = $param->{format};
8721 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
8724 if ( $format eq 'simple' ) {
8725 @fields = qw( custnum agent_custid amount pkg );
8727 die "unknown format $format";
8730 eval "use Text::CSV_XS;";
8733 my $csv = new Text::CSV_XS;
8740 local $SIG{HUP} = 'IGNORE';
8741 local $SIG{INT} = 'IGNORE';
8742 local $SIG{QUIT} = 'IGNORE';
8743 local $SIG{TERM} = 'IGNORE';
8744 local $SIG{TSTP} = 'IGNORE';
8745 local $SIG{PIPE} = 'IGNORE';
8747 my $oldAutoCommit = $FS::UID::AutoCommit;
8748 local $FS::UID::AutoCommit = 0;
8751 #while ( $columns = $csv->getline($fh) ) {
8753 while ( defined($line=<$fh>) ) {
8755 $csv->parse($line) or do {
8756 $dbh->rollback if $oldAutoCommit;
8757 return "can't parse: ". $csv->error_input();
8760 my @columns = $csv->fields();
8761 #warn join('-',@columns);
8764 foreach my $field ( @fields ) {
8765 $row{$field} = shift @columns;
8768 if ( $row{custnum} && $row{agent_custid} ) {
8769 dbh->rollback if $oldAutoCommit;
8770 return "can't specify custnum with agent_custid $row{agent_custid}";
8774 if ( $row{agent_custid} && $agentnum ) {
8775 %hash = ( 'agent_custid' => $row{agent_custid},
8776 'agentnum' => $agentnum,
8780 if ( $row{custnum} ) {
8781 %hash = ( 'custnum' => $row{custnum} );
8784 unless ( scalar(keys %hash) ) {
8785 $dbh->rollback if $oldAutoCommit;
8786 return "can't find customer without custnum or agent_custid and agentnum";
8789 my $cust_main = qsearchs('cust_main', { %hash } );
8790 unless ( $cust_main ) {
8791 $dbh->rollback if $oldAutoCommit;
8792 my $custnum = $row{custnum} || $row{agent_custid};
8793 return "unknown custnum $custnum";
8796 if ( $row{'amount'} > 0 ) {
8797 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8799 $dbh->rollback if $oldAutoCommit;
8803 } elsif ( $row{'amount'} < 0 ) {
8804 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8807 $dbh->rollback if $oldAutoCommit;
8817 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8819 return "Empty file!" unless $imported;
8825 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8827 Deprecated. Use event notification and message templates
8828 (L<FS::msg_template>) instead.
8830 Sends a templated email notification to the customer (see L<Text::Template>).
8832 OPTIONS is a hash and may include
8834 I<from> - the email sender (default is invoice_from)
8836 I<to> - comma-separated scalar or arrayref of recipients
8837 (default is invoicing_list)
8839 I<subject> - The subject line of the sent email notification
8840 (default is "Notice from company_name")
8842 I<extra_fields> - a hashref of name/value pairs which will be substituted
8845 The following variables are vavailable in the template.
8847 I<$first> - the customer first name
8848 I<$last> - the customer last name
8849 I<$company> - the customer company
8850 I<$payby> - a description of the method of payment for the customer
8851 # would be nice to use FS::payby::shortname
8852 I<$payinfo> - the account information used to collect for this customer
8853 I<$expdate> - the expiration of the customer payment in seconds from epoch
8858 my ($self, $template, %options) = @_;
8860 return unless $conf->exists($template);
8862 my $from = $conf->config('invoice_from', $self->agentnum)
8863 if $conf->exists('invoice_from', $self->agentnum);
8864 $from = $options{from} if exists($options{from});
8866 my $to = join(',', $self->invoicing_list_emailonly);
8867 $to = $options{to} if exists($options{to});
8869 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
8870 if $conf->exists('company_name', $self->agentnum);
8871 $subject = $options{subject} if exists($options{subject});
8873 my $notify_template = new Text::Template (TYPE => 'ARRAY',
8874 SOURCE => [ map "$_\n",
8875 $conf->config($template)]
8877 or die "can't create new Text::Template object: Text::Template::ERROR";
8878 $notify_template->compile()
8879 or die "can't compile template: Text::Template::ERROR";
8881 $FS::notify_template::_template::company_name =
8882 $conf->config('company_name', $self->agentnum);
8883 $FS::notify_template::_template::company_address =
8884 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
8886 my $paydate = $self->paydate || '2037-12-31';
8887 $FS::notify_template::_template::first = $self->first;
8888 $FS::notify_template::_template::last = $self->last;
8889 $FS::notify_template::_template::company = $self->company;
8890 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
8891 my $payby = $self->payby;
8892 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8893 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8895 #credit cards expire at the end of the month/year of their exp date
8896 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8897 $FS::notify_template::_template::payby = 'credit card';
8898 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8899 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8901 }elsif ($payby eq 'COMP') {
8902 $FS::notify_template::_template::payby = 'complimentary account';
8904 $FS::notify_template::_template::payby = 'current method';
8906 $FS::notify_template::_template::expdate = $expire_time;
8908 for (keys %{$options{extra_fields}}){
8910 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
8913 send_email(from => $from,
8915 subject => $subject,
8916 body => $notify_template->fill_in( PACKAGE =>
8917 'FS::notify_template::_template' ),
8922 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8924 Generates a templated notification to the customer (see L<Text::Template>).
8926 OPTIONS is a hash and may include
8928 I<extra_fields> - a hashref of name/value pairs which will be substituted
8929 into the template. These values may override values mentioned below
8930 and those from the customer record.
8932 The following variables are available in the template instead of or in addition
8933 to the fields of the customer record.
8935 I<$payby> - a description of the method of payment for the customer
8936 # would be nice to use FS::payby::shortname
8937 I<$payinfo> - the masked account information used to collect for this customer
8938 I<$expdate> - the expiration of the customer payment method in seconds from epoch
8939 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
8943 # a lot like cust_bill::print_latex
8944 sub generate_letter {
8945 my ($self, $template, %options) = @_;
8947 return unless $conf->exists($template);
8949 my $letter_template = new Text::Template
8951 SOURCE => [ map "$_\n", $conf->config($template)],
8952 DELIMITERS => [ '[@--', '--@]' ],
8954 or die "can't create new Text::Template object: Text::Template::ERROR";
8956 $letter_template->compile()
8957 or die "can't compile template: Text::Template::ERROR";
8959 my %letter_data = map { $_ => $self->$_ } $self->fields;
8960 $letter_data{payinfo} = $self->mask_payinfo;
8962 #my $paydate = $self->paydate || '2037-12-31';
8963 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
8965 my $payby = $self->payby;
8966 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8967 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8969 #credit cards expire at the end of the month/year of their exp date
8970 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8971 $letter_data{payby} = 'credit card';
8972 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8973 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8975 }elsif ($payby eq 'COMP') {
8976 $letter_data{payby} = 'complimentary account';
8978 $letter_data{payby} = 'current method';
8980 $letter_data{expdate} = $expire_time;
8982 for (keys %{$options{extra_fields}}){
8983 $letter_data{$_} = $options{extra_fields}->{$_};
8986 unless(exists($letter_data{returnaddress})){
8987 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
8988 $self->agent_template)
8990 if ( length($retadd) ) {
8991 $letter_data{returnaddress} = $retadd;
8992 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
8993 $letter_data{returnaddress} =
8994 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
8998 ( $conf->config('company_name', $self->agentnum),
8999 $conf->config('company_address', $self->agentnum),
9003 $letter_data{returnaddress} = '~';
9007 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
9009 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
9011 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
9013 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
9017 ) or die "can't open temp file: $!\n";
9018 print $lh $conf->config_binary('logo.eps', $self->agentnum)
9019 or die "can't write temp file: $!\n";
9021 $letter_data{'logo_file'} = $lh->filename;
9023 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
9027 ) or die "can't open temp file: $!\n";
9029 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
9031 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
9032 return ($1, $letter_data{'logo_file'});
9036 =item print_ps TEMPLATE
9038 Returns an postscript letter filled in from TEMPLATE, as a scalar.
9044 my($file, $lfile) = $self->generate_letter(@_);
9045 my $ps = FS::Misc::generate_ps($file);
9046 unlink($file.'.tex');
9052 =item print TEMPLATE
9054 Prints the filled in template.
9056 TEMPLATE is the name of a L<Text::Template> to fill in and print.
9060 sub queueable_print {
9063 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
9064 or die "invalid customer number: " . $opt{custvnum};
9066 my $error = $self->print( $opt{template} );
9067 die $error if $error;
9071 my ($self, $template) = (shift, shift);
9072 do_print [ $self->print_ps($template) ];
9075 #these three subs should just go away once agent stuff is all config overrides
9077 sub agent_template {
9079 $self->_agent_plandata('agent_templatename');
9082 sub agent_invoice_from {
9084 $self->_agent_plandata('agent_invoice_from');
9087 sub _agent_plandata {
9088 my( $self, $option ) = @_;
9090 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
9091 #agent-specific Conf
9093 use FS::part_event::Condition;
9095 my $agentnum = $self->agentnum;
9097 my $regexp = regexp_sql();
9099 my $part_event_option =
9101 'select' => 'part_event_option.*',
9102 'table' => 'part_event_option',
9104 LEFT JOIN part_event USING ( eventpart )
9105 LEFT JOIN part_event_option AS peo_agentnum
9106 ON ( part_event.eventpart = peo_agentnum.eventpart
9107 AND peo_agentnum.optionname = 'agentnum'
9108 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
9110 LEFT JOIN part_event_condition
9111 ON ( part_event.eventpart = part_event_condition.eventpart
9112 AND part_event_condition.conditionname = 'cust_bill_age'
9114 LEFT JOIN part_event_condition_option
9115 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
9116 AND part_event_condition_option.optionname = 'age'
9119 #'hashref' => { 'optionname' => $option },
9120 #'hashref' => { 'part_event_option.optionname' => $option },
9122 " WHERE part_event_option.optionname = ". dbh->quote($option).
9123 " AND action = 'cust_bill_send_agent' ".
9124 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
9125 " AND peo_agentnum.optionname = 'agentnum' ".
9126 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
9128 CASE WHEN part_event_condition_option.optionname IS NULL
9130 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
9132 , part_event.weight".
9136 unless ( $part_event_option ) {
9137 return $self->agent->invoice_template || ''
9138 if $option eq 'agent_templatename';
9142 $part_event_option->optionvalue;
9146 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
9148 Subroutine (not a method), designed to be called from the queue.
9150 Takes a list of options and values.
9152 Pulls up the customer record via the custnum option and calls bill_and_collect.
9157 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
9159 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
9160 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
9162 $cust_main->bill_and_collect( %args );
9165 sub process_bill_and_collect {
9167 my $param = thaw(decode_base64(shift));
9168 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
9169 or die "custnum '$param->{custnum}' not found!\n";
9170 $param->{'job'} = $job;
9171 $param->{'fatal'} = 1; # runs from job queue, will be caught
9172 $param->{'retry'} = 1;
9174 $cust_main->bill_and_collect( %$param );
9177 sub _upgrade_data { #class method
9178 my ($class, %opts) = @_;
9180 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
9181 my $sth = dbh->prepare($sql) or die dbh->errstr;
9182 $sth->execute or die $sth->errstr;
9184 local($ignore_expired_card) = 1;
9185 local($skip_fuzzyfiles) = 1;
9186 $class->_upgrade_otaker(%opts);
9196 The delete method should possibly take an FS::cust_main object reference
9197 instead of a scalar customer number.
9199 Bill and collect options should probably be passed as references instead of a
9202 There should probably be a configuration file with a list of allowed credit
9205 No multiple currency support (probably a larger project than just this module).
9207 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
9209 Birthdates rely on negative epoch values.
9211 The payby for card/check batches is broken. With mixed batching, bad
9214 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
9218 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
9219 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
9220 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.