5 use base qw( FS::otaker_Mixin FS::payinfo_Mixin FS::Record );
6 use vars qw( @EXPORT_OK $DEBUG $me $conf
8 $import $ignore_expired_card
9 $skip_fuzzyfiles @fuzzyfields
12 use vars qw( $realtime_bop_decline_quiet ); #ugh
16 use Scalar::Util qw( blessed );
17 use List::Util qw( min );
18 use Time::Local qw(timelocal);
19 use Storable qw(thaw);
23 use Digest::MD5 qw(md5_base64);
26 use File::Temp qw( tempfile );
27 use String::Approx qw(amatch);
28 use Business::CreditCard 0.28;
30 use FS::UID qw( getotaker dbh driver_name );
31 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
32 use FS::Misc qw( generate_email send_email generate_ps do_print );
33 use FS::Msgcat qw(gettext);
38 use FS::cust_bill_pkg;
39 use FS::cust_bill_pkg_display;
40 use FS::cust_bill_pkg_tax_location;
41 use FS::cust_bill_pkg_tax_rate_location;
43 use FS::cust_pay_pending;
44 use FS::cust_pay_void;
45 use FS::cust_pay_batch;
48 use FS::part_referral;
49 use FS::cust_main_county;
50 use FS::cust_location;
52 use FS::cust_main_exemption;
53 use FS::cust_tax_adjustment;
55 use FS::tax_rate_location;
56 use FS::cust_tax_location;
57 use FS::part_pkg_taxrate;
59 use FS::cust_main_invoice;
61 use FS::cust_credit_bill;
62 use FS::cust_bill_pay;
63 use FS::prepay_credit;
67 use FS::part_event_condition;
71 use FS::payment_gateway;
72 use FS::agent_payment_gateway;
76 @EXPORT_OK = qw( smart_search );
78 $realtime_bop_decline_quiet = 0;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 $me = '[FS::cust_main]';
87 $ignore_expired_card = 0;
90 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub {
99 install_callback FS::UID sub {
100 $conf = new FS::Conf;
101 #yes, need it for stuff below (prolly should be cached)
106 my ( $hashref, $cache ) = @_;
107 if ( exists $hashref->{'pkgnum'} ) {
108 #@{ $self->{'_pkgnum'} } = ();
109 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110 $self->{'_pkgnum'} = $subcache;
111 #push @{ $self->{'_pkgnum'} },
112 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
118 FS::cust_main - Object methods for cust_main records
124 $record = new FS::cust_main \%hash;
125 $record = new FS::cust_main { 'column' => 'value' };
127 $error = $record->insert;
129 $error = $new_record->replace($old_record);
131 $error = $record->delete;
133 $error = $record->check;
135 @cust_pkg = $record->all_pkgs;
137 @cust_pkg = $record->ncancelled_pkgs;
139 @cust_pkg = $record->suspended_pkgs;
141 $error = $record->bill;
142 $error = $record->bill %options;
143 $error = $record->bill 'time' => $time;
145 $error = $record->collect;
146 $error = $record->collect %options;
147 $error = $record->collect 'invoice_time' => $time,
152 An FS::cust_main object represents a customer. FS::cust_main inherits from
153 FS::Record. The following fields are currently supported:
159 Primary key (assigned automatically for new customers)
163 Agent (see L<FS::agent>)
167 Advertising source (see L<FS::part_referral>)
179 Cocial security number (optional)
195 (optional, see L<FS::cust_main_county>)
199 (see L<FS::cust_main_county>)
205 (see L<FS::cust_main_county>)
241 (optional, see L<FS::cust_main_county>)
245 (see L<FS::cust_main_county>)
251 (see L<FS::cust_main_county>)
267 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
271 Payment Information (See L<FS::payinfo_Mixin> for data format)
275 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
279 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
283 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
287 Start date month (maestro/solo cards only)
291 Start date year (maestro/solo cards only)
295 Issue number (maestro/solo cards only)
299 Name on card or billing name
303 IP address from which payment information was received
307 Tax exempt, empty or `Y'
311 Order taker (see L<FS::access_user>)
317 =item referral_custnum
319 Referring customer number
323 Enable individual CDR spooling, empty or `Y'
327 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
331 Discourage individual CDR printing, empty or `Y'
341 Creates a new customer. To add the customer to the database, see L<"insert">.
343 Note that this stores the hash reference, not a distinct copy of the hash it
344 points to. You can ask the object for a copy with the I<hash> method.
348 sub table { 'cust_main'; }
350 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
352 Adds this customer to the database. If there is an error, returns the error,
353 otherwise returns false.
355 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
356 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
357 are inserted atomicly, or the transaction is rolled back. Passing an empty
358 hash reference is equivalent to not supplying this parameter. There should be
359 a better explanation of this, but until then, here's an example:
362 tie %hash, 'Tie::RefHash'; #this part is important
364 $cust_pkg => [ $svc_acct ],
367 $cust_main->insert( \%hash );
369 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
370 be set as the invoicing list (see L<"invoicing_list">). Errors return as
371 expected and rollback the entire transaction; it is not necessary to call
372 check_invoicing_list first. The invoicing_list is set after the records in the
373 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
374 invoicing_list destination to the newly-created svc_acct. Here's an example:
376 $cust_main->insert( {}, [ $email, 'POST' ] );
378 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
380 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
381 on the supplied jobnum (they will not run until the specific job completes).
382 This can be used to defer provisioning until some action completes (such
383 as running the customer's credit card successfully).
385 The I<noexport> option is deprecated. If I<noexport> is set true, no
386 provisioning jobs (exports) are scheduled. (You can schedule them later with
387 the B<reexport> method.)
389 The I<tax_exemption> option can be set to an arrayref of tax names.
390 FS::cust_main_exemption records will be created and inserted.
396 my $cust_pkgs = @_ ? shift : {};
397 my $invoicing_list = @_ ? shift : '';
399 warn "$me insert called with options ".
400 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
403 local $SIG{HUP} = 'IGNORE';
404 local $SIG{INT} = 'IGNORE';
405 local $SIG{QUIT} = 'IGNORE';
406 local $SIG{TERM} = 'IGNORE';
407 local $SIG{TSTP} = 'IGNORE';
408 local $SIG{PIPE} = 'IGNORE';
410 my $oldAutoCommit = $FS::UID::AutoCommit;
411 local $FS::UID::AutoCommit = 0;
414 my $prepay_identifier = '';
415 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
417 if ( $self->payby eq 'PREPAY' ) {
419 $self->payby('BILL');
420 $prepay_identifier = $self->payinfo;
423 warn " looking up prepaid card $prepay_identifier\n"
426 my $error = $self->get_prepay( $prepay_identifier,
427 'amount_ref' => \$amount,
428 'seconds_ref' => \$seconds,
429 'upbytes_ref' => \$upbytes,
430 'downbytes_ref' => \$downbytes,
431 'totalbytes_ref' => \$totalbytes,
434 $dbh->rollback if $oldAutoCommit;
435 #return "error applying prepaid card (transaction rolled back): $error";
439 $payby = 'PREP' if $amount;
441 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
444 $self->payby('BILL');
445 $amount = $self->paid;
449 warn " inserting $self\n"
452 $self->signupdate(time) unless $self->signupdate;
454 $self->auto_agent_custid()
455 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
457 my $error = $self->SUPER::insert;
459 $dbh->rollback if $oldAutoCommit;
460 #return "inserting cust_main record (transaction rolled back): $error";
464 warn " setting invoicing list\n"
467 if ( $invoicing_list ) {
468 $error = $self->check_invoicing_list( $invoicing_list );
470 $dbh->rollback if $oldAutoCommit;
471 #return "checking invoicing_list (transaction rolled back): $error";
474 $self->invoicing_list( $invoicing_list );
477 warn " setting customer tags\n"
480 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
481 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
482 'custnum' => $self->custnum };
483 my $error = $cust_tag->insert;
485 $dbh->rollback if $oldAutoCommit;
490 if ( $invoicing_list ) {
491 $error = $self->check_invoicing_list( $invoicing_list );
493 $dbh->rollback if $oldAutoCommit;
494 #return "checking invoicing_list (transaction rolled back): $error";
497 $self->invoicing_list( $invoicing_list );
501 warn " setting cust_main_exemption\n"
504 my $tax_exemption = delete $options{'tax_exemption'};
505 if ( $tax_exemption ) {
506 foreach my $taxname ( @$tax_exemption ) {
507 my $cust_main_exemption = new FS::cust_main_exemption {
508 'custnum' => $self->custnum,
509 'taxname' => $taxname,
511 my $error = $cust_main_exemption->insert;
513 $dbh->rollback if $oldAutoCommit;
514 return "inserting cust_main_exemption (transaction rolled back): $error";
519 if ( $conf->config('cust_main-skeleton_tables')
520 && $conf->config('cust_main-skeleton_custnum') ) {
522 warn " inserting skeleton records\n"
525 my $error = $self->start_copy_skel;
527 $dbh->rollback if $oldAutoCommit;
533 warn " ordering packages\n"
536 $error = $self->order_pkgs( $cust_pkgs,
538 'seconds_ref' => \$seconds,
539 'upbytes_ref' => \$upbytes,
540 'downbytes_ref' => \$downbytes,
541 'totalbytes_ref' => \$totalbytes,
544 $dbh->rollback if $oldAutoCommit;
549 $dbh->rollback if $oldAutoCommit;
550 return "No svc_acct record to apply pre-paid time";
552 if ( $upbytes || $downbytes || $totalbytes ) {
553 $dbh->rollback if $oldAutoCommit;
554 return "No svc_acct record to apply pre-paid data";
558 warn " inserting initial $payby payment of $amount\n"
560 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
562 $dbh->rollback if $oldAutoCommit;
563 return "inserting payment (transaction rolled back): $error";
567 unless ( $import || $skip_fuzzyfiles ) {
568 warn " queueing fuzzyfiles update\n"
570 $error = $self->queue_fuzzyfiles_update;
572 $dbh->rollback if $oldAutoCommit;
573 return "updating fuzzy search cache: $error";
578 warn " exporting\n" if $DEBUG > 1;
580 my $export_args = $options{'export_args'} || [];
583 map qsearch( 'part_export', {exportnum=>$_} ),
584 $conf->config('cust_main-exports'); #, $agentnum
586 foreach my $part_export ( @part_export ) {
587 my $error = $part_export->export_insert($self, @$export_args);
589 $dbh->rollback if $oldAutoCommit;
590 return "exporting to ". $part_export->exporttype.
591 " (transaction rolled back): $error";
595 #foreach my $depend_jobnum ( @$depend_jobnums ) {
596 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
598 # foreach my $jobnum ( @jobnums ) {
599 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
600 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
602 # my $error = $queue->depend_insert($depend_jobnum);
604 # $dbh->rollback if $oldAutoCommit;
605 # return "error queuing job dependancy: $error";
612 #if ( exists $options{'jobnums'} ) {
613 # push @{ $options{'jobnums'} }, @jobnums;
616 warn " insert complete; committing transaction\n"
619 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
624 use File::CounterFile;
625 sub auto_agent_custid {
628 my $format = $conf->config('cust_main-auto_agent_custid');
630 if ( $format eq '1YMMXXXXXXXX' ) {
632 my $counter = new File::CounterFile 'cust_main.agent_custid';
635 my $ym = 100000000000 + time2str('%y%m00000000', time);
636 if ( $ym > $counter->value ) {
637 $counter->{'value'} = $agent_custid = $ym;
638 $counter->{'updated'} = 1;
640 $agent_custid = $counter->inc;
646 die "Unknown cust_main-auto_agent_custid format: $format";
649 $self->agent_custid($agent_custid);
653 sub start_copy_skel {
656 #'mg_user_preference' => {},
657 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
658 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
659 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
660 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
661 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
664 _copy_skel( 'cust_main', #tablename
665 $conf->config('cust_main-skeleton_custnum'), #sourceid
666 $self->custnum, #destid
667 @tables, #child tables
671 #recursive subroutine, not a method
673 my( $table, $sourceid, $destid, %child_tables ) = @_;
676 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
677 ( $table, $primary_key ) = ( $1, $2 );
679 my $dbdef_table = dbdef->table($table);
680 $primary_key = $dbdef_table->primary_key
681 or return "$table has no primary key".
682 " (or do you need to run dbdef-create?)";
685 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
686 join (', ', keys %child_tables). "\n"
689 foreach my $child_table_def ( keys %child_tables ) {
693 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
694 ( $child_table, $child_pkey ) = ( $1, $2 );
696 $child_table = $child_table_def;
698 $child_pkey = dbdef->table($child_table)->primary_key;
699 # or return "$table has no primary key".
700 # " (or do you need to run dbdef-create?)\n";
704 if ( keys %{ $child_tables{$child_table_def} } ) {
706 return "$child_table has no primary key".
707 " (run dbdef-create or try specifying it?)\n"
710 #false laziness w/Record::insert and only works on Pg
711 #refactor the proper last-inserted-id stuff out of Record::insert if this
712 # ever gets use for anything besides a quick kludge for one customer
713 my $default = dbdef->table($child_table)->column($child_pkey)->default;
714 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
715 or return "can't parse $child_table.$child_pkey default value ".
716 " for sequence name: $default";
721 my @sel_columns = grep { $_ ne $primary_key }
722 dbdef->table($child_table)->columns;
723 my $sel_columns = join(', ', @sel_columns );
725 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
726 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
727 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
729 my $sel_st = "SELECT $sel_columns FROM $child_table".
730 " WHERE $primary_key = $sourceid";
733 my $sel_sth = dbh->prepare( $sel_st )
734 or return dbh->errstr;
736 $sel_sth->execute or return $sel_sth->errstr;
738 while ( my $row = $sel_sth->fetchrow_hashref ) {
740 warn " selected row: ".
741 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
745 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
746 my $ins_sth =dbh->prepare($statement)
747 or return dbh->errstr;
748 my @param = ( $destid, map $row->{$_}, @ins_columns );
749 warn " $statement: [ ". join(', ', @param). " ]\n"
751 $ins_sth->execute( @param )
752 or return $ins_sth->errstr;
754 #next unless keys %{ $child_tables{$child_table} };
755 next unless $sequence;
757 #another section of that laziness
758 my $seq_sql = "SELECT currval('$sequence')";
759 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
760 $seq_sth->execute or return $seq_sth->errstr;
761 my $insertid = $seq_sth->fetchrow_arrayref->[0];
763 # don't drink soap! recurse! recurse! okay!
765 _copy_skel( $child_table_def,
766 $row->{$child_pkey}, #sourceid
768 %{ $child_tables{$child_table_def} },
770 return $error if $error;
780 =item order_pkg HASHREF | OPTION => VALUE ...
782 Orders a single package.
784 Options may be passed as a list of key/value pairs or as a hash reference.
795 Optional FS::cust_location object
799 Optional arryaref of FS::svc_* service objects.
803 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
804 jobs will have a dependancy on the supplied job (they will not run until the
805 specific job completes). This can be used to defer provisioning until some
806 action completes (such as running the customer's credit card successfully).
810 Optional subject for a ticket created and attached to this customer
814 Optional queue name for ticket additions
822 my $opt = ref($_[0]) ? shift : { @_ };
824 warn "$me order_pkg called with options ".
825 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
828 my $cust_pkg = $opt->{'cust_pkg'};
829 my $svcs = $opt->{'svcs'} || [];
831 my %svc_options = ();
832 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
833 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
835 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
836 qw( ticket_subject ticket_queue );
838 local $SIG{HUP} = 'IGNORE';
839 local $SIG{INT} = 'IGNORE';
840 local $SIG{QUIT} = 'IGNORE';
841 local $SIG{TERM} = 'IGNORE';
842 local $SIG{TSTP} = 'IGNORE';
843 local $SIG{PIPE} = 'IGNORE';
845 my $oldAutoCommit = $FS::UID::AutoCommit;
846 local $FS::UID::AutoCommit = 0;
849 if ( $opt->{'cust_location'} &&
850 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
851 my $error = $opt->{'cust_location'}->insert;
853 $dbh->rollback if $oldAutoCommit;
854 return "inserting cust_location (transaction rolled back): $error";
856 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
859 $cust_pkg->custnum( $self->custnum );
861 my $error = $cust_pkg->insert( %insert_params );
863 $dbh->rollback if $oldAutoCommit;
864 return "inserting cust_pkg (transaction rolled back): $error";
867 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
868 if ( $svc_something->svcnum ) {
869 my $old_cust_svc = $svc_something->cust_svc;
870 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
871 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
872 $error = $new_cust_svc->replace($old_cust_svc);
874 $svc_something->pkgnum( $cust_pkg->pkgnum );
875 if ( $svc_something->isa('FS::svc_acct') ) {
876 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
877 qw( seconds upbytes downbytes totalbytes ) ) {
878 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
879 ${ $opt->{$_.'_ref'} } = 0;
882 $error = $svc_something->insert(%svc_options);
885 $dbh->rollback if $oldAutoCommit;
886 return "inserting svc_ (transaction rolled back): $error";
890 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
895 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
896 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
898 Like the insert method on an existing record, this method orders multiple
899 packages and included services atomicaly. Pass a Tie::RefHash data structure
900 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
901 There should be a better explanation of this, but until then, here's an
905 tie %hash, 'Tie::RefHash'; #this part is important
907 $cust_pkg => [ $svc_acct ],
910 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
912 Services can be new, in which case they are inserted, or existing unaudited
913 services, in which case they are linked to the newly-created package.
915 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
916 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
918 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
919 on the supplied jobnum (they will not run until the specific job completes).
920 This can be used to defer provisioning until some action completes (such
921 as running the customer's credit card successfully).
923 The I<noexport> option is deprecated. If I<noexport> is set true, no
924 provisioning jobs (exports) are scheduled. (You can schedule them later with
925 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
926 on the cust_main object is not recommended, as existing services will also be
929 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
930 provided, the scalars (provided by references) will be incremented by the
931 values of the prepaid card.`
937 my $cust_pkgs = shift;
938 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
940 $seconds_ref ||= $options{'seconds_ref'};
942 warn "$me order_pkgs called with options ".
943 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
946 local $SIG{HUP} = 'IGNORE';
947 local $SIG{INT} = 'IGNORE';
948 local $SIG{QUIT} = 'IGNORE';
949 local $SIG{TERM} = 'IGNORE';
950 local $SIG{TSTP} = 'IGNORE';
951 local $SIG{PIPE} = 'IGNORE';
953 my $oldAutoCommit = $FS::UID::AutoCommit;
954 local $FS::UID::AutoCommit = 0;
957 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
959 foreach my $cust_pkg ( keys %$cust_pkgs ) {
961 my $error = $self->order_pkg(
962 'cust_pkg' => $cust_pkg,
963 'svcs' => $cust_pkgs->{$cust_pkg},
964 'seconds_ref' => $seconds_ref,
965 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
970 $dbh->rollback if $oldAutoCommit;
976 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
980 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
982 Recharges this (existing) customer with the specified prepaid card (see
983 L<FS::prepay_credit>), specified either by I<identifier> or as an
984 FS::prepay_credit object. If there is an error, returns the error, otherwise
987 Optionally, five scalar references can be passed as well. They will have their
988 values filled in with the amount, number of seconds, and number of upload,
989 download, and total bytes applied by this prepaid card.
993 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
994 #the only place that uses these args
995 sub recharge_prepay {
996 my( $self, $prepay_credit, $amountref, $secondsref,
997 $upbytesref, $downbytesref, $totalbytesref ) = @_;
999 local $SIG{HUP} = 'IGNORE';
1000 local $SIG{INT} = 'IGNORE';
1001 local $SIG{QUIT} = 'IGNORE';
1002 local $SIG{TERM} = 'IGNORE';
1003 local $SIG{TSTP} = 'IGNORE';
1004 local $SIG{PIPE} = 'IGNORE';
1006 my $oldAutoCommit = $FS::UID::AutoCommit;
1007 local $FS::UID::AutoCommit = 0;
1010 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
1012 my $error = $self->get_prepay( $prepay_credit,
1013 'amount_ref' => \$amount,
1014 'seconds_ref' => \$seconds,
1015 'upbytes_ref' => \$upbytes,
1016 'downbytes_ref' => \$downbytes,
1017 'totalbytes_ref' => \$totalbytes,
1019 || $self->increment_seconds($seconds)
1020 || $self->increment_upbytes($upbytes)
1021 || $self->increment_downbytes($downbytes)
1022 || $self->increment_totalbytes($totalbytes)
1023 || $self->insert_cust_pay_prepay( $amount,
1025 ? $prepay_credit->identifier
1030 $dbh->rollback if $oldAutoCommit;
1034 if ( defined($amountref) ) { $$amountref = $amount; }
1035 if ( defined($secondsref) ) { $$secondsref = $seconds; }
1036 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1037 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1038 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1040 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1045 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1047 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1048 specified either by I<identifier> or as an FS::prepay_credit object.
1050 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>. The scalars (provided by references) will be
1051 incremented by the values of the prepaid card.
1053 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1054 check or set this customer's I<agentnum>.
1056 If there is an error, returns the error, otherwise returns false.
1062 my( $self, $prepay_credit, %opt ) = @_;
1064 local $SIG{HUP} = 'IGNORE';
1065 local $SIG{INT} = 'IGNORE';
1066 local $SIG{QUIT} = 'IGNORE';
1067 local $SIG{TERM} = 'IGNORE';
1068 local $SIG{TSTP} = 'IGNORE';
1069 local $SIG{PIPE} = 'IGNORE';
1071 my $oldAutoCommit = $FS::UID::AutoCommit;
1072 local $FS::UID::AutoCommit = 0;
1075 unless ( ref($prepay_credit) ) {
1077 my $identifier = $prepay_credit;
1079 $prepay_credit = qsearchs(
1081 { 'identifier' => $prepay_credit },
1086 unless ( $prepay_credit ) {
1087 $dbh->rollback if $oldAutoCommit;
1088 return "Invalid prepaid card: ". $identifier;
1093 if ( $prepay_credit->agentnum ) {
1094 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1095 $dbh->rollback if $oldAutoCommit;
1096 return "prepaid card not valid for agent ". $self->agentnum;
1098 $self->agentnum($prepay_credit->agentnum);
1101 my $error = $prepay_credit->delete;
1103 $dbh->rollback if $oldAutoCommit;
1104 return "removing prepay_credit (transaction rolled back): $error";
1107 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1108 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1110 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1115 =item increment_upbytes SECONDS
1117 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1118 the specified number of upbytes. If there is an error, returns the error,
1119 otherwise returns false.
1123 sub increment_upbytes {
1124 _increment_column( shift, 'upbytes', @_);
1127 =item increment_downbytes SECONDS
1129 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1130 the specified number of downbytes. If there is an error, returns the error,
1131 otherwise returns false.
1135 sub increment_downbytes {
1136 _increment_column( shift, 'downbytes', @_);
1139 =item increment_totalbytes SECONDS
1141 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1142 the specified number of totalbytes. If there is an error, returns the error,
1143 otherwise returns false.
1147 sub increment_totalbytes {
1148 _increment_column( shift, 'totalbytes', @_);
1151 =item increment_seconds SECONDS
1153 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1154 the specified number of seconds. If there is an error, returns the error,
1155 otherwise returns false.
1159 sub increment_seconds {
1160 _increment_column( shift, 'seconds', @_);
1163 =item _increment_column AMOUNT
1165 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1166 the specified number of seconds or bytes. If there is an error, returns
1167 the error, otherwise returns false.
1171 sub _increment_column {
1172 my( $self, $column, $amount ) = @_;
1173 warn "$me increment_column called: $column, $amount\n"
1176 return '' unless $amount;
1178 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1179 $self->ncancelled_pkgs;
1181 if ( ! @cust_pkg ) {
1182 return 'No packages with primary or single services found'.
1183 ' to apply pre-paid time';
1184 } elsif ( scalar(@cust_pkg) > 1 ) {
1185 #maybe have a way to specify the package/account?
1186 return 'Multiple packages found to apply pre-paid time';
1189 my $cust_pkg = $cust_pkg[0];
1190 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1194 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1196 if ( ! @cust_svc ) {
1197 return 'No account found to apply pre-paid time';
1198 } elsif ( scalar(@cust_svc) > 1 ) {
1199 return 'Multiple accounts found to apply pre-paid time';
1202 my $svc_acct = $cust_svc[0]->svc_x;
1203 warn " found service svcnum ". $svc_acct->pkgnum.
1204 ' ('. $svc_acct->email. ")\n"
1207 $column = "increment_$column";
1208 $svc_acct->$column($amount);
1212 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1214 Inserts a prepayment in the specified amount for this customer. An optional
1215 second argument can specify the prepayment identifier for tracking purposes.
1216 If there is an error, returns the error, otherwise returns false.
1220 sub insert_cust_pay_prepay {
1221 shift->insert_cust_pay('PREP', @_);
1224 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1226 Inserts a cash payment in the specified amount for this customer. An optional
1227 second argument can specify the payment identifier for tracking purposes.
1228 If there is an error, returns the error, otherwise returns false.
1232 sub insert_cust_pay_cash {
1233 shift->insert_cust_pay('CASH', @_);
1236 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1238 Inserts a Western Union payment in the specified amount for this customer. An
1239 optional second argument can specify the prepayment identifier for tracking
1240 purposes. If there is an error, returns the error, otherwise returns false.
1244 sub insert_cust_pay_west {
1245 shift->insert_cust_pay('WEST', @_);
1248 sub insert_cust_pay {
1249 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1250 my $payinfo = scalar(@_) ? shift : '';
1252 my $cust_pay = new FS::cust_pay {
1253 'custnum' => $self->custnum,
1254 'paid' => sprintf('%.2f', $amount),
1255 #'_date' => #date the prepaid card was purchased???
1257 'payinfo' => $payinfo,
1265 This method is deprecated. See the I<depend_jobnum> option to the insert and
1266 order_pkgs methods for a better way to defer provisioning.
1268 Re-schedules all exports by calling the B<reexport> method of all associated
1269 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1270 otherwise returns false.
1277 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1278 "use the depend_jobnum option to insert or order_pkgs to delay export";
1280 local $SIG{HUP} = 'IGNORE';
1281 local $SIG{INT} = 'IGNORE';
1282 local $SIG{QUIT} = 'IGNORE';
1283 local $SIG{TERM} = 'IGNORE';
1284 local $SIG{TSTP} = 'IGNORE';
1285 local $SIG{PIPE} = 'IGNORE';
1287 my $oldAutoCommit = $FS::UID::AutoCommit;
1288 local $FS::UID::AutoCommit = 0;
1291 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1292 my $error = $cust_pkg->reexport;
1294 $dbh->rollback if $oldAutoCommit;
1299 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1304 =item delete [ OPTION => VALUE ... ]
1306 This deletes the customer. If there is an error, returns the error, otherwise
1309 This will completely remove all traces of the customer record. This is not
1310 what you want when a customer cancels service; for that, cancel all of the
1311 customer's packages (see L</cancel>).
1313 If the customer has any uncancelled packages, you need to pass a new (valid)
1314 customer number for those packages to be transferred to, as the "new_customer"
1315 option. Cancelled packages will be deleted. Did I mention that this is NOT
1316 what you want when a customer cancels service and that you really should be
1317 looking at L<FS::cust_pkg/cancel>?
1319 You can't delete a customer with invoices (see L<FS::cust_bill>),
1320 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1321 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1322 set the "delete_financials" option to a true value.
1327 my( $self, %opt ) = @_;
1329 local $SIG{HUP} = 'IGNORE';
1330 local $SIG{INT} = 'IGNORE';
1331 local $SIG{QUIT} = 'IGNORE';
1332 local $SIG{TERM} = 'IGNORE';
1333 local $SIG{TSTP} = 'IGNORE';
1334 local $SIG{PIPE} = 'IGNORE';
1336 my $oldAutoCommit = $FS::UID::AutoCommit;
1337 local $FS::UID::AutoCommit = 0;
1340 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1341 $dbh->rollback if $oldAutoCommit;
1342 return "Can't delete a master agent customer";
1345 #use FS::access_user
1346 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1347 $dbh->rollback if $oldAutoCommit;
1348 return "Can't delete a master employee customer";
1351 tie my %financial_tables, 'Tie::IxHash',
1352 'cust_bill' => 'invoices',
1353 'cust_statement' => 'statements',
1354 'cust_credit' => 'credits',
1355 'cust_pay' => 'payments',
1356 'cust_refund' => 'refunds',
1359 foreach my $table ( keys %financial_tables ) {
1361 my @records = $self->$table();
1363 if ( @records && ! $opt{'delete_financials'} ) {
1364 $dbh->rollback if $oldAutoCommit;
1365 return "Can't delete a customer with ". $financial_tables{$table};
1368 foreach my $record ( @records ) {
1369 my $error = $record->delete;
1371 $dbh->rollback if $oldAutoCommit;
1372 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1378 my @cust_pkg = $self->ncancelled_pkgs;
1380 my $new_custnum = $opt{'new_custnum'};
1381 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1382 $dbh->rollback if $oldAutoCommit;
1383 return "Invalid new customer number: $new_custnum";
1385 foreach my $cust_pkg ( @cust_pkg ) {
1386 my %hash = $cust_pkg->hash;
1387 $hash{'custnum'} = $new_custnum;
1388 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1389 my $error = $new_cust_pkg->replace($cust_pkg,
1390 options => { $cust_pkg->options },
1393 $dbh->rollback if $oldAutoCommit;
1398 my @cancelled_cust_pkg = $self->all_pkgs;
1399 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1400 my $error = $cust_pkg->delete;
1402 $dbh->rollback if $oldAutoCommit;
1407 #cust_tax_adjustment in financials?
1408 #cust_pay_pending? ouch
1409 foreach my $table (qw(
1410 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1411 cust_location cust_main_note cust_tax_adjustment
1412 cust_pay_void cust_pay_batch queue cust_tax_exempt
1415 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1416 my $error = $record->delete;
1418 $dbh->rollback if $oldAutoCommit;
1424 my $sth = $dbh->prepare(
1425 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1427 my $errstr = $dbh->errstr;
1428 $dbh->rollback if $oldAutoCommit;
1431 $sth->execute($self->custnum) or do {
1432 my $errstr = $sth->errstr;
1433 $dbh->rollback if $oldAutoCommit;
1437 my $error = $self->SUPER::delete;
1439 $dbh->rollback if $oldAutoCommit;
1443 # cust_main exports!
1445 #my $export_args = $options{'export_args'} || [];
1448 map qsearch( 'part_export', {exportnum=>$_} ),
1449 $conf->config('cust_main-exports'); #, $agentnum
1451 foreach my $part_export ( @part_export ) {
1452 my $error = $part_export->export_delete( $self ); #, @$export_args);
1454 $dbh->rollback if $oldAutoCommit;
1455 return "exporting to ". $part_export->exporttype.
1456 " (transaction rolled back): $error";
1460 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1465 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1468 Replaces the OLD_RECORD with this one in the database. If there is an error,
1469 returns the error, otherwise returns false.
1471 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1472 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1473 expected and rollback the entire transaction; it is not necessary to call
1474 check_invoicing_list first. Here's an example:
1476 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1478 Currently available options are: I<tax_exemption>.
1480 The I<tax_exemption> option can be set to an arrayref of tax names.
1481 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1488 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1490 : $self->replace_old;
1494 warn "$me replace called\n"
1497 my $curuser = $FS::CurrentUser::CurrentUser;
1498 if ( $self->payby eq 'COMP'
1499 && $self->payby ne $old->payby
1500 && ! $curuser->access_right('Complimentary customer')
1503 return "You are not permitted to create complimentary accounts.";
1506 local($ignore_expired_card) = 1
1507 if $old->payby =~ /^(CARD|DCRD)$/
1508 && $self->payby =~ /^(CARD|DCRD)$/
1509 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1511 local $SIG{HUP} = 'IGNORE';
1512 local $SIG{INT} = 'IGNORE';
1513 local $SIG{QUIT} = 'IGNORE';
1514 local $SIG{TERM} = 'IGNORE';
1515 local $SIG{TSTP} = 'IGNORE';
1516 local $SIG{PIPE} = 'IGNORE';
1518 my $oldAutoCommit = $FS::UID::AutoCommit;
1519 local $FS::UID::AutoCommit = 0;
1522 my $error = $self->SUPER::replace($old);
1525 $dbh->rollback if $oldAutoCommit;
1529 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1530 my $invoicing_list = shift @param;
1531 $error = $self->check_invoicing_list( $invoicing_list );
1533 $dbh->rollback if $oldAutoCommit;
1536 $self->invoicing_list( $invoicing_list );
1539 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1541 #this could be more efficient than deleting and re-inserting, if it matters
1542 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1543 my $error = $cust_tag->delete;
1545 $dbh->rollback if $oldAutoCommit;
1549 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1550 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1551 'custnum' => $self->custnum };
1552 my $error = $cust_tag->insert;
1554 $dbh->rollback if $oldAutoCommit;
1561 my %options = @param;
1563 my $tax_exemption = delete $options{'tax_exemption'};
1564 if ( $tax_exemption ) {
1566 my %cust_main_exemption =
1567 map { $_->taxname => $_ }
1568 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1570 foreach my $taxname ( @$tax_exemption ) {
1572 next if delete $cust_main_exemption{$taxname};
1574 my $cust_main_exemption = new FS::cust_main_exemption {
1575 'custnum' => $self->custnum,
1576 'taxname' => $taxname,
1578 my $error = $cust_main_exemption->insert;
1580 $dbh->rollback if $oldAutoCommit;
1581 return "inserting cust_main_exemption (transaction rolled back): $error";
1585 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1586 my $error = $cust_main_exemption->delete;
1588 $dbh->rollback if $oldAutoCommit;
1589 return "deleting cust_main_exemption (transaction rolled back): $error";
1595 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1596 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1597 && $self->get('payinfo') !~ /^99\d{14}$/
1599 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1604 # card/check/lec info has changed, want to retry realtime_ invoice events
1605 my $error = $self->retry_realtime;
1607 $dbh->rollback if $oldAutoCommit;
1612 unless ( $import || $skip_fuzzyfiles ) {
1613 $error = $self->queue_fuzzyfiles_update;
1615 $dbh->rollback if $oldAutoCommit;
1616 return "updating fuzzy search cache: $error";
1620 # cust_main exports!
1622 my $export_args = $options{'export_args'} || [];
1625 map qsearch( 'part_export', {exportnum=>$_} ),
1626 $conf->config('cust_main-exports'); #, $agentnum
1628 foreach my $part_export ( @part_export ) {
1629 my $error = $part_export->export_replace( $self, $old, @$export_args);
1631 $dbh->rollback if $oldAutoCommit;
1632 return "exporting to ". $part_export->exporttype.
1633 " (transaction rolled back): $error";
1637 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1642 =item queue_fuzzyfiles_update
1644 Used by insert & replace to update the fuzzy search cache
1648 sub queue_fuzzyfiles_update {
1651 local $SIG{HUP} = 'IGNORE';
1652 local $SIG{INT} = 'IGNORE';
1653 local $SIG{QUIT} = 'IGNORE';
1654 local $SIG{TERM} = 'IGNORE';
1655 local $SIG{TSTP} = 'IGNORE';
1656 local $SIG{PIPE} = 'IGNORE';
1658 my $oldAutoCommit = $FS::UID::AutoCommit;
1659 local $FS::UID::AutoCommit = 0;
1662 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1663 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1665 $dbh->rollback if $oldAutoCommit;
1666 return "queueing job (transaction rolled back): $error";
1669 if ( $self->ship_last ) {
1670 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1671 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1673 $dbh->rollback if $oldAutoCommit;
1674 return "queueing job (transaction rolled back): $error";
1678 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1685 Checks all fields to make sure this is a valid customer record. If there is
1686 an error, returns the error, otherwise returns false. Called by the insert
1687 and replace methods.
1694 warn "$me check BEFORE: \n". $self->_dump
1698 $self->ut_numbern('custnum')
1699 || $self->ut_number('agentnum')
1700 || $self->ut_textn('agent_custid')
1701 || $self->ut_number('refnum')
1702 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1703 || $self->ut_textn('custbatch')
1704 || $self->ut_name('last')
1705 || $self->ut_name('first')
1706 || $self->ut_snumbern('birthdate')
1707 || $self->ut_snumbern('signupdate')
1708 || $self->ut_textn('company')
1709 || $self->ut_text('address1')
1710 || $self->ut_textn('address2')
1711 || $self->ut_text('city')
1712 || $self->ut_textn('county')
1713 || $self->ut_textn('state')
1714 || $self->ut_country('country')
1715 || $self->ut_anything('comments')
1716 || $self->ut_numbern('referral_custnum')
1717 || $self->ut_textn('stateid')
1718 || $self->ut_textn('stateid_state')
1719 || $self->ut_textn('invoice_terms')
1720 || $self->ut_alphan('geocode')
1721 || $self->ut_floatn('cdr_termination_percentage')
1724 #barf. need message catalogs. i18n. etc.
1725 $error .= "Please select an advertising source."
1726 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1727 return $error if $error;
1729 return "Unknown agent"
1730 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1732 return "Unknown refnum"
1733 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1735 return "Unknown referring custnum: ". $self->referral_custnum
1736 unless ! $self->referral_custnum
1737 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1739 if ( $self->censustract ne '' ) {
1740 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1741 or return "Illegal census tract: ". $self->censustract;
1743 $self->censustract("$1.$2");
1746 if ( $self->ss eq '' ) {
1751 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1752 or return "Illegal social security number: ". $self->ss;
1753 $self->ss("$1-$2-$3");
1757 # bad idea to disable, causes billing to fail because of no tax rates later
1758 # unless ( $import ) {
1759 unless ( qsearch('cust_main_county', {
1760 'country' => $self->country,
1763 return "Unknown state/county/country: ".
1764 $self->state. "/". $self->county. "/". $self->country
1765 unless qsearch('cust_main_county',{
1766 'state' => $self->state,
1767 'county' => $self->county,
1768 'country' => $self->country,
1774 $self->ut_phonen('daytime', $self->country)
1775 || $self->ut_phonen('night', $self->country)
1776 || $self->ut_phonen('fax', $self->country)
1777 || $self->ut_zip('zip', $self->country)
1779 return $error if $error;
1781 if ( $conf->exists('cust_main-require_phone')
1782 && ! length($self->daytime) && ! length($self->night)
1785 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1787 : FS::Msgcat::_gettext('daytime');
1788 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1790 : FS::Msgcat::_gettext('night');
1792 return "$daytime_label or $night_label is required"
1796 if ( $self->has_ship_address
1797 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1798 $self->addr_fields )
1802 $self->ut_name('ship_last')
1803 || $self->ut_name('ship_first')
1804 || $self->ut_textn('ship_company')
1805 || $self->ut_text('ship_address1')
1806 || $self->ut_textn('ship_address2')
1807 || $self->ut_text('ship_city')
1808 || $self->ut_textn('ship_county')
1809 || $self->ut_textn('ship_state')
1810 || $self->ut_country('ship_country')
1812 return $error if $error;
1814 #false laziness with above
1815 unless ( qsearchs('cust_main_county', {
1816 'country' => $self->ship_country,
1819 return "Unknown ship_state/ship_county/ship_country: ".
1820 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1821 unless qsearch('cust_main_county',{
1822 'state' => $self->ship_state,
1823 'county' => $self->ship_county,
1824 'country' => $self->ship_country,
1830 $self->ut_phonen('ship_daytime', $self->ship_country)
1831 || $self->ut_phonen('ship_night', $self->ship_country)
1832 || $self->ut_phonen('ship_fax', $self->ship_country)
1833 || $self->ut_zip('ship_zip', $self->ship_country)
1835 return $error if $error;
1837 return "Unit # is required."
1838 if $self->ship_address2 =~ /^\s*$/
1839 && $conf->exists('cust_main-require_address2');
1841 } else { # ship_ info eq billing info, so don't store dup info in database
1843 $self->setfield("ship_$_", '')
1844 foreach $self->addr_fields;
1846 return "Unit # is required."
1847 if $self->address2 =~ /^\s*$/
1848 && $conf->exists('cust_main-require_address2');
1852 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1853 # or return "Illegal payby: ". $self->payby;
1855 FS::payby->can_payby($self->table, $self->payby)
1856 or return "Illegal payby: ". $self->payby;
1858 $error = $self->ut_numbern('paystart_month')
1859 || $self->ut_numbern('paystart_year')
1860 || $self->ut_numbern('payissue')
1861 || $self->ut_textn('paytype')
1863 return $error if $error;
1865 if ( $self->payip eq '' ) {
1868 $error = $self->ut_ip('payip');
1869 return $error if $error;
1872 # If it is encrypted and the private key is not availaible then we can't
1873 # check the credit card.
1874 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1876 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1878 my $payinfo = $self->payinfo;
1879 $payinfo =~ s/\D//g;
1880 $payinfo =~ /^(\d{13,16})$/
1881 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1883 $self->payinfo($payinfo);
1885 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1887 return gettext('unknown_card_type')
1888 if $self->payinfo !~ /^99\d{14}$/ #token
1889 && cardtype($self->payinfo) eq "Unknown";
1891 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1893 return 'Banned credit card: banned on '.
1894 time2str('%a %h %o at %r', $ban->_date).
1895 ' by '. $ban->otaker.
1896 ' (ban# '. $ban->bannum. ')';
1899 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1900 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1901 $self->paycvv =~ /^(\d{4})$/
1902 or return "CVV2 (CID) for American Express cards is four digits.";
1905 $self->paycvv =~ /^(\d{3})$/
1906 or return "CVV2 (CVC2/CID) is three digits.";
1913 my $cardtype = cardtype($payinfo);
1914 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1916 return "Start date or issue number is required for $cardtype cards"
1917 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1919 return "Start month must be between 1 and 12"
1920 if $self->paystart_month
1921 and $self->paystart_month < 1 || $self->paystart_month > 12;
1923 return "Start year must be 1990 or later"
1924 if $self->paystart_year
1925 and $self->paystart_year < 1990;
1927 return "Issue number must be beween 1 and 99"
1929 and $self->payissue < 1 || $self->payissue > 99;
1932 $self->paystart_month('');
1933 $self->paystart_year('');
1934 $self->payissue('');
1937 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1939 my $payinfo = $self->payinfo;
1940 $payinfo =~ s/[^\d\@]//g;
1941 if ( $conf->exists('echeck-nonus') ) {
1942 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1943 $payinfo = "$1\@$2";
1945 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1946 $payinfo = "$1\@$2";
1948 $self->payinfo($payinfo);
1951 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1953 return 'Banned ACH account: banned on '.
1954 time2str('%a %h %o at %r', $ban->_date).
1955 ' by '. $ban->otaker.
1956 ' (ban# '. $ban->bannum. ')';
1959 } elsif ( $self->payby eq 'LECB' ) {
1961 my $payinfo = $self->payinfo;
1962 $payinfo =~ s/\D//g;
1963 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1965 $self->payinfo($payinfo);
1968 } elsif ( $self->payby eq 'BILL' ) {
1970 $error = $self->ut_textn('payinfo');
1971 return "Illegal P.O. number: ". $self->payinfo if $error;
1974 } elsif ( $self->payby eq 'COMP' ) {
1976 my $curuser = $FS::CurrentUser::CurrentUser;
1977 if ( ! $self->custnum
1978 && ! $curuser->access_right('Complimentary customer')
1981 return "You are not permitted to create complimentary accounts."
1984 $error = $self->ut_textn('payinfo');
1985 return "Illegal comp account issuer: ". $self->payinfo if $error;
1988 } elsif ( $self->payby eq 'PREPAY' ) {
1990 my $payinfo = $self->payinfo;
1991 $payinfo =~ s/\W//g; #anything else would just confuse things
1992 $self->payinfo($payinfo);
1993 $error = $self->ut_alpha('payinfo');
1994 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1995 return "Unknown prepayment identifier"
1996 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2001 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2002 return "Expiration date required"
2003 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2007 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2008 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2009 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2010 ( $m, $y ) = ( $2, "19$1" );
2011 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2012 ( $m, $y ) = ( $3, "20$2" );
2014 return "Illegal expiration date: ". $self->paydate;
2016 $self->paydate("$y-$m-01");
2017 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2018 return gettext('expired_card')
2020 && !$ignore_expired_card
2021 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2024 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2025 ( ! $conf->exists('require_cardname')
2026 || $self->payby !~ /^(CARD|DCRD)$/ )
2028 $self->payname( $self->first. " ". $self->getfield('last') );
2030 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2031 or return gettext('illegal_name'). " payname: ". $self->payname;
2035 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2036 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2040 $self->otaker(getotaker) unless $self->otaker;
2042 warn "$me check AFTER: \n". $self->_dump
2045 $self->SUPER::check;
2050 Returns a list of fields which have ship_ duplicates.
2055 qw( last first company
2056 address1 address2 city county state zip country
2061 =item has_ship_address
2063 Returns true if this customer record has a separate shipping address.
2067 sub has_ship_address {
2069 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2074 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2075 city, county, state, zip, country. The shipping address is used if present.
2079 #geocode? dependent on tax-ship_address config, not available in cust_location
2080 #mostly. not yet then.
2084 my $prefix = $self->has_ship_address ? 'ship_' : '';
2086 map { $_ => $self->get($prefix.$_) }
2087 qw( address1 address2 city county state zip country geocode );
2088 #fields that cust_location has
2091 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2093 Returns all packages (see L<FS::cust_pkg>) for this customer.
2099 my $extra_qsearch = ref($_[0]) ? shift : {};
2101 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
2104 if ( $self->{'_pkgnum'} ) {
2105 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2107 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2110 sort sort_packages @cust_pkg;
2115 Synonym for B<all_pkgs>.
2120 shift->all_pkgs(@_);
2125 Returns all locations (see L<FS::cust_location>) for this customer.
2131 qsearch('cust_location', { 'custnum' => $self->custnum } );
2134 =item location_label [ OPTION => VALUE ... ]
2136 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2144 used to separate the address elements (defaults to ', ')
2146 =item escape_function
2148 a callback used for escaping the text of the address elements
2154 # false laziness with FS::cust_location::line
2156 sub location_label {
2160 my $separator = $opt{join_string} || ', ';
2161 my $escape = $opt{escape_function} || sub{ shift };
2163 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2164 my $prefix = length($self->ship_last) ? 'ship_' : '';
2167 foreach (qw ( address1 address2 ) ) {
2168 my $method = "$prefix$_";
2169 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2174 foreach (qw ( city county state zip ) ) {
2175 my $method = "$prefix$_";
2176 if ( $self->$method ) {
2177 $line .= ' (' if $method eq 'county';
2178 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2179 $line .= ' )' if $method eq 'county';
2183 $line .= $separator. &$escape(code2country($self->country))
2184 if $self->country ne $cydefault;
2189 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2191 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2195 sub ncancelled_pkgs {
2197 my $extra_qsearch = ref($_[0]) ? shift : {};
2199 return $self->num_ncancelled_pkgs unless wantarray;
2202 if ( $self->{'_pkgnum'} ) {
2204 warn "$me ncancelled_pkgs: returning cached objects"
2207 @cust_pkg = grep { ! $_->getfield('cancel') }
2208 values %{ $self->{'_pkgnum'}->cache };
2212 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2213 $self->custnum. "\n"
2216 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2218 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2222 sort sort_packages @cust_pkg;
2228 my $extra_qsearch = ref($_[0]) ? shift : {};
2230 $extra_qsearch->{'select'} ||= '*';
2231 $extra_qsearch->{'select'} .=
2232 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2236 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2241 'table' => 'cust_pkg',
2242 'hashref' => { 'custnum' => $self->custnum },
2247 # This should be generalized to use config options to determine order.
2250 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2251 return $locationsort if $locationsort;
2253 if ( $a->get('cancel') xor $b->get('cancel') ) {
2254 return -1 if $b->get('cancel');
2255 return 1 if $a->get('cancel');
2256 #shouldn't get here...
2259 my $a_num_cust_svc = $a->num_cust_svc;
2260 my $b_num_cust_svc = $b->num_cust_svc;
2261 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2262 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2263 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2264 my @a_cust_svc = $a->cust_svc;
2265 my @b_cust_svc = $b->cust_svc;
2266 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2267 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2268 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
2269 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2274 =item suspended_pkgs
2276 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2280 sub suspended_pkgs {
2282 grep { $_->susp } $self->ncancelled_pkgs;
2285 =item unflagged_suspended_pkgs
2287 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2288 customer (thouse packages without the `manual_flag' set).
2292 sub unflagged_suspended_pkgs {
2294 return $self->suspended_pkgs
2295 unless dbdef->table('cust_pkg')->column('manual_flag');
2296 grep { ! $_->manual_flag } $self->suspended_pkgs;
2299 =item unsuspended_pkgs
2301 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2306 sub unsuspended_pkgs {
2308 grep { ! $_->susp } $self->ncancelled_pkgs;
2311 =item next_bill_date
2313 Returns the next date this customer will be billed, as a UNIX timestamp, or
2314 undef if no active package has a next bill date.
2318 sub next_bill_date {
2320 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2323 =item num_cancelled_pkgs
2325 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2330 sub num_cancelled_pkgs {
2331 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2334 sub num_ncancelled_pkgs {
2335 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2339 my( $self ) = shift;
2340 my $sql = scalar(@_) ? shift : '';
2341 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2342 my $sth = dbh->prepare(
2343 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2344 ) or die dbh->errstr;
2345 $sth->execute($self->custnum) or die $sth->errstr;
2346 $sth->fetchrow_arrayref->[0];
2351 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2352 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2353 on success or a list of errors.
2359 grep { $_->unsuspend } $self->suspended_pkgs;
2364 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2366 Returns a list: an empty list on success or a list of errors.
2372 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2375 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2377 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2378 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2379 of a list of pkgparts; the hashref has the following keys:
2383 =item pkgparts - listref of pkgparts
2385 =item (other options are passed to the suspend method)
2390 Returns a list: an empty list on success or a list of errors.
2394 sub suspend_if_pkgpart {
2396 my (@pkgparts, %opt);
2397 if (ref($_[0]) eq 'HASH'){
2398 @pkgparts = @{$_[0]{pkgparts}};
2403 grep { $_->suspend(%opt) }
2404 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2405 $self->unsuspended_pkgs;
2408 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2410 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2411 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2412 instead of a list of pkgparts; the hashref has the following keys:
2416 =item pkgparts - listref of pkgparts
2418 =item (other options are passed to the suspend method)
2422 Returns a list: an empty list on success or a list of errors.
2426 sub suspend_unless_pkgpart {
2428 my (@pkgparts, %opt);
2429 if (ref($_[0]) eq 'HASH'){
2430 @pkgparts = @{$_[0]{pkgparts}};
2435 grep { $_->suspend(%opt) }
2436 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2437 $self->unsuspended_pkgs;
2440 =item cancel [ OPTION => VALUE ... ]
2442 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2444 Available options are:
2448 =item quiet - can be set true to supress email cancellation notices.
2450 =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.
2452 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2454 =item nobill - can be set true to skip billing if it might otherwise be done.
2458 Always returns a list: an empty list on success or a list of errors.
2462 # nb that dates are not specified as valid options to this method
2465 my( $self, %opt ) = @_;
2467 warn "$me cancel called on customer ". $self->custnum. " with options ".
2468 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2471 return ( 'access denied' )
2472 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2474 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2476 #should try decryption (we might have the private key)
2477 # and if not maybe queue a job for the server that does?
2478 return ( "Can't (yet) ban encrypted credit cards" )
2479 if $self->is_encrypted($self->payinfo);
2481 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2482 my $error = $ban->insert;
2483 return ( $error ) if $error;
2487 my @pkgs = $self->ncancelled_pkgs;
2489 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2491 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2492 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2496 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2497 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2500 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2503 sub _banned_pay_hashref {
2514 'payby' => $payby2ban{$self->payby},
2515 'payinfo' => md5_base64($self->payinfo),
2516 #don't ever *search* on reason! #'reason' =>
2522 Returns all notes (see L<FS::cust_main_note>) for this customer.
2529 qsearch( 'cust_main_note',
2530 { 'custnum' => $self->custnum },
2532 'ORDER BY _DATE DESC'
2538 Returns the agent (see L<FS::agent>) for this customer.
2544 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2549 Returns the agent name (see L<FS::agent>) for this customer.
2555 $self->agent->agent;
2560 Returns any tags associated with this customer, as FS::cust_tag objects,
2561 or an empty list if there are no tags.
2567 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2572 Returns any tags associated with this customer, as FS::part_tag objects,
2573 or an empty list if there are no tags.
2579 map $_->part_tag, $self->cust_tag;
2585 Returns the customer class, as an FS::cust_class object, or the empty string
2586 if there is no customer class.
2592 if ( $self->classnum ) {
2593 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2601 Returns the customer category name, or the empty string if there is no customer
2608 my $cust_class = $self->cust_class;
2610 ? $cust_class->categoryname
2616 Returns the customer class name, or the empty string if there is no customer
2623 my $cust_class = $self->cust_class;
2625 ? $cust_class->classname
2630 =item bill_and_collect
2632 Cancels and suspends any packages due, generates bills, applies payments and
2633 credits, and applies collection events to run cards, send bills and notices,
2636 By default, warns on errors and continues with the next operation (but see the
2637 "fatal" flag below).
2639 Options are passed as name-value pairs. Currently available options are:
2645 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:
2649 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2653 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.
2657 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2661 If set true, re-charges setup fees.
2665 If set any errors prevent subsequent operations from continusing. If set
2666 specifically to "return", returns the error (or false, if there is no error).
2667 Any other true value causes errors to die.
2671 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)
2675 Optional FS::queue entry to receive status updates.
2679 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2680 options of those methods are also available.
2684 sub bill_and_collect {
2685 my( $self, %options ) = @_;
2689 #$options{actual_time} not $options{time} because freeside-daily -d is for
2690 #pre-printing invoices
2692 $options{'actual_time'} ||= time;
2693 my $job = $options{'job'};
2695 $job->update_statustext('0,cleaning expired packages') if $job;
2696 $error = $self->cancel_expired_pkgs( $options{actual_time} );
2698 $error = "Error expiring custnum ". $self->custnum. ": $error";
2699 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2700 elsif ( $options{fatal} ) { die $error; }
2701 else { warn $error; }
2704 $error = $self->suspend_adjourned_pkgs( $options{actual_time} );
2706 $error = "Error adjourning custnum ". $self->custnum. ": $error";
2707 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2708 elsif ( $options{fatal} ) { die $error; }
2709 else { warn $error; }
2712 $job->update_statustext('20,billing packages') if $job;
2713 $error = $self->bill( %options );
2715 $error = "Error billing custnum ". $self->custnum. ": $error";
2716 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2717 elsif ( $options{fatal} ) { die $error; }
2718 else { warn $error; }
2721 $job->update_statustext('50,applying payments and credits') if $job;
2722 $error = $self->apply_payments_and_credits;
2724 $error = "Error applying custnum ". $self->custnum. ": $error";
2725 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2726 elsif ( $options{fatal} ) { die $error; }
2727 else { warn $error; }
2730 $job->update_statustext('70,running collection events') if $job;
2731 unless ( $conf->exists('cancelled_cust-noevents')
2732 && ! $self->num_ncancelled_pkgs
2734 $error = $self->collect( %options );
2736 $error = "Error collecting custnum ". $self->custnum. ": $error";
2737 if ($options{fatal} && $options{fatal} eq 'return') { return $error; }
2738 elsif ($options{fatal} ) { die $error; }
2739 else { warn $error; }
2742 $job->update_statustext('100,finished') if $job;
2748 sub cancel_expired_pkgs {
2749 my ( $self, $time, %options ) = @_;
2751 my @cancel_pkgs = $self->ncancelled_pkgs( {
2752 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2757 foreach my $cust_pkg ( @cancel_pkgs ) {
2758 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2759 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2760 'reason_otaker' => $cpr->otaker
2764 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2767 scalar(@errors) ? join(' / ', @errors) : '';
2771 sub suspend_adjourned_pkgs {
2772 my ( $self, $time, %options ) = @_;
2774 my @susp_pkgs = $self->ncancelled_pkgs( {
2776 " AND ( susp IS NULL OR susp = 0 )
2777 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
2778 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2783 #only because there's no SQL test for is_prepaid :/
2785 grep { ( $_->part_pkg->is_prepaid
2790 && $_->adjourn <= $time
2798 foreach my $cust_pkg ( @susp_pkgs ) {
2799 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2800 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2801 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2802 'reason_otaker' => $cpr->otaker
2806 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2809 scalar(@errors) ? join(' / ', @errors) : '';
2815 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2816 conjunction with the collect method by calling B<bill_and_collect>.
2818 If there is an error, returns the error, otherwise returns false.
2820 Options are passed as name-value pairs. Currently available options are:
2826 If set true, re-charges setup fees.
2830 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:
2834 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2838 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2840 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2844 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2848 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.
2852 This boolean value informs the us that the package is being cancelled. This
2853 typically might mean not charging the normal recurring fee but only usage
2854 fees since the last billing. Setup charges may be charged. Not all package
2855 plans support this feature (they tend to charge 0).
2859 Optional terms to be printed on this invoice. Otherwise, customer-specific
2860 terms or the default terms are used.
2867 my( $self, %options ) = @_;
2868 return '' if $self->payby eq 'COMP';
2869 warn "$me bill customer ". $self->custnum. "\n"
2872 my $time = $options{'time'} || time;
2873 my $invoice_time = $options{'invoice_time'} || $time;
2875 $options{'not_pkgpart'} ||= {};
2876 $options{'not_pkgpart'} = { map { $_ => 1 }
2877 split(/\s*,\s*/, $options{'not_pkgpart'})
2879 unless ref($options{'not_pkgpart'});
2881 local $SIG{HUP} = 'IGNORE';
2882 local $SIG{INT} = 'IGNORE';
2883 local $SIG{QUIT} = 'IGNORE';
2884 local $SIG{TERM} = 'IGNORE';
2885 local $SIG{TSTP} = 'IGNORE';
2886 local $SIG{PIPE} = 'IGNORE';
2888 my $oldAutoCommit = $FS::UID::AutoCommit;
2889 local $FS::UID::AutoCommit = 0;
2892 warn "$me acquiring lock on customer ". $self->custnum. "\n"
2895 $self->select_for_update; #mutex
2897 warn "$me running pre-bill events for customer ". $self->custnum. "\n"
2900 my $error = $self->do_cust_event(
2901 'debug' => ( $options{'debug'} || 0 ),
2902 'time' => $invoice_time,
2903 'check_freq' => $options{'check_freq'},
2904 'stage' => 'pre-bill',
2907 $dbh->rollback if $oldAutoCommit;
2911 warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
2914 #keep auto-charge and non-auto-charge line items separate
2915 my @passes = ( '', 'no_auto' );
2917 my %cust_bill_pkg = map { $_ => [] } @passes;
2920 # find the packages which are due for billing, find out how much they are
2921 # & generate invoice database.
2924 my %total_setup = map { my $z = 0; $_ => \$z; } @passes;
2925 my %total_recur = map { my $z = 0; $_ => \$z; } @passes;
2927 my %taxlisthash = map { $_ => {} } @passes;
2929 my @precommit_hooks = ();
2931 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
2932 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2934 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2936 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2938 #? to avoid use of uninitialized value errors... ?
2939 $cust_pkg->setfield('bill', '')
2940 unless defined($cust_pkg->bill);
2942 #my $part_pkg = $cust_pkg->part_pkg;
2944 my $real_pkgpart = $cust_pkg->pkgpart;
2945 my %hash = $cust_pkg->hash;
2947 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2949 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2951 my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
2954 $self->_make_lines( 'part_pkg' => $part_pkg,
2955 'cust_pkg' => $cust_pkg,
2956 'precommit_hooks' => \@precommit_hooks,
2957 'line_items' => $cust_bill_pkg{$pass},
2958 'setup' => $total_setup{$pass},
2959 'recur' => $total_recur{$pass},
2960 'tax_matrix' => $taxlisthash{$pass},
2962 'real_pkgpart' => $real_pkgpart,
2963 'options' => \%options,
2966 $dbh->rollback if $oldAutoCommit;
2970 } #foreach my $part_pkg
2972 } #foreach my $cust_pkg
2974 #if the customer isn't on an automatic payby, everything can go on a single
2976 #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
2977 #merge everything into one list
2980 foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
2982 my @cust_bill_pkg = @{ $cust_bill_pkg{$pass} };
2984 next unless @cust_bill_pkg; #don't create an invoice w/o line items
2986 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2987 !$conf->exists('postal_invoice-recurring_only')
2991 my $postal_pkg = $self->charge_postal_fee();
2992 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2994 $dbh->rollback if $oldAutoCommit;
2995 return "can't charge postal invoice fee for customer ".
2996 $self->custnum. ": $postal_pkg";
2998 } elsif ( $postal_pkg ) {
3000 my $real_pkgpart = $postal_pkg->pkgpart;
3001 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
3002 my %postal_options = %options;
3003 delete $postal_options{cancel};
3005 $self->_make_lines( 'part_pkg' => $part_pkg,
3006 'cust_pkg' => $postal_pkg,
3007 'precommit_hooks' => \@precommit_hooks,
3008 'line_items' => \@cust_bill_pkg,
3009 'setup' => $total_setup{$pass},
3010 'recur' => $total_recur{$pass},
3011 'tax_matrix' => $taxlisthash{$pass},
3013 'real_pkgpart' => $real_pkgpart,
3014 'options' => \%postal_options,
3017 $dbh->rollback if $oldAutoCommit;
3026 my $listref_or_error =
3027 $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
3029 unless ( ref( $listref_or_error ) ) {
3030 $dbh->rollback if $oldAutoCommit;
3031 return $listref_or_error;
3034 foreach my $taxline ( @$listref_or_error ) {
3035 ${ $total_setup{$pass} } =
3036 sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
3037 push @cust_bill_pkg, $taxline;
3040 #add tax adjustments
3041 warn "adding tax adjustments...\n" if $DEBUG > 2;
3042 foreach my $cust_tax_adjustment (
3043 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
3049 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
3051 my $itemdesc = $cust_tax_adjustment->taxname;
3052 $itemdesc = '' if $itemdesc eq 'Tax';
3054 push @cust_bill_pkg, new FS::cust_bill_pkg {
3060 'itemdesc' => $itemdesc,
3061 'itemcomment' => $cust_tax_adjustment->comment,
3062 'cust_tax_adjustment' => $cust_tax_adjustment,
3063 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3068 my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
3070 my @cust_bill = $self->cust_bill;
3071 my $balance = $self->balance;
3072 my $previous_balance = scalar(@cust_bill)
3073 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
3076 $previous_balance += $cust_bill[$#cust_bill]->charged
3077 if scalar(@cust_bill);
3078 #my $balance_adjustments =
3079 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
3081 #create the new invoice
3082 my $cust_bill = new FS::cust_bill ( {
3083 'custnum' => $self->custnum,
3084 '_date' => ( $invoice_time ),
3085 'charged' => $charged,
3086 'billing_balance' => $balance,
3087 'previous_balance' => $previous_balance,
3088 'invoice_terms' => $options{'invoice_terms'},
3090 $error = $cust_bill->insert;
3092 $dbh->rollback if $oldAutoCommit;
3093 return "can't create invoice for customer #". $self->custnum. ": $error";
3096 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
3097 $cust_bill_pkg->invnum($cust_bill->invnum);
3098 my $error = $cust_bill_pkg->insert;
3100 $dbh->rollback if $oldAutoCommit;
3101 return "can't create invoice line item: $error";
3105 } #foreach my $pass ( keys %cust_bill_pkg )
3107 foreach my $hook ( @precommit_hooks ) {
3109 &{$hook}; #($self) ?
3112 $dbh->rollback if $oldAutoCommit;
3113 return "$@ running precommit hook $hook\n";
3117 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3121 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
3123 This is a weird one. Perhaps it should not even be exposed.
3125 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
3126 Usually used internally by bill method B<bill>.
3128 If there is an error, returns the error, otherwise returns reference to a
3129 list of line items suitable for insertion.
3135 An array ref of the line items being billed.
3139 A strange beast. The keys to this hash are internal identifiers consisting
3140 of the name of the tax object type, a space, and its unique identifier ( e.g.
3141 'cust_main_county 23' ). The values of the hash are listrefs. The first
3142 item in the list is the tax object. The remaining items are either line
3143 items or floating point values (currency amounts).
3145 The taxes are calculated on this entity. Calculated exemption records are
3146 transferred to the LINEITEMREF items on the assumption that they are related.
3152 This specifies the date appearing on the associated invoice. Some
3153 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
3158 sub calculate_taxes {
3159 my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
3161 my @tax_line_items = ();
3163 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
3165 # keys are tax names (as printed on invoices / itemdesc )
3166 # values are listrefs of taxlisthash keys (internal identifiers)
3169 # keys are taxlisthash keys (internal identifiers)
3170 # values are (cumulative) amounts
3173 # keys are taxlisthash keys (internal identifiers)
3174 # values are listrefs of cust_bill_pkg_tax_location hashrefs
3175 my %tax_location = ();
3177 # keys are taxlisthash keys (internal identifiers)
3178 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
3179 my %tax_rate_location = ();
3181 foreach my $tax ( keys %$taxlisthash ) {
3182 my $tax_object = shift @{ $taxlisthash->{$tax} };
3183 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
3184 warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
3185 my $hashref_or_error =
3186 $tax_object->taxline( $taxlisthash->{$tax},
3187 'custnum' => $self->custnum,
3188 'invoice_time' => $invoice_time
3190 return $hashref_or_error unless ref($hashref_or_error);
3192 unshift @{ $taxlisthash->{$tax} }, $tax_object;
3194 my $name = $hashref_or_error->{'name'};
3195 my $amount = $hashref_or_error->{'amount'};
3197 #warn "adding $amount as $name\n";
3198 $taxname{ $name } ||= [];
3199 push @{ $taxname{ $name } }, $tax;
3201 $tax{ $tax } += $amount;
3203 $tax_location{ $tax } ||= [];
3204 if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
3205 push @{ $tax_location{ $tax } },
3207 'taxnum' => $tax_object->taxnum,
3208 'taxtype' => ref($tax_object),
3209 'pkgnum' => $tax_object->get('pkgnum'),
3210 'locationnum' => $tax_object->get('locationnum'),
3211 'amount' => sprintf('%.2f', $amount ),
3215 $tax_rate_location{ $tax } ||= [];
3216 if ( ref($tax_object) eq 'FS::tax_rate' ) {
3217 my $taxratelocationnum =
3218 $tax_object->tax_rate_location->taxratelocationnum;
3219 push @{ $tax_rate_location{ $tax } },
3221 'taxnum' => $tax_object->taxnum,
3222 'taxtype' => ref($tax_object),
3223 'amount' => sprintf('%.2f', $amount ),
3224 'locationtaxid' => $tax_object->location,
3225 'taxratelocationnum' => $taxratelocationnum,
3231 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
3232 my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
3233 foreach my $tax ( keys %$taxlisthash ) {
3234 foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
3235 next unless ref($_) eq 'FS::cust_bill_pkg';
3237 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
3238 splice( @{ $_->_cust_tax_exempt_pkg } );
3242 #consolidate and create tax line items
3243 warn "consolidating and generating...\n" if $DEBUG > 2;
3244 foreach my $taxname ( keys %taxname ) {
3247 my @cust_bill_pkg_tax_location = ();
3248 my @cust_bill_pkg_tax_rate_location = ();
3249 warn "adding $taxname\n" if $DEBUG > 1;
3250 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
3251 next if $seen{$taxitem}++;
3252 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
3253 $tax += $tax{$taxitem};
3254 push @cust_bill_pkg_tax_location,
3255 map { new FS::cust_bill_pkg_tax_location $_ }
3256 @{ $tax_location{ $taxitem } };
3257 push @cust_bill_pkg_tax_rate_location,
3258 map { new FS::cust_bill_pkg_tax_rate_location $_ }
3259 @{ $tax_rate_location{ $taxitem } };
3263 $tax = sprintf('%.2f', $tax );
3265 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
3271 if ( $pkg_category and
3272 $conf->config('invoice_latexsummary') ||
3273 $conf->config('invoice_htmlsummary')
3277 my %hash = ( 'section' => $pkg_category->categoryname );
3278 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3282 push @tax_line_items, new FS::cust_bill_pkg {
3288 'itemdesc' => $taxname,
3289 'display' => \@display,
3290 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3291 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
3300 my ($self, %params) = @_;
3302 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
3303 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
3304 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
3305 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
3306 my $total_setup = $params{setup} or die "no setup accumulator specified";
3307 my $total_recur = $params{recur} or die "no recur accumulator specified";
3308 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
3309 my $time = $params{'time'} or die "no time specified";
3310 my (%options) = %{$params{options}};
3313 my $real_pkgpart = $params{real_pkgpart};
3314 my %hash = $cust_pkg->hash;
3315 my $old_cust_pkg = new FS::cust_pkg \%hash;
3321 $cust_pkg->pkgpart($part_pkg->pkgpart);
3329 if ( $options{'resetup'}
3330 || ( ! $cust_pkg->setup
3331 && ( ! $cust_pkg->start_date
3332 || $cust_pkg->start_date <= $time
3334 && ( ! $conf->exists('disable_setup_suspended_pkgs')
3335 || ( $conf->exists('disable_setup_suspended_pkgs') &&
3336 ! $cust_pkg->getfield('susp')
3343 warn " bill setup\n" if $DEBUG > 1;
3346 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
3347 return "$@ running calc_setup for $cust_pkg\n"
3350 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
3352 $cust_pkg->setfield('setup', $time)
3353 unless $cust_pkg->setup;
3354 #do need it, but it won't get written to the db
3355 #|| $cust_pkg->pkgpart != $real_pkgpart;
3357 $cust_pkg->setfield('start_date', '')
3358 if $cust_pkg->start_date;
3363 # bill recurring fee
3366 #XXX unit stuff here too
3370 if ( ! $cust_pkg->get('susp')
3371 and ! $cust_pkg->get('start_date')
3372 and ( $part_pkg->getfield('freq') ne '0'
3373 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3375 || ( $part_pkg->plan eq 'voip_cdr'
3376 && $part_pkg->option('bill_every_call')
3378 || ( $options{cancel} )
3381 # XXX should this be a package event? probably. events are called
3382 # at collection time at the moment, though...
3383 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
3384 if $part_pkg->can('reset_usage');
3385 #don't want to reset usage just cause we want a line item??
3386 #&& $part_pkg->pkgpart == $real_pkgpart;
3388 warn " bill recur\n" if $DEBUG > 1;
3391 # XXX shared with $recur_prog
3392 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
3396 #over two params! lets at least switch to a hashref for the rest...
3397 my $increment_next_bill = ( $part_pkg->freq ne '0'
3398 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3399 && !$options{cancel}
3401 my %param = ( 'precommit_hooks' => $precommit_hooks,
3402 'increment_next_bill' => $increment_next_bill,
3403 'discounts' => \@discounts,
3406 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
3407 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
3408 return "$@ running $method for $cust_pkg\n"
3411 if ( $increment_next_bill ) {
3413 my $next_bill = $part_pkg->add_freq($sdate);
3414 return "unparsable frequency: ". $part_pkg->freq
3415 if $next_bill == -1;
3417 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
3418 # only for figuring next bill date, nothing else, so, reset $sdate again
3420 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
3421 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
3422 $cust_pkg->last_bill($sdate);
3424 $cust_pkg->setfield('bill', $next_bill );
3430 warn "\$setup is undefined" unless defined($setup);
3431 warn "\$recur is undefined" unless defined($recur);
3432 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
3435 # If there's line items, create em cust_bill_pkg records
3436 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
3441 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
3442 # hmm.. and if just the options are modified in some weird price plan?
3444 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
3447 my $error = $cust_pkg->replace( $old_cust_pkg,
3448 'options' => { $cust_pkg->options },
3450 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
3451 if $error; #just in case
3454 $setup = sprintf( "%.2f", $setup );
3455 $recur = sprintf( "%.2f", $recur );
3456 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
3457 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3459 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3460 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3463 if ( $setup != 0 || $recur != 0 ) {
3465 warn " charges (setup=$setup, recur=$recur); adding line items\n"
3468 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3470 warn " adding customer package invoice detail: $_\n"
3471 foreach @cust_pkg_detail;
3473 push @details, @cust_pkg_detail;
3475 my $cust_bill_pkg = new FS::cust_bill_pkg {
3476 'pkgnum' => $cust_pkg->pkgnum,
3478 'unitsetup' => $unitsetup,
3480 'unitrecur' => $unitrecur,
3481 'quantity' => $cust_pkg->quantity,
3482 'details' => \@details,
3483 'discounts' => \@discounts,
3484 'hidden' => $part_pkg->hidden,
3487 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3488 $cust_bill_pkg->sdate( $hash{last_bill} );
3489 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
3490 $cust_bill_pkg->edate( $time ) if $options{cancel};
3491 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3492 $cust_bill_pkg->sdate( $sdate );
3493 $cust_bill_pkg->edate( $cust_pkg->bill );
3494 #$cust_bill_pkg->edate( $time ) if $options{cancel};
3497 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3498 unless $part_pkg->pkgpart == $real_pkgpart;
3500 $$total_setup += $setup;
3501 $$total_recur += $recur;
3508 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3509 return $error if $error;
3511 push @$cust_bill_pkgs, $cust_bill_pkg;
3513 } #if $setup != 0 || $recur != 0
3523 my $part_pkg = shift;
3524 my $taxlisthash = shift;
3525 my $cust_bill_pkg = shift;
3526 my $cust_pkg = shift;
3527 my $invoice_time = shift;
3528 my $real_pkgpart = shift;
3529 my $options = shift;
3531 my %cust_bill_pkg = ();
3535 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3536 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3537 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3538 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3540 if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3542 if ( $conf->exists('enable_taxproducts')
3543 && ( scalar($part_pkg->part_pkg_taxoverride)
3544 || $part_pkg->has_taxproduct
3549 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3550 return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3553 foreach my $class (@classes) {
3554 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3555 return $err_or_ref unless ref($err_or_ref);
3556 $taxes{$class} = $err_or_ref;
3559 unless (exists $taxes{''}) {
3560 my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3561 return $err_or_ref unless ref($err_or_ref);
3562 $taxes{''} = $err_or_ref;
3567 my @loc_keys = qw( city county state country );
3569 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3570 my $cust_location = $cust_pkg->cust_location;
3571 %taxhash = map { $_ => $cust_location->$_() } @loc_keys;
3574 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3577 %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3580 $taxhash{'taxclass'} = $part_pkg->taxclass;
3583 my %taxhash_elim = %taxhash;
3584 my @elim = qw( city county state );
3587 #first try a match with taxclass
3588 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3590 if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
3591 #then try a match without taxclass
3592 my %no_taxclass = %taxhash_elim;
3593 $no_taxclass{ 'taxclass' } = '';
3594 @taxes = qsearch( 'cust_main_county', \%no_taxclass );
3597 $taxhash_elim{ shift(@elim) } = '';
3599 } while ( !scalar(@taxes) && scalar(@elim) );
3601 @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3603 if $self->cust_main_exemption; #just to be safe
3605 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3607 $_->set('pkgnum', $cust_pkg->pkgnum );
3608 $_->set('locationnum', $cust_pkg->locationnum );
3612 $taxes{''} = [ @taxes ];
3613 $taxes{'setup'} = [ @taxes ];
3614 $taxes{'recur'} = [ @taxes ];
3615 $taxes{$_} = [ @taxes ] foreach (@classes);
3617 # # maybe eliminate this entirely, along with all the 0% records
3618 # unless ( @taxes ) {
3620 # "fatal: can't find tax rate for state/county/country/taxclass ".
3621 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
3624 } #if $conf->exists('enable_taxproducts') ...
3629 my $separate = $conf->exists('separate_usage');
3630 my $usage_mandate = $cust_pkg->part_pkg->option('usage_mandate', 'Hush!');
3631 if ( $separate || $cust_bill_pkg->hidden || $usage_mandate ) {
3633 my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3634 my %hash = $cust_bill_pkg->hidden # maybe for all bill linked?
3635 ? ( 'section' => $temp_pkg->part_pkg->categoryname )
3638 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
3639 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
3641 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3642 push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3644 push @display, new FS::cust_bill_pkg_display
3647 ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3651 if ($separate && $section && $summary) {
3652 push @display, new FS::cust_bill_pkg_display { type => 'U',
3657 if ($usage_mandate || $section && $summary) {
3658 $hash{post_total} = 'Y';
3661 $hash{section} = $section if ($separate || $usage_mandate);
3662 push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3665 $cust_bill_pkg->set('display', \@display);
3667 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3668 foreach my $key (keys %tax_cust_bill_pkg) {
3669 my @taxes = @{ $taxes{$key} || [] };
3670 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3672 my %localtaxlisthash = ();
3673 foreach my $tax ( @taxes ) {
3675 my $taxname = ref( $tax ). ' '. $tax->taxnum;
3676 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3677 # ' locationnum'. $cust_pkg->locationnum
3678 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3680 $taxlisthash->{ $taxname } ||= [ $tax ];
3681 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
3683 $localtaxlisthash{ $taxname } ||= [ $tax ];
3684 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
3688 warn "finding taxed taxes...\n" if $DEBUG > 2;
3689 foreach my $tax ( keys %localtaxlisthash ) {
3690 my $tax_object = shift @{ $localtaxlisthash{$tax} };
3691 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3693 next unless $tax_object->can('tax_on_tax');
3695 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3696 my $totname = ref( $tot ). ' '. $tot->taxnum;
3698 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3700 next unless exists( $localtaxlisthash{ $totname } ); # only increase
3702 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3703 my $hashref_or_error =
3704 $tax_object->taxline( $localtaxlisthash{$tax},
3705 'custnum' => $self->custnum,
3706 'invoice_time' => $invoice_time,
3708 return $hashref_or_error
3709 unless ref($hashref_or_error);
3711 $taxlisthash->{ $totname } ||= [ $tot ];
3712 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
3724 my $part_pkg = shift;
3728 my $geocode = $self->geocode('cch');
3730 my @taxclassnums = map { $_->taxclassnum }
3731 $part_pkg->part_pkg_taxoverride($class);
3733 unless (@taxclassnums) {
3734 @taxclassnums = map { $_->taxclassnum }
3735 grep { $_->taxable eq 'Y' }
3736 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3738 warn "Found taxclassnum values of ". join(',', @taxclassnums)
3743 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3745 @taxes = qsearch({ 'table' => 'tax_rate',
3746 'hashref' => { 'geocode' => $geocode, },
3747 'extra_sql' => $extra_sql,
3749 if scalar(@taxclassnums);
3751 warn "Found taxes ".
3752 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
3759 =item collect [ HASHREF | OPTION => VALUE ... ]
3761 (Attempt to) collect money for this customer's outstanding invoices (see
3762 L<FS::cust_bill>). Usually used after the bill method.
3764 Actions are now triggered by billing events; see L<FS::part_event> and the
3765 billing events web interface. Old-style invoice events (see
3766 L<FS::part_bill_event>) have been deprecated.
3768 If there is an error, returns the error, otherwise returns false.
3770 Options are passed as name-value pairs.
3772 Currently available options are:
3778 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.
3782 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3786 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3790 set true to surpress email card/ACH decline notices.
3794 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)
3800 # allows for one time override of normal customer billing method
3805 my( $self, %options ) = @_;
3806 my $invoice_time = $options{'invoice_time'} || time;
3809 local $SIG{HUP} = 'IGNORE';
3810 local $SIG{INT} = 'IGNORE';
3811 local $SIG{QUIT} = 'IGNORE';
3812 local $SIG{TERM} = 'IGNORE';
3813 local $SIG{TSTP} = 'IGNORE';
3814 local $SIG{PIPE} = 'IGNORE';
3816 my $oldAutoCommit = $FS::UID::AutoCommit;
3817 local $FS::UID::AutoCommit = 0;
3820 $self->select_for_update; #mutex
3823 my $balance = $self->balance;
3824 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3827 if ( exists($options{'retry_card'}) ) {
3828 carp 'retry_card option passed to collect is deprecated; use retry';
3829 $options{'retry'} ||= $options{'retry_card'};
3831 if ( exists($options{'retry'}) && $options{'retry'} ) {
3832 my $error = $self->retry_realtime;
3834 $dbh->rollback if $oldAutoCommit;
3839 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3841 #never want to roll back an event just because it returned an error
3842 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3844 $self->do_cust_event(
3845 'debug' => ( $options{'debug'} || 0 ),
3846 'time' => $invoice_time,
3847 'check_freq' => $options{'check_freq'},
3848 'stage' => 'collect',
3853 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3855 Runs billing events; see L<FS::part_event> and the billing events web
3858 If there is an error, returns the error, otherwise returns false.
3860 Options are passed as name-value pairs.
3862 Currently available options are:
3868 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.
3872 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3876 "collect" (the default) or "pre-bill"
3880 set true to surpress email card/ACH decline notices.
3884 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)
3890 # allows for one time override of normal customer billing method
3894 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3897 my( $self, %options ) = @_;
3898 my $time = $options{'time'} || time;
3901 local $SIG{HUP} = 'IGNORE';
3902 local $SIG{INT} = 'IGNORE';
3903 local $SIG{QUIT} = 'IGNORE';
3904 local $SIG{TERM} = 'IGNORE';
3905 local $SIG{TSTP} = 'IGNORE';
3906 local $SIG{PIPE} = 'IGNORE';
3908 my $oldAutoCommit = $FS::UID::AutoCommit;
3909 local $FS::UID::AutoCommit = 0;
3912 $self->select_for_update; #mutex
3915 my $balance = $self->balance;
3916 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
3919 # if ( exists($options{'retry_card'}) ) {
3920 # carp 'retry_card option passed to collect is deprecated; use retry';
3921 # $options{'retry'} ||= $options{'retry_card'};
3923 # if ( exists($options{'retry'}) && $options{'retry'} ) {
3924 # my $error = $self->retry_realtime;
3926 # $dbh->rollback if $oldAutoCommit;
3931 # false laziness w/pay_batch::import_results
3933 my $due_cust_event = $self->due_cust_event(
3934 'debug' => ( $options{'debug'} || 0 ),
3936 'check_freq' => $options{'check_freq'},
3937 'stage' => ( $options{'stage'} || 'collect' ),
3939 unless( ref($due_cust_event) ) {
3940 $dbh->rollback if $oldAutoCommit;
3941 return $due_cust_event;
3944 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3945 #never want to roll back an event just because it or a different one
3947 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3949 foreach my $cust_event ( @$due_cust_event ) {
3953 #re-eval event conditions (a previous event could have changed things)
3954 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
3955 #don't leave stray "new/locked" records around
3956 my $error = $cust_event->delete;
3957 return $error if $error;
3962 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
3963 warn " running cust_event ". $cust_event->eventnum. "\n"
3966 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
3967 if ( my $error = $cust_event->do_event() ) {
3968 #XXX wtf is this? figure out a proper dealio with return value
3980 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
3982 Inserts database records for and returns an ordered listref of new events due
3983 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
3984 events are due, an empty listref is returned. If there is an error, returns a
3985 scalar error message.
3987 To actually run the events, call each event's test_condition method, and if
3988 still true, call the event's do_event method.
3990 Options are passed as a hashref or as a list of name-value pairs. Available
3997 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.
4001 "collect" (the default) or "pre-bill"
4005 "Current time" for the events.
4009 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)
4013 Only return events for the specified eventtable (by default, events of all eventtables are returned)
4017 Explicitly pass the objects to be tested (typically used with eventtable).
4021 Set to true to return the objects, but not actually insert them into the
4028 sub due_cust_event {
4030 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
4033 #my $DEBUG = $opt{'debug'}
4034 local($DEBUG) = $opt{'debug'}
4035 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
4037 warn "$me due_cust_event called with options ".
4038 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
4041 $opt{'time'} ||= time;
4043 local $SIG{HUP} = 'IGNORE';
4044 local $SIG{INT} = 'IGNORE';
4045 local $SIG{QUIT} = 'IGNORE';
4046 local $SIG{TERM} = 'IGNORE';
4047 local $SIG{TSTP} = 'IGNORE';
4048 local $SIG{PIPE} = 'IGNORE';
4050 my $oldAutoCommit = $FS::UID::AutoCommit;
4051 local $FS::UID::AutoCommit = 0;
4054 $self->select_for_update #mutex
4055 unless $opt{testonly};
4058 # find possible events (initial search)
4061 my @cust_event = ();
4063 my @eventtable = $opt{'eventtable'}
4064 ? ( $opt{'eventtable'} )
4065 : FS::part_event->eventtables_runorder;
4067 foreach my $eventtable ( @eventtable ) {
4070 if ( $opt{'objects'} ) {
4072 @objects = @{ $opt{'objects'} };
4076 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
4077 @objects = ( $eventtable eq 'cust_main' )
4079 : ( $self->$eventtable() );
4083 my @e_cust_event = ();
4085 my $cross = "CROSS JOIN $eventtable";
4086 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
4087 unless $eventtable eq 'cust_main';
4089 foreach my $object ( @objects ) {
4091 #this first search uses the condition_sql magic for optimization.
4092 #the more possible events we can eliminate in this step the better
4094 my $cross_where = '';
4095 my $pkey = $object->primary_key;
4096 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
4098 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
4100 FS::part_event_condition->where_conditions_sql( $eventtable,
4101 'time'=>$opt{'time'}
4103 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
4105 $extra_sql = "AND $extra_sql" if $extra_sql;
4107 #here is the agent virtualization
4108 $extra_sql .= " AND ( part_event.agentnum IS NULL
4109 OR part_event.agentnum = ". $self->agentnum. ' )';
4111 $extra_sql .= " $order";
4113 warn "searching for events for $eventtable ". $object->$pkey. "\n"
4114 if $opt{'debug'} > 2;
4115 my @part_event = qsearch( {
4116 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
4117 'select' => 'part_event.*',
4118 'table' => 'part_event',
4119 'addl_from' => "$cross $join",
4120 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
4121 'eventtable' => $eventtable,
4124 'extra_sql' => "AND $cross_where $extra_sql",
4128 my $pkey = $object->primary_key;
4129 warn " ". scalar(@part_event).
4130 " possible events found for $eventtable ". $object->$pkey(). "\n";
4133 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
4137 warn " ". scalar(@e_cust_event).
4138 " subtotal possible cust events found for $eventtable\n"
4141 push @cust_event, @e_cust_event;
4145 warn " ". scalar(@cust_event).
4146 " total possible cust events found in initial search\n"
4154 $opt{stage} ||= 'collect';
4156 grep { my $stage = $_->part_event->event_stage;
4157 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
4167 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
4168 'stats_hashref' => \%unsat ),
4171 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
4174 warn " invalid conditions not eliminated with condition_sql:\n".
4175 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
4176 if keys %unsat && $DEBUG; # > 1;
4182 unless( $opt{testonly} ) {
4183 foreach my $cust_event ( @cust_event ) {
4185 my $error = $cust_event->insert();
4187 $dbh->rollback if $oldAutoCommit;
4194 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4200 warn " returning events: ". Dumper(@cust_event). "\n"
4207 =item retry_realtime
4209 Schedules realtime / batch credit card / electronic check / LEC billing
4210 events for for retry. Useful if card information has changed or manual
4211 retry is desired. The 'collect' method must be called to actually retry
4214 Implementation details: For either this customer, or for each of this
4215 customer's open invoices, changes the status of the first "done" (with
4216 statustext error) realtime processing event to "failed".
4220 sub retry_realtime {
4223 local $SIG{HUP} = 'IGNORE';
4224 local $SIG{INT} = 'IGNORE';
4225 local $SIG{QUIT} = 'IGNORE';
4226 local $SIG{TERM} = 'IGNORE';
4227 local $SIG{TSTP} = 'IGNORE';
4228 local $SIG{PIPE} = 'IGNORE';
4230 my $oldAutoCommit = $FS::UID::AutoCommit;
4231 local $FS::UID::AutoCommit = 0;
4234 #a little false laziness w/due_cust_event (not too bad, really)
4236 my $join = FS::part_event_condition->join_conditions_sql;
4237 my $order = FS::part_event_condition->order_conditions_sql;
4240 . join ( ' OR ' , map {
4241 "( part_event.eventtable = " . dbh->quote($_)
4242 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
4243 } FS::part_event->eventtables)
4246 #here is the agent virtualization
4247 my $agent_virt = " ( part_event.agentnum IS NULL
4248 OR part_event.agentnum = ". $self->agentnum. ' )';
4250 #XXX this shouldn't be hardcoded, actions should declare it...
4251 my @realtime_events = qw(
4252 cust_bill_realtime_card
4253 cust_bill_realtime_check
4254 cust_bill_realtime_lec
4258 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
4263 my @cust_event = qsearchs({
4264 'table' => 'cust_event',
4265 'select' => 'cust_event.*',
4266 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
4267 'hashref' => { 'status' => 'done' },
4268 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
4269 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
4272 my %seen_invnum = ();
4273 foreach my $cust_event (@cust_event) {
4275 #max one for the customer, one for each open invoice
4276 my $cust_X = $cust_event->cust_X;
4277 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
4281 or $cust_event->part_event->eventtable eq 'cust_bill'
4284 my $error = $cust_event->retry;
4286 $dbh->rollback if $oldAutoCommit;
4287 return "error scheduling event for retry: $error";
4292 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4300 =item realtime_collect [ OPTION => VALUE ... ]
4302 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4303 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4304 gateway. See L<http://420.am/business-onlinepayment> and
4305 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4307 On failure returns an error message.
4309 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.
4311 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4313 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
4314 then it is deduced from the customer record.
4316 If no I<amount> is specified, then the customer balance is used.
4318 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4319 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4320 if set, will override the value from the customer record.
4322 I<description> is a free-text field passed to the gateway. It defaults to
4323 the value defined by the business-onlinepayment-description configuration
4324 option, or "Internet services" if that is unset.
4326 If an I<invnum> is specified, this payment (if successful) is applied to the
4327 specified invoice. If you don't specify an I<invnum> you might want to
4328 call the B<apply_payments> method or set the I<apply> option.
4330 I<apply> can be set to true to apply a resulting payment.
4332 I<quiet> can be set true to surpress email decline notices.
4334 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4335 resulting paynum, if any.
4337 I<payunique> is a unique identifier for this payment.
4339 I<session_id> is a session identifier associated with this payment.
4341 I<depend_jobnum> allows payment capture to unlock export jobs
4345 sub realtime_collect {
4346 my( $self, %options ) = @_;
4349 warn "$me realtime_collect:\n";
4350 warn " $_ => $options{$_}\n" foreach keys %options;
4353 $options{amount} = $self->balance unless exists( $options{amount} );
4354 $options{method} = FS::payby->payby2bop($self->payby)
4355 unless exists( $options{method} );
4357 return $self->realtime_bop({%options});
4361 =item realtime_bop { [ ARG => VALUE ... ] }
4363 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4364 via a Business::OnlinePayment realtime gateway. See
4365 L<http://420.am/business-onlinepayment> for supported gateways.
4367 Required arguments in the hashref are I<method>, and I<amount>
4369 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4371 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4373 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4374 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4375 if set, will override the value from the customer record.
4377 I<description> is a free-text field passed to the gateway. It defaults to
4378 the value defined by the business-onlinepayment-description configuration
4379 option, or "Internet services" if that is unset.
4381 If an I<invnum> is specified, this payment (if successful) is applied to the
4382 specified invoice. If you don't specify an I<invnum> you might want to
4383 call the B<apply_payments> method or set the I<apply> option.
4385 I<apply> can be set to true to apply a resulting payment.
4387 I<quiet> can be set true to surpress email decline notices.
4389 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4390 resulting paynum, if any.
4392 I<payunique> is a unique identifier for this payment.
4394 I<session_id> is a session identifier associated with this payment.
4396 I<depend_jobnum> allows payment capture to unlock export jobs
4398 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4402 # some helper routines
4403 sub _bop_recurring_billing {
4404 my( $self, %opt ) = @_;
4406 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
4408 if ( defined($method) && $method eq 'transaction_is_recur' ) {
4410 return 1 if $opt{'trans_is_recur'};
4414 my %hash = ( 'custnum' => $self->custnum,
4419 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4420 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4430 sub _payment_gateway {
4431 my ($self, $options) = @_;
4433 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4434 unless exists($options->{payment_gateway});
4436 $options->{payment_gateway};
4440 my ($self, $options) = @_;
4443 'login' => $options->{payment_gateway}->gateway_username,
4444 'password' => $options->{payment_gateway}->gateway_password,
4449 my ($self, $options) = @_;
4451 $options->{payment_gateway}->gatewaynum
4452 ? $options->{payment_gateway}->options
4453 : @{ $options->{payment_gateway}->get('options') };
4458 my ($self, $options) = @_;
4460 unless ( $options->{'description'} ) {
4461 if ( $conf->exists('business-onlinepayment-description') ) {
4462 my $dtempl = $conf->config('business-onlinepayment-description');
4464 my $agent = $self->agent->agent;
4466 $options->{'description'} = eval qq("$dtempl");
4468 $options->{'description'} = 'Internet services';
4472 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4473 $options->{invnum} ||= '';
4474 $options->{payname} = $self->payname unless exists( $options->{payname} );
4478 my ($self, $options) = @_;
4481 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4482 $content{customer_ip} = $payip if length($payip);
4484 $content{invoice_number} = $options->{'invnum'}
4485 if exists($options->{'invnum'}) && length($options->{'invnum'});
4487 $content{email_customer} =
4488 ( $conf->exists('business-onlinepayment-email_customer')
4489 || $conf->exists('business-onlinepayment-email-override') );
4491 my ($payname, $payfirst, $paylast);
4492 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
4493 ($payname = $options->{payname}) =~
4494 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4495 or return "Illegal payname $payname";
4496 ($payfirst, $paylast) = ($1, $2);
4498 $payfirst = $self->getfield('first');
4499 $paylast = $self->getfield('last');
4500 $payname = "$payfirst $paylast";
4503 $content{last_name} = $paylast;
4504 $content{first_name} = $payfirst;
4506 $content{name} = $payname;
4508 $content{address} = exists($options->{'address1'})
4509 ? $options->{'address1'}
4511 my $address2 = exists($options->{'address2'})
4512 ? $options->{'address2'}
4514 $content{address} .= ", ". $address2 if length($address2);
4516 $content{city} = exists($options->{city})
4519 $content{state} = exists($options->{state})
4522 $content{zip} = exists($options->{zip})
4525 $content{country} = exists($options->{country})
4526 ? $options->{country}
4529 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4530 $content{phone} = $self->daytime || $self->night;
4535 my %bop_method2payby = (
4545 if (ref($_[0]) eq 'HASH') {
4546 %options = %{$_[0]};
4548 my ( $method, $amount ) = ( shift, shift );
4550 $options{method} = $method;
4551 $options{amount} = $amount;
4555 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
4556 warn " $_ => $options{$_}\n" foreach keys %options;
4559 return $self->fake_bop(%options) if $options{'fake'};
4561 $self->_bop_defaults(\%options);
4564 # set trans_is_recur based on invnum if there is one
4567 my $trans_is_recur = 0;
4568 if ( $options{'invnum'} ) {
4570 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
4571 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
4574 map { $_->part_pkg }
4576 map { $_->cust_pkg }
4577 $cust_bill->cust_bill_pkg;
4580 if grep { $_->freq ne '0' } @part_pkg;
4588 my $payment_gateway = $self->_payment_gateway( \%options );
4589 my $namespace = $payment_gateway->gateway_namespace;
4591 eval "use $namespace";
4595 # check for banned credit card/ACH
4598 my $ban = qsearchs('banned_pay', {
4599 'payby' => $bop_method2payby{$options{method}},
4600 'payinfo' => md5_base64($options{payinfo}),
4602 return "Banned credit card" if $ban;
4608 my $bop_content = $self->_bop_content(\%options);
4609 return $bop_content unless ref($bop_content);
4611 my @invoicing_list = $self->invoicing_list_emailonly;
4612 if ( $conf->exists('emailinvoiceautoalways')
4613 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4614 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4615 push @invoicing_list, $self->all_emails;
4618 my $email = ($conf->exists('business-onlinepayment-email-override'))
4619 ? $conf->config('business-onlinepayment-email-override')
4620 : $invoicing_list[0];
4624 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
4626 $content{card_number} = $options{payinfo};
4627 $paydate = exists($options{'paydate'})
4628 ? $options{'paydate'}
4630 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4631 $content{expiration} = "$2/$1";
4633 my $paycvv = exists($options{'paycvv'})
4634 ? $options{'paycvv'}
4636 $content{cvv2} = $paycvv
4639 my $paystart_month = exists($options{'paystart_month'})
4640 ? $options{'paystart_month'}
4641 : $self->paystart_month;
4643 my $paystart_year = exists($options{'paystart_year'})
4644 ? $options{'paystart_year'}
4645 : $self->paystart_year;
4647 $content{card_start} = "$paystart_month/$paystart_year"
4648 if $paystart_month && $paystart_year;
4650 my $payissue = exists($options{'payissue'})
4651 ? $options{'payissue'}
4653 $content{issue_number} = $payissue if $payissue;
4655 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
4656 'trans_is_recur' => $trans_is_recur,
4660 $content{recurring_billing} = 'YES';
4661 $content{acct_code} = 'rebill'
4662 if $conf->exists('credit_card-recurring_billing_acct_code');
4665 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
4666 ( $content{account_number}, $content{routing_code} ) =
4667 split('@', $options{payinfo});
4668 $content{bank_name} = $options{payname};
4669 $content{bank_state} = exists($options{'paystate'})
4670 ? $options{'paystate'}
4671 : $self->getfield('paystate');
4672 $content{account_type} = exists($options{'paytype'})
4673 ? uc($options{'paytype'}) || 'CHECKING'
4674 : uc($self->getfield('paytype')) || 'CHECKING';
4675 $content{account_name} = $self->getfield('first'). ' '.
4676 $self->getfield('last');
4678 $content{customer_org} = $self->company ? 'B' : 'I';
4679 $content{state_id} = exists($options{'stateid'})
4680 ? $options{'stateid'}
4681 : $self->getfield('stateid');
4682 $content{state_id_state} = exists($options{'stateid_state'})
4683 ? $options{'stateid_state'}
4684 : $self->getfield('stateid_state');
4685 $content{customer_ssn} = exists($options{'ss'})
4688 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
4689 $content{phone} = $options{payinfo};
4690 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4697 # run transaction(s)
4700 my $balance = exists( $options{'balance'} )
4701 ? $options{'balance'}
4704 $self->select_for_update; #mutex ... just until we get our pending record in
4706 #the checks here are intended to catch concurrent payments
4707 #double-form-submission prevention is taken care of in cust_pay_pending::check
4710 return "The customer's balance has changed; $options{method} transaction aborted."
4711 if $self->balance < $balance;
4712 #&& $self->balance < $options{amount}; #might as well anyway?
4714 #also check and make sure there aren't *other* pending payments for this cust
4716 my @pending = qsearch('cust_pay_pending', {
4717 'custnum' => $self->custnum,
4718 'status' => { op=>'!=', value=>'done' }
4720 return "A payment is already being processed for this customer (".
4721 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4722 "); $options{method} transaction aborted."
4723 if scalar(@pending);
4725 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4727 my $cust_pay_pending = new FS::cust_pay_pending {
4728 'custnum' => $self->custnum,
4729 #'invnum' => $options{'invnum'},
4730 'paid' => $options{amount},
4732 'payby' => $bop_method2payby{$options{method}},
4733 'payinfo' => $options{payinfo},
4734 'paydate' => $paydate,
4735 'recurring_billing' => $content{recurring_billing},
4736 'pkgnum' => $options{'pkgnum'},
4738 'gatewaynum' => $payment_gateway->gatewaynum || '',
4739 'session_id' => $options{session_id} || '',
4740 'jobnum' => $options{depend_jobnum} || '',
4742 $cust_pay_pending->payunique( $options{payunique} )
4743 if defined($options{payunique}) && length($options{payunique});
4744 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4745 return $cpp_new_err if $cpp_new_err;
4747 my( $action1, $action2 ) =
4748 split( /\s*\,\s*/, $payment_gateway->gateway_action );
4750 my $transaction = new $namespace( $payment_gateway->gateway_module,
4751 $self->_bop_options(\%options),
4754 $transaction->content(
4755 'type' => $options{method},
4756 $self->_bop_auth(\%options),
4757 'action' => $action1,
4758 'description' => $options{'description'},
4759 'amount' => $options{amount},
4760 #'invoice_number' => $options{'invnum'},
4761 'customer_id' => $self->custnum,
4763 'reference' => $cust_pay_pending->paypendingnum, #for now
4768 $cust_pay_pending->status('pending');
4769 my $cpp_pending_err = $cust_pay_pending->replace;
4770 return $cpp_pending_err if $cpp_pending_err;
4773 my $BOP_TESTING = 0;
4774 my $BOP_TESTING_SUCCESS = 1;
4776 unless ( $BOP_TESTING ) {
4777 $transaction->test_transaction(1)
4778 if $conf->exists('business-onlinepayment-test_transaction');
4779 $transaction->submit();
4781 if ( $BOP_TESTING_SUCCESS ) {
4782 $transaction->is_success(1);
4783 $transaction->authorization('fake auth');
4785 $transaction->is_success(0);
4786 $transaction->error_message('fake failure');
4790 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4792 return { reference => $cust_pay_pending->paypendingnum,
4793 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
4795 } elsif ( $transaction->is_success() && $action2 ) {
4797 $cust_pay_pending->status('authorized');
4798 my $cpp_authorized_err = $cust_pay_pending->replace;
4799 return $cpp_authorized_err if $cpp_authorized_err;
4801 my $auth = $transaction->authorization;
4802 my $ordernum = $transaction->can('order_number')
4803 ? $transaction->order_number
4807 new Business::OnlinePayment( $payment_gateway->gateway_module,
4808 $self->_bop_options(\%options),
4813 type => $options{method},
4815 $self->_bop_auth(\%options),
4816 order_number => $ordernum,
4817 amount => $options{amount},
4818 authorization => $auth,
4819 description => $options{'description'},
4822 foreach my $field (qw( authorization_source_code returned_ACI
4823 transaction_identifier validation_code
4824 transaction_sequence_num local_transaction_date
4825 local_transaction_time AVS_result_code )) {
4826 $capture{$field} = $transaction->$field() if $transaction->can($field);
4829 $capture->content( %capture );
4831 $capture->test_transaction(1)
4832 if $conf->exists('business-onlinepayment-test_transaction');
4835 unless ( $capture->is_success ) {
4836 my $e = "Authorization successful but capture failed, custnum #".
4837 $self->custnum. ': '. $capture->result_code.
4838 ": ". $capture->error_message;
4846 # remove paycvv after initial transaction
4849 #false laziness w/misc/process/payment.cgi - check both to make sure working
4851 if ( defined $self->dbdef_table->column('paycvv')
4852 && length($self->paycvv)
4853 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
4855 my $error = $self->remove_cvv;
4857 warn "WARNING: error removing cvv: $error\n";
4866 if ( $transaction->can('card_token') && $transaction->card_token ) {
4868 $self->card_token($transaction->card_token);
4870 if ( $options{'payinfo'} eq $self->payinfo ) {
4871 $self->payinfo($transaction->card_token);
4872 my $error = $self->replace;
4874 warn "WARNING: error storing token: $error, but proceeding anyway\n";
4884 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
4896 if (ref($_[0]) eq 'HASH') {
4897 %options = %{$_[0]};
4899 my ( $method, $amount ) = ( shift, shift );
4901 $options{method} = $method;
4902 $options{amount} = $amount;
4905 if ( $options{'fake_failure'} ) {
4906 return "Error: No error; test failure requested with fake_failure";
4910 #if ( $payment_gateway->gatewaynum ) { # agent override
4911 # $paybatch = $payment_gateway->gatewaynum. '-';
4914 #$paybatch .= "$processor:". $transaction->authorization;
4916 #$paybatch .= ':'. $transaction->order_number
4917 # if $transaction->can('order_number')
4918 # && length($transaction->order_number);
4920 my $paybatch = 'FakeProcessor:54:32';
4922 my $cust_pay = new FS::cust_pay ( {
4923 'custnum' => $self->custnum,
4924 'invnum' => $options{'invnum'},
4925 'paid' => $options{amount},
4927 'payby' => $bop_method2payby{$options{method}},
4928 #'payinfo' => $payinfo,
4929 'payinfo' => '4111111111111111',
4930 'paybatch' => $paybatch,
4931 #'paydate' => $paydate,
4932 'paydate' => '2012-05-01',
4934 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
4936 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4939 $cust_pay->invnum(''); #try again with no specific invnum
4940 my $error2 = $cust_pay->insert( $options{'manual'} ?
4941 ( 'manual' => 1 ) : ()
4944 # gah, even with transactions.
4945 my $e = 'WARNING: Card/ACH debited but database not updated - '.
4946 "error inserting (fake!) payment: $error2".
4947 " (previously tried insert with invnum #$options{'invnum'}" .
4954 if ( $options{'paynum_ref'} ) {
4955 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4958 return ''; #no error
4963 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
4965 # Wraps up processing of a realtime credit card, ACH (electronic check) or
4966 # phone bill transaction.
4968 sub _realtime_bop_result {
4969 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
4971 warn "$me _realtime_bop_result: pending transaction ".
4972 $cust_pay_pending->paypendingnum. "\n";
4973 warn " $_ => $options{$_}\n" foreach keys %options;
4976 my $payment_gateway = $options{payment_gateway}
4977 or return "no payment gateway in arguments to _realtime_bop_result";
4979 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
4980 my $cpp_captured_err = $cust_pay_pending->replace;
4981 return $cpp_captured_err if $cpp_captured_err;
4983 if ( $transaction->is_success() ) {
4986 if ( $payment_gateway->gatewaynum ) { # agent override
4987 $paybatch = $payment_gateway->gatewaynum. '-';
4990 $paybatch .= $payment_gateway->gateway_module. ":".
4991 $transaction->authorization;
4993 $paybatch .= ':'. $transaction->order_number
4994 if $transaction->can('order_number')
4995 && length($transaction->order_number);
4997 my $cust_pay = new FS::cust_pay ( {
4998 'custnum' => $self->custnum,
4999 'invnum' => $options{'invnum'},
5000 'paid' => $cust_pay_pending->paid,
5002 'payby' => $cust_pay_pending->payby,
5003 'payinfo' => $options{'payinfo'},
5004 'paybatch' => $paybatch,
5005 'paydate' => $cust_pay_pending->paydate,
5006 'pkgnum' => $cust_pay_pending->pkgnum,
5008 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
5009 $cust_pay->payunique( $options{payunique} )
5010 if defined($options{payunique}) && length($options{payunique});
5012 my $oldAutoCommit = $FS::UID::AutoCommit;
5013 local $FS::UID::AutoCommit = 0;
5016 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
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. but at least we have a record of the state we had to abort in
5027 # from cust_pay_pending now.
5028 my $e = "WARNING: $options{method} captured but payment not recorded -".
5029 " error inserting payment (". $payment_gateway->gateway_module.
5031 " (previously tried insert with invnum #$options{'invnum'}" .
5032 ": $error ) - pending payment saved as paypendingnum ".
5033 $cust_pay_pending->paypendingnum. "\n";
5039 my $jobnum = $cust_pay_pending->jobnum;
5041 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5043 unless ( $placeholder ) {
5044 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5045 my $e = "WARNING: $options{method} captured but job $jobnum not ".
5046 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
5051 $error = $placeholder->delete;
5054 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5055 my $e = "WARNING: $options{method} captured but could not delete ".
5056 "job $jobnum for paypendingnum ".
5057 $cust_pay_pending->paypendingnum. ": $error\n";
5064 if ( $options{'paynum_ref'} ) {
5065 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5068 $cust_pay_pending->status('done');
5069 $cust_pay_pending->statustext('captured');
5070 $cust_pay_pending->paynum($cust_pay->paynum);
5071 my $cpp_done_err = $cust_pay_pending->replace;
5073 if ( $cpp_done_err ) {
5075 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5076 my $e = "WARNING: $options{method} captured but payment not recorded - ".
5077 "error updating status for paypendingnum ".
5078 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5084 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5086 if ( $options{'apply'} ) {
5087 my $apply_error = $self->apply_payments_and_credits;
5088 if ( $apply_error ) {
5089 warn "WARNING: error applying payment: $apply_error\n";
5090 #but we still should return no error cause the payment otherwise went
5095 return ''; #no error
5101 my $perror = $payment_gateway->gateway_module. " error: ".
5102 $transaction->error_message;
5104 my $jobnum = $cust_pay_pending->jobnum;
5106 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5108 if ( $placeholder ) {
5109 my $error = $placeholder->depended_delete;
5110 $error ||= $placeholder->delete;
5111 warn "error removing provisioning jobs after declined paypendingnum ".
5112 $cust_pay_pending->paypendingnum. "\n";
5114 my $e = "error finding job $jobnum for declined paypendingnum ".
5115 $cust_pay_pending->paypendingnum. "\n";
5121 unless ( $transaction->error_message ) {
5124 if ( $transaction->can('response_page') ) {
5126 'page' => ( $transaction->can('response_page')
5127 ? $transaction->response_page
5130 'code' => ( $transaction->can('response_code')
5131 ? $transaction->response_code
5134 'headers' => ( $transaction->can('response_headers')
5135 ? $transaction->response_headers
5141 "No additional debugging information available for ".
5142 $payment_gateway->gateway_module;
5145 $perror .= "No error_message returned from ".
5146 $payment_gateway->gateway_module. " -- ".
5147 ( ref($t_response) ? Dumper($t_response) : $t_response );
5151 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
5152 && $conf->exists('emaildecline')
5153 && grep { $_ ne 'POST' } $self->invoicing_list
5154 && ! grep { $transaction->error_message =~ /$_/ }
5155 $conf->config('emaildecline-exclude')
5158 # Send a decline alert to the customer.
5159 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
5162 # include the raw error message in the transaction state
5163 $cust_pay_pending->setfield('error', $transaction->error_message);
5164 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
5165 $error = $msg_template->send( 'cust_main' => $self,
5166 'object' => $cust_pay_pending );
5170 my @templ = $conf->config('declinetemplate');
5171 my $template = new Text::Template (
5173 SOURCE => [ map "$_\n", @templ ],
5174 ) or return "($perror) can't create template: $Text::Template::ERROR";
5175 $template->compile()
5176 or return "($perror) can't compile template: $Text::Template::ERROR";
5180 scalar( $conf->config('company_name', $self->agentnum ) ),
5181 'company_address' =>
5182 join("\n", $conf->config('company_address', $self->agentnum ) ),
5183 'error' => $transaction->error_message,
5186 my $error = send_email(
5187 'from' => $conf->config('invoice_from', $self->agentnum ),
5188 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
5189 'subject' => 'Your payment could not be processed',
5190 'body' => [ $template->fill_in(HASH => $templ_hash) ],
5194 $perror .= " (also received error sending decline notification: $error)"
5199 $cust_pay_pending->status('done');
5200 $cust_pay_pending->statustext("declined: $perror");
5201 my $cpp_done_err = $cust_pay_pending->replace;
5202 if ( $cpp_done_err ) {
5203 my $e = "WARNING: $options{method} declined but pending payment not ".
5204 "resolved - error updating status for paypendingnum ".
5205 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5207 $perror = "$e ($perror)";
5215 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
5217 Verifies successful third party processing of a realtime credit card,
5218 ACH (electronic check) or phone bill transaction via a
5219 Business::OnlineThirdPartyPayment realtime gateway. See
5220 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
5222 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
5224 The additional options I<payname>, I<city>, I<state>,
5225 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5226 if set, will override the value from the customer record.
5228 I<description> is a free-text field passed to the gateway. It defaults to
5229 "Internet services".
5231 If an I<invnum> is specified, this payment (if successful) is applied to the
5232 specified invoice. If you don't specify an I<invnum> you might want to
5233 call the B<apply_payments> method.
5235 I<quiet> can be set true to surpress email decline notices.
5237 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
5238 resulting paynum, if any.
5240 I<payunique> is a unique identifier for this payment.
5242 Returns a hashref containing elements bill_error (which will be undefined
5243 upon success) and session_id of any associated session.
5247 sub realtime_botpp_capture {
5248 my( $self, $cust_pay_pending, %options ) = @_;
5250 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5251 warn " $_ => $options{$_}\n" foreach keys %options;
5254 eval "use Business::OnlineThirdPartyPayment";
5258 # select the gateway
5261 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5263 my $payment_gateway = $cust_pay_pending->gatewaynum
5264 ? qsearchs( 'payment_gateway',
5265 { gatewaynum => $cust_pay_pending->gatewaynum }
5267 : $self->agent->payment_gateway( 'method' => $method,
5268 # 'invnum' => $cust_pay_pending->invnum,
5269 # 'payinfo' => $cust_pay_pending->payinfo,
5272 $options{payment_gateway} = $payment_gateway; # for the helper subs
5278 my @invoicing_list = $self->invoicing_list_emailonly;
5279 if ( $conf->exists('emailinvoiceautoalways')
5280 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5281 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5282 push @invoicing_list, $self->all_emails;
5285 my $email = ($conf->exists('business-onlinepayment-email-override'))
5286 ? $conf->config('business-onlinepayment-email-override')
5287 : $invoicing_list[0];
5291 $content{email_customer} =
5292 ( $conf->exists('business-onlinepayment-email_customer')
5293 || $conf->exists('business-onlinepayment-email-override') );
5296 # run transaction(s)
5300 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5301 $self->_bop_options(\%options),
5304 $transaction->reference({ %options });
5306 $transaction->content(
5308 $self->_bop_auth(\%options),
5309 'action' => 'Post Authorization',
5310 'description' => $options{'description'},
5311 'amount' => $cust_pay_pending->paid,
5312 #'invoice_number' => $options{'invnum'},
5313 'customer_id' => $self->custnum,
5314 'referer' => 'http://cleanwhisker.420.am/',
5315 'reference' => $cust_pay_pending->paypendingnum,
5317 'phone' => $self->daytime || $self->night,
5319 # plus whatever is required for bogus capture avoidance
5322 $transaction->submit();
5325 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5328 bill_error => $error,
5329 session_id => $cust_pay_pending->session_id,
5334 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5338 sub default_payment_gateway {
5339 my( $self, $method ) = @_;
5341 die "Real-time processing not enabled\n"
5342 unless $conf->exists('business-onlinepayment');
5344 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5347 my $bop_config = 'business-onlinepayment';
5348 $bop_config .= '-ach'
5349 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5350 my ( $processor, $login, $password, $action, @bop_options ) =
5351 $conf->config($bop_config);
5352 $action ||= 'normal authorization';
5353 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5354 die "No real-time processor is enabled - ".
5355 "did you set the business-onlinepayment configuration value?\n"
5358 ( $processor, $login, $password, $action, @bop_options )
5363 Removes the I<paycvv> field from the database directly.
5365 If there is an error, returns the error, otherwise returns false.
5371 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5372 or return dbh->errstr;
5373 $sth->execute($self->custnum)
5374 or return $sth->errstr;
5379 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5381 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5382 via a Business::OnlinePayment realtime gateway. See
5383 L<http://420.am/business-onlinepayment> for supported gateways.
5385 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5387 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5389 Most gateways require a reference to an original payment transaction to refund,
5390 so you probably need to specify a I<paynum>.
5392 I<amount> defaults to the original amount of the payment if not specified.
5394 I<reason> specifies a reason for the refund.
5396 I<paydate> specifies the expiration date for a credit card overriding the
5397 value from the customer record or the payment record. Specified as yyyy-mm-dd
5399 Implementation note: If I<amount> is unspecified or equal to the amount of the
5400 orignal payment, first an attempt is made to "void" the transaction via
5401 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5402 the normal attempt is made to "refund" ("credit") the transaction via the
5403 gateway is attempted.
5405 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5406 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5407 #if set, will override the value from the customer record.
5409 #If an I<invnum> is specified, this payment (if successful) is applied to the
5410 #specified invoice. If you don't specify an I<invnum> you might want to
5411 #call the B<apply_payments> method.
5415 #some false laziness w/realtime_bop, not enough to make it worth merging
5416 #but some useful small subs should be pulled out
5417 sub realtime_refund_bop {
5421 if (ref($_[0]) eq 'HASH') {
5422 %options = %{$_[0]};
5426 $options{method} = $method;
5430 warn "$me realtime_refund_bop (new): $options{method} refund\n";
5431 warn " $_ => $options{$_}\n" foreach keys %options;
5435 # look up the original payment and optionally a gateway for that payment
5439 my $amount = $options{'amount'};
5441 my( $processor, $login, $password, @bop_options, $namespace ) ;
5442 my( $auth, $order_number ) = ( '', '', '' );
5444 if ( $options{'paynum'} ) {
5446 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
5447 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5448 or return "Unknown paynum $options{'paynum'}";
5449 $amount ||= $cust_pay->paid;
5451 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5452 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5453 $cust_pay->paybatch;
5454 my $gatewaynum = '';
5455 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5457 if ( $gatewaynum ) { #gateway for the payment to be refunded
5459 my $payment_gateway =
5460 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5461 die "payment gateway $gatewaynum not found"
5462 unless $payment_gateway;
5464 $processor = $payment_gateway->gateway_module;
5465 $login = $payment_gateway->gateway_username;
5466 $password = $payment_gateway->gateway_password;
5467 $namespace = $payment_gateway->gateway_namespace;
5468 @bop_options = $payment_gateway->options;
5470 } else { #try the default gateway
5473 my $payment_gateway =
5474 $self->agent->payment_gateway('method' => $options{method});
5476 ( $conf_processor, $login, $password, $namespace ) =
5477 map { my $method = "gateway_$_"; $payment_gateway->$method }
5478 qw( module username password namespace );
5480 @bop_options = $payment_gateway->gatewaynum
5481 ? $payment_gateway->options
5482 : @{ $payment_gateway->get('options') };
5484 return "processor of payment $options{'paynum'} $processor does not".
5485 " match default processor $conf_processor"
5486 unless $processor eq $conf_processor;
5491 } else { # didn't specify a paynum, so look for agent gateway overrides
5492 # like a normal transaction
5494 my $payment_gateway =
5495 $self->agent->payment_gateway( 'method' => $options{method},
5496 #'payinfo' => $payinfo,
5498 my( $processor, $login, $password, $namespace ) =
5499 map { my $method = "gateway_$_"; $payment_gateway->$method }
5500 qw( module username password namespace );
5502 my @bop_options = $payment_gateway->gatewaynum
5503 ? $payment_gateway->options
5504 : @{ $payment_gateway->get('options') };
5507 return "neither amount nor paynum specified" unless $amount;
5509 eval "use $namespace";
5513 'type' => $options{method},
5515 'password' => $password,
5516 'order_number' => $order_number,
5517 'amount' => $amount,
5518 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5520 $content{authorization} = $auth
5521 if length($auth); #echeck/ACH transactions have an order # but no auth
5522 #(at least with authorize.net)
5524 my $disable_void_after;
5525 if ($conf->exists('disable_void_after')
5526 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5527 $disable_void_after = $1;
5530 #first try void if applicable
5531 if ( $cust_pay && $cust_pay->paid == $amount
5533 ( not defined($disable_void_after) )
5534 || ( time < ($cust_pay->_date + $disable_void_after ) )
5537 warn " attempting void\n" if $DEBUG > 1;
5538 my $void = new Business::OnlinePayment( $processor, @bop_options );
5539 if ( $void->can('info') ) {
5540 if ( $cust_pay->payby eq 'CARD'
5541 && $void->info('CC_void_requires_card') )
5543 $content{'card_number'} = $cust_pay->payinfo;
5544 } elsif ( $cust_pay->payby eq 'CHEK'
5545 && $void->info('ECHECK_void_requires_account') )
5547 ( $content{'account_number'}, $content{'routing_code'} ) =
5548 split('@', $cust_pay->payinfo);
5549 $content{'name'} = $self->get('first'). ' '. $self->get('last');
5552 $void->content( 'action' => 'void', %content );
5553 $void->test_transaction(1)
5554 if $conf->exists('business-onlinepayment-test_transaction');
5556 if ( $void->is_success ) {
5557 my $error = $cust_pay->void($options{'reason'});
5559 # gah, even with transactions.
5560 my $e = 'WARNING: Card/ACH voided but database not updated - '.
5561 "error voiding payment: $error";
5565 warn " void successful\n" if $DEBUG > 1;
5570 warn " void unsuccessful, trying refund\n"
5574 my $address = $self->address1;
5575 $address .= ", ". $self->address2 if $self->address2;
5577 my($payname, $payfirst, $paylast);
5578 if ( $self->payname && $options{method} ne 'ECHECK' ) {
5579 $payname = $self->payname;
5580 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5581 or return "Illegal payname $payname";
5582 ($payfirst, $paylast) = ($1, $2);
5584 $payfirst = $self->getfield('first');
5585 $paylast = $self->getfield('last');
5586 $payname = "$payfirst $paylast";
5589 my @invoicing_list = $self->invoicing_list_emailonly;
5590 if ( $conf->exists('emailinvoiceautoalways')
5591 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5592 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5593 push @invoicing_list, $self->all_emails;
5596 my $email = ($conf->exists('business-onlinepayment-email-override'))
5597 ? $conf->config('business-onlinepayment-email-override')
5598 : $invoicing_list[0];
5600 my $payip = exists($options{'payip'})
5603 $content{customer_ip} = $payip
5607 if ( $options{method} eq 'CC' ) {
5610 $content{card_number} = $payinfo = $cust_pay->payinfo;
5611 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
5612 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
5613 ($content{expiration} = "$2/$1"); # where available
5615 $content{card_number} = $payinfo = $self->payinfo;
5616 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
5617 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5618 $content{expiration} = "$2/$1";
5621 } elsif ( $options{method} eq 'ECHECK' ) {
5624 $payinfo = $cust_pay->payinfo;
5626 $payinfo = $self->payinfo;
5628 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
5629 $content{bank_name} = $self->payname;
5630 $content{account_type} = 'CHECKING';
5631 $content{account_name} = $payname;
5632 $content{customer_org} = $self->company ? 'B' : 'I';
5633 $content{customer_ssn} = $self->ss;
5634 } elsif ( $options{method} eq 'LEC' ) {
5635 $content{phone} = $payinfo = $self->payinfo;
5639 my $refund = new Business::OnlinePayment( $processor, @bop_options );
5640 my %sub_content = $refund->content(
5641 'action' => 'credit',
5642 'customer_id' => $self->custnum,
5643 'last_name' => $paylast,
5644 'first_name' => $payfirst,
5646 'address' => $address,
5647 'city' => $self->city,
5648 'state' => $self->state,
5649 'zip' => $self->zip,
5650 'country' => $self->country,
5652 'phone' => $self->daytime || $self->night,
5655 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
5657 $refund->test_transaction(1)
5658 if $conf->exists('business-onlinepayment-test_transaction');
5661 return "$processor error: ". $refund->error_message
5662 unless $refund->is_success();
5664 my $paybatch = "$processor:". $refund->authorization;
5665 $paybatch .= ':'. $refund->order_number
5666 if $refund->can('order_number') && $refund->order_number;
5668 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
5669 my @cust_bill_pay = $cust_pay->cust_bill_pay;
5670 last unless @cust_bill_pay;
5671 my $cust_bill_pay = pop @cust_bill_pay;
5672 my $error = $cust_bill_pay->delete;
5676 my $cust_refund = new FS::cust_refund ( {
5677 'custnum' => $self->custnum,
5678 'paynum' => $options{'paynum'},
5679 'refund' => $amount,
5681 'payby' => $bop_method2payby{$options{method}},
5682 'payinfo' => $payinfo,
5683 'paybatch' => $paybatch,
5684 'reason' => $options{'reason'} || 'card or ACH refund',
5686 my $error = $cust_refund->insert;
5688 $cust_refund->paynum(''); #try again with no specific paynum
5689 my $error2 = $cust_refund->insert;
5691 # gah, even with transactions.
5692 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
5693 "error inserting refund ($processor): $error2".
5694 " (previously tried insert with paynum #$options{'paynum'}" .
5705 =item batch_card OPTION => VALUE...
5707 Adds a payment for this invoice to the pending credit card batch (see
5708 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
5709 runs the payment using a realtime gateway.
5714 my ($self, %options) = @_;
5717 if (exists($options{amount})) {
5718 $amount = $options{amount};
5720 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
5722 return '' unless $amount > 0;
5724 my $invnum = delete $options{invnum};
5725 my $payby = $options{invnum} || $self->payby; #dubious
5727 if ($options{'realtime'}) {
5728 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
5734 my $oldAutoCommit = $FS::UID::AutoCommit;
5735 local $FS::UID::AutoCommit = 0;
5738 #this needs to handle mysql as well as Pg, like svc_acct.pm
5739 #(make it into a common function if folks need to do batching with mysql)
5740 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
5741 or return "Cannot lock pay_batch: " . $dbh->errstr;
5745 'payby' => FS::payby->payby2payment($payby),
5748 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
5750 unless ( $pay_batch ) {
5751 $pay_batch = new FS::pay_batch \%pay_batch;
5752 my $error = $pay_batch->insert;
5754 $dbh->rollback if $oldAutoCommit;
5755 die "error creating new batch: $error\n";
5759 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
5760 'batchnum' => $pay_batch->batchnum,
5761 'custnum' => $self->custnum,
5764 foreach (qw( address1 address2 city state zip country payby payinfo paydate
5766 $options{$_} = '' unless exists($options{$_});
5769 my $cust_pay_batch = new FS::cust_pay_batch ( {
5770 'batchnum' => $pay_batch->batchnum,
5771 'invnum' => $invnum || 0, # is there a better value?
5772 # this field should be
5774 # cust_bill_pay_batch now
5775 'custnum' => $self->custnum,
5776 'last' => $self->getfield('last'),
5777 'first' => $self->getfield('first'),
5778 'address1' => $options{address1} || $self->address1,
5779 'address2' => $options{address2} || $self->address2,
5780 'city' => $options{city} || $self->city,
5781 'state' => $options{state} || $self->state,
5782 'zip' => $options{zip} || $self->zip,
5783 'country' => $options{country} || $self->country,
5784 'payby' => $options{payby} || $self->payby,
5785 'payinfo' => $options{payinfo} || $self->payinfo,
5786 'exp' => $options{paydate} || $self->paydate,
5787 'payname' => $options{payname} || $self->payname,
5788 'amount' => $amount, # consolidating
5791 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
5792 if $old_cust_pay_batch;
5795 if ($old_cust_pay_batch) {
5796 $error = $cust_pay_batch->replace($old_cust_pay_batch)
5798 $error = $cust_pay_batch->insert;
5802 $dbh->rollback if $oldAutoCommit;
5806 my $unapplied = $self->total_unapplied_credits
5807 + $self->total_unapplied_payments
5808 + $self->in_transit_payments;
5809 foreach my $cust_bill ($self->open_cust_bill) {
5810 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
5811 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
5812 'invnum' => $cust_bill->invnum,
5813 'paybatchnum' => $cust_pay_batch->paybatchnum,
5814 'amount' => $cust_bill->owed,
5817 if ($unapplied >= $cust_bill_pay_batch->amount){
5818 $unapplied -= $cust_bill_pay_batch->amount;
5821 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
5822 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
5824 $error = $cust_bill_pay_batch->insert;
5826 $dbh->rollback if $oldAutoCommit;
5831 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5835 =item apply_payments_and_credits [ OPTION => VALUE ... ]
5837 Applies unapplied payments and credits.
5839 In most cases, this new method should be used in place of sequential
5840 apply_payments and apply_credits methods.
5842 A hash of optional arguments may be passed. Currently "manual" is supported.
5843 If true, a payment receipt is sent instead of a statement when
5844 'payment_receipt_email' configuration option is set.
5846 If there is an error, returns the error, otherwise returns false.
5850 sub apply_payments_and_credits {
5851 my( $self, %options ) = @_;
5853 local $SIG{HUP} = 'IGNORE';
5854 local $SIG{INT} = 'IGNORE';
5855 local $SIG{QUIT} = 'IGNORE';
5856 local $SIG{TERM} = 'IGNORE';
5857 local $SIG{TSTP} = 'IGNORE';
5858 local $SIG{PIPE} = 'IGNORE';
5860 my $oldAutoCommit = $FS::UID::AutoCommit;
5861 local $FS::UID::AutoCommit = 0;
5864 $self->select_for_update; #mutex
5866 foreach my $cust_bill ( $self->open_cust_bill ) {
5867 my $error = $cust_bill->apply_payments_and_credits(%options);
5869 $dbh->rollback if $oldAutoCommit;
5870 return "Error applying: $error";
5874 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5879 =item apply_credits OPTION => VALUE ...
5881 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
5882 to outstanding invoice balances in chronological order (or reverse
5883 chronological order if the I<order> option is set to B<newest>) and returns the
5884 value of any remaining unapplied credits available for refund (see
5885 L<FS::cust_refund>).
5887 Dies if there is an error.
5895 local $SIG{HUP} = 'IGNORE';
5896 local $SIG{INT} = 'IGNORE';
5897 local $SIG{QUIT} = 'IGNORE';
5898 local $SIG{TERM} = 'IGNORE';
5899 local $SIG{TSTP} = 'IGNORE';
5900 local $SIG{PIPE} = 'IGNORE';
5902 my $oldAutoCommit = $FS::UID::AutoCommit;
5903 local $FS::UID::AutoCommit = 0;
5906 $self->select_for_update; #mutex
5908 unless ( $self->total_unapplied_credits ) {
5909 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5913 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
5914 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
5916 my @invoices = $self->open_cust_bill;
5917 @invoices = sort { $b->_date <=> $a->_date } @invoices
5918 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
5920 if ( $conf->exists('pkg-balances') ) {
5921 # limit @credits to those w/ a pkgnum grepped from $self
5923 foreach my $i (@invoices) {
5924 foreach my $li ( $i->cust_bill_pkg ) {
5925 $pkgnums{$li->pkgnum} = 1;
5928 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
5933 foreach my $cust_bill ( @invoices ) {
5935 if ( !defined($credit) || $credit->credited == 0) {
5936 $credit = pop @credits or last;
5940 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
5941 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
5943 $owed = $cust_bill->owed;
5945 unless ( $owed > 0 ) {
5946 push @credits, $credit;
5950 my $amount = min( $credit->credited, $owed );
5952 my $cust_credit_bill = new FS::cust_credit_bill ( {
5953 'crednum' => $credit->crednum,
5954 'invnum' => $cust_bill->invnum,
5955 'amount' => $amount,
5957 $cust_credit_bill->pkgnum( $credit->pkgnum )
5958 if $conf->exists('pkg-balances') && $credit->pkgnum;
5959 my $error = $cust_credit_bill->insert;
5961 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5965 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5969 my $total_unapplied_credits = $self->total_unapplied_credits;
5971 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5973 return $total_unapplied_credits;
5976 =item apply_payments [ OPTION => VALUE ... ]
5978 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
5979 to outstanding invoice balances in chronological order.
5981 #and returns the value of any remaining unapplied payments.
5983 A hash of optional arguments may be passed. Currently "manual" is supported.
5984 If true, a payment receipt is sent instead of a statement when
5985 'payment_receipt_email' configuration option is set.
5987 Dies if there is an error.
5991 sub apply_payments {
5992 my( $self, %options ) = @_;
5994 local $SIG{HUP} = 'IGNORE';
5995 local $SIG{INT} = 'IGNORE';
5996 local $SIG{QUIT} = 'IGNORE';
5997 local $SIG{TERM} = 'IGNORE';
5998 local $SIG{TSTP} = 'IGNORE';
5999 local $SIG{PIPE} = 'IGNORE';
6001 my $oldAutoCommit = $FS::UID::AutoCommit;
6002 local $FS::UID::AutoCommit = 0;
6005 $self->select_for_update; #mutex
6009 my @payments = sort { $b->_date <=> $a->_date }
6010 grep { $_->unapplied > 0 }
6013 my @invoices = sort { $a->_date <=> $b->_date}
6014 grep { $_->owed > 0 }
6017 if ( $conf->exists('pkg-balances') ) {
6018 # limit @payments to those w/ a pkgnum grepped from $self
6020 foreach my $i (@invoices) {
6021 foreach my $li ( $i->cust_bill_pkg ) {
6022 $pkgnums{$li->pkgnum} = 1;
6025 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
6030 foreach my $cust_bill ( @invoices ) {
6032 if ( !defined($payment) || $payment->unapplied == 0 ) {
6033 $payment = pop @payments or last;
6037 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
6038 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
6040 $owed = $cust_bill->owed;
6042 unless ( $owed > 0 ) {
6043 push @payments, $payment;
6047 my $amount = min( $payment->unapplied, $owed );
6049 my $cust_bill_pay = new FS::cust_bill_pay ( {
6050 'paynum' => $payment->paynum,
6051 'invnum' => $cust_bill->invnum,
6052 'amount' => $amount,
6054 $cust_bill_pay->pkgnum( $payment->pkgnum )
6055 if $conf->exists('pkg-balances') && $payment->pkgnum;
6056 my $error = $cust_bill_pay->insert(%options);
6058 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6062 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6066 my $total_unapplied_payments = $self->total_unapplied_payments;
6068 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6070 return $total_unapplied_payments;
6075 Returns the total owed for this customer on all invoices
6076 (see L<FS::cust_bill/owed>).
6082 $self->total_owed_date(2145859200); #12/31/2037
6085 =item total_owed_date TIME
6087 Returns the total owed for this customer on all invoices with date earlier than
6088 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6089 see L<Time::Local> and L<Date::Parse> for conversion functions.
6093 sub total_owed_date {
6097 my $custnum = $self->custnum;
6099 my $owed_sql = FS::cust_bill->owed_sql;
6102 SELECT SUM($owed_sql) FROM cust_bill
6103 WHERE custnum = $custnum
6107 sprintf( "%.2f", $self->scalar_sql($sql) );
6111 =item total_owed_pkgnum PKGNUM
6113 Returns the total owed on all invoices for this customer's specific package
6114 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
6118 sub total_owed_pkgnum {
6119 my( $self, $pkgnum ) = @_;
6120 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
6123 =item total_owed_date_pkgnum TIME PKGNUM
6125 Returns the total owed for this customer's specific package when using
6126 experimental package balances on all invoices with date earlier than
6127 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6128 see L<Time::Local> and L<Date::Parse> for conversion functions.
6132 sub total_owed_date_pkgnum {
6133 my( $self, $time, $pkgnum ) = @_;
6136 foreach my $cust_bill (
6137 grep { $_->_date <= $time }
6138 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6140 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
6142 sprintf( "%.2f", $total_bill );
6148 Returns the total amount of all payments.
6155 $total += $_->paid foreach $self->cust_pay;
6156 sprintf( "%.2f", $total );
6159 =item total_unapplied_credits
6161 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6162 customer. See L<FS::cust_credit/credited>.
6164 =item total_credited
6166 Old name for total_unapplied_credits. Don't use.
6170 sub total_credited {
6171 #carp "total_credited deprecated, use total_unapplied_credits";
6172 shift->total_unapplied_credits(@_);
6175 sub total_unapplied_credits {
6178 my $custnum = $self->custnum;
6180 my $unapplied_sql = FS::cust_credit->unapplied_sql;
6183 SELECT SUM($unapplied_sql) FROM cust_credit
6184 WHERE custnum = $custnum
6187 sprintf( "%.2f", $self->scalar_sql($sql) );
6191 =item total_unapplied_credits_pkgnum PKGNUM
6193 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6194 customer. See L<FS::cust_credit/credited>.
6198 sub total_unapplied_credits_pkgnum {
6199 my( $self, $pkgnum ) = @_;
6200 my $total_credit = 0;
6201 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
6202 sprintf( "%.2f", $total_credit );
6206 =item total_unapplied_payments
6208 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
6209 See L<FS::cust_pay/unapplied>.
6213 sub total_unapplied_payments {
6216 my $custnum = $self->custnum;
6218 my $unapplied_sql = FS::cust_pay->unapplied_sql;
6221 SELECT SUM($unapplied_sql) FROM cust_pay
6222 WHERE custnum = $custnum
6225 sprintf( "%.2f", $self->scalar_sql($sql) );
6229 =item total_unapplied_payments_pkgnum PKGNUM
6231 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
6232 specific package when using experimental package balances. See
6233 L<FS::cust_pay/unapplied>.
6237 sub total_unapplied_payments_pkgnum {
6238 my( $self, $pkgnum ) = @_;
6239 my $total_unapplied = 0;
6240 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
6241 sprintf( "%.2f", $total_unapplied );
6245 =item total_unapplied_refunds
6247 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
6248 customer. See L<FS::cust_refund/unapplied>.
6252 sub total_unapplied_refunds {
6254 my $custnum = $self->custnum;
6256 my $unapplied_sql = FS::cust_refund->unapplied_sql;
6259 SELECT SUM($unapplied_sql) FROM cust_refund
6260 WHERE custnum = $custnum
6263 sprintf( "%.2f", $self->scalar_sql($sql) );
6269 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6270 total_unapplied_credits minus total_unapplied_payments).
6276 $self->balance_date_range;
6279 =item balance_date TIME
6281 Returns the balance for this customer, only considering invoices with date
6282 earlier than TIME (total_owed_date minus total_credited minus
6283 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
6284 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
6291 $self->balance_date_range(shift);
6294 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
6296 Returns the balance for this customer, optionally considering invoices with
6297 date earlier than START_TIME, and not later than END_TIME
6298 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
6300 Times are specified as SQL fragments or numeric
6301 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
6302 L<Date::Parse> for conversion functions. The empty string can be passed
6303 to disable that time constraint completely.
6305 Available options are:
6309 =item unapplied_date
6311 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)
6317 sub balance_date_range {
6319 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
6320 ') FROM cust_main WHERE custnum='. $self->custnum;
6321 sprintf( '%.2f', $self->scalar_sql($sql) );
6324 =item balance_pkgnum PKGNUM
6326 Returns the balance for this customer's specific package when using
6327 experimental package balances (total_owed plus total_unrefunded, minus
6328 total_unapplied_credits minus total_unapplied_payments)
6332 sub balance_pkgnum {
6333 my( $self, $pkgnum ) = @_;
6336 $self->total_owed_pkgnum($pkgnum)
6337 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6338 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
6339 - $self->total_unapplied_credits_pkgnum($pkgnum)
6340 - $self->total_unapplied_payments_pkgnum($pkgnum)
6344 =item in_transit_payments
6346 Returns the total of requests for payments for this customer pending in
6347 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
6351 sub in_transit_payments {
6353 my $in_transit_payments = 0;
6354 foreach my $pay_batch ( qsearch('pay_batch', {
6357 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6358 'batchnum' => $pay_batch->batchnum,
6359 'custnum' => $self->custnum,
6361 $in_transit_payments += $cust_pay_batch->amount;
6364 sprintf( "%.2f", $in_transit_payments );
6369 Returns a hash of useful information for making a payment.
6379 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6380 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6381 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6385 For credit card transactions:
6397 For electronic check transactions:
6412 $return{balance} = $self->balance;
6414 $return{payname} = $self->payname
6415 || ( $self->first. ' '. $self->get('last') );
6417 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6419 $return{payby} = $self->payby;
6420 $return{stateid_state} = $self->stateid_state;
6422 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6423 $return{card_type} = cardtype($self->payinfo);
6424 $return{payinfo} = $self->paymask;
6426 @return{'month', 'year'} = $self->paydate_monthyear;
6430 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6431 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6432 $return{payinfo1} = $payinfo1;
6433 $return{payinfo2} = $payinfo2;
6434 $return{paytype} = $self->paytype;
6435 $return{paystate} = $self->paystate;
6439 #doubleclick protection
6441 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6447 =item paydate_monthyear
6449 Returns a two-element list consisting of the month and year of this customer's
6450 paydate (credit card expiration date for CARD customers)
6454 sub paydate_monthyear {
6456 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6458 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6465 =item tax_exemption TAXNAME
6470 my( $self, $taxname ) = @_;
6472 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6473 'taxname' => $taxname,
6478 =item cust_main_exemption
6482 sub cust_main_exemption {
6484 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6487 =item invoicing_list [ ARRAYREF ]
6489 If an arguement is given, sets these email addresses as invoice recipients
6490 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
6491 (except as warnings), so use check_invoicing_list first.
6493 Returns a list of email addresses (with svcnum entries expanded).
6495 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
6496 check it without disturbing anything by passing nothing.
6498 This interface may change in the future.
6502 sub invoicing_list {
6503 my( $self, $arrayref ) = @_;
6506 my @cust_main_invoice;
6507 if ( $self->custnum ) {
6508 @cust_main_invoice =
6509 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6511 @cust_main_invoice = ();
6513 foreach my $cust_main_invoice ( @cust_main_invoice ) {
6514 #warn $cust_main_invoice->destnum;
6515 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6516 #warn $cust_main_invoice->destnum;
6517 my $error = $cust_main_invoice->delete;
6518 warn $error if $error;
6521 if ( $self->custnum ) {
6522 @cust_main_invoice =
6523 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6525 @cust_main_invoice = ();
6527 my %seen = map { $_->address => 1 } @cust_main_invoice;
6528 foreach my $address ( @{$arrayref} ) {
6529 next if exists $seen{$address} && $seen{$address};
6530 $seen{$address} = 1;
6531 my $cust_main_invoice = new FS::cust_main_invoice ( {
6532 'custnum' => $self->custnum,
6535 my $error = $cust_main_invoice->insert;
6536 warn $error if $error;
6540 if ( $self->custnum ) {
6542 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6549 =item check_invoicing_list ARRAYREF
6551 Checks these arguements as valid input for the invoicing_list method. If there
6552 is an error, returns the error, otherwise returns false.
6556 sub check_invoicing_list {
6557 my( $self, $arrayref ) = @_;
6559 foreach my $address ( @$arrayref ) {
6561 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6562 return 'Can\'t add FAX invoice destination with a blank FAX number.';
6565 my $cust_main_invoice = new FS::cust_main_invoice ( {
6566 'custnum' => $self->custnum,
6569 my $error = $self->custnum
6570 ? $cust_main_invoice->check
6571 : $cust_main_invoice->checkdest
6573 return $error if $error;
6577 return "Email address required"
6578 if $conf->exists('cust_main-require_invoicing_list_email')
6579 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6584 =item set_default_invoicing_list
6586 Sets the invoicing list to all accounts associated with this customer,
6587 overwriting any previous invoicing list.
6591 sub set_default_invoicing_list {
6593 $self->invoicing_list($self->all_emails);
6598 Returns the email addresses of all accounts provisioned for this customer.
6605 foreach my $cust_pkg ( $self->all_pkgs ) {
6606 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6608 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6609 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6611 $list{$_}=1 foreach map { $_->email } @svc_acct;
6616 =item invoicing_list_addpost
6618 Adds postal invoicing to this customer. If this customer is already configured
6619 to receive postal invoices, does nothing.
6623 sub invoicing_list_addpost {
6625 return if grep { $_ eq 'POST' } $self->invoicing_list;
6626 my @invoicing_list = $self->invoicing_list;
6627 push @invoicing_list, 'POST';
6628 $self->invoicing_list(\@invoicing_list);
6631 =item invoicing_list_emailonly
6633 Returns the list of email invoice recipients (invoicing_list without non-email
6634 destinations such as POST and FAX).
6638 sub invoicing_list_emailonly {
6640 warn "$me invoicing_list_emailonly called"
6642 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
6645 =item invoicing_list_emailonly_scalar
6647 Returns the list of email invoice recipients (invoicing_list without non-email
6648 destinations such as POST and FAX) as a comma-separated scalar.
6652 sub invoicing_list_emailonly_scalar {
6654 warn "$me invoicing_list_emailonly_scalar called"
6656 join(', ', $self->invoicing_list_emailonly);
6659 =item referral_custnum_cust_main
6661 Returns the customer who referred this customer (or the empty string, if
6662 this customer was not referred).
6664 Note the difference with referral_cust_main method: This method,
6665 referral_custnum_cust_main returns the single customer (if any) who referred
6666 this customer, while referral_cust_main returns an array of customers referred
6671 sub referral_custnum_cust_main {
6673 return '' unless $self->referral_custnum;
6674 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6677 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
6679 Returns an array of customers referred by this customer (referral_custnum set
6680 to this custnum). If DEPTH is given, recurses up to the given depth, returning
6681 customers referred by customers referred by this customer and so on, inclusive.
6682 The default behavior is DEPTH 1 (no recursion).
6684 Note the difference with referral_custnum_cust_main method: This method,
6685 referral_cust_main, returns an array of customers referred BY this customer,
6686 while referral_custnum_cust_main returns the single customer (if any) who
6687 referred this customer.
6691 sub referral_cust_main {
6693 my $depth = @_ ? shift : 1;
6694 my $exclude = @_ ? shift : {};
6697 map { $exclude->{$_->custnum}++; $_; }
6698 grep { ! $exclude->{ $_->custnum } }
6699 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
6703 map { $_->referral_cust_main($depth-1, $exclude) }
6710 =item referral_cust_main_ncancelled
6712 Same as referral_cust_main, except only returns customers with uncancelled
6717 sub referral_cust_main_ncancelled {
6719 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
6722 =item referral_cust_pkg [ DEPTH ]
6724 Like referral_cust_main, except returns a flat list of all unsuspended (and
6725 uncancelled) packages for each customer. The number of items in this list may
6726 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
6730 sub referral_cust_pkg {
6732 my $depth = @_ ? shift : 1;
6734 map { $_->unsuspended_pkgs }
6735 grep { $_->unsuspended_pkgs }
6736 $self->referral_cust_main($depth);
6739 =item referring_cust_main
6741 Returns the single cust_main record for the customer who referred this customer
6742 (referral_custnum), or false.
6746 sub referring_cust_main {
6748 return '' unless $self->referral_custnum;
6749 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6752 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
6754 Applies a credit to this customer. If there is an error, returns the error,
6755 otherwise returns false.
6757 REASON can be a text string, an FS::reason object, or a scalar reference to
6758 a reasonnum. If a text string, it will be automatically inserted as a new
6759 reason, and a 'reason_type' option must be passed to indicate the
6760 FS::reason_type for the new reason.
6762 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
6764 Any other options are passed to FS::cust_credit::insert.
6769 my( $self, $amount, $reason, %options ) = @_;
6771 my $cust_credit = new FS::cust_credit {
6772 'custnum' => $self->custnum,
6773 'amount' => $amount,
6776 if ( ref($reason) ) {
6778 if ( ref($reason) eq 'SCALAR' ) {
6779 $cust_credit->reasonnum( $$reason );
6781 $cust_credit->reasonnum( $reason->reasonnum );
6785 $cust_credit->set('reason', $reason)
6788 for (qw( addlinfo eventnum )) {
6789 $cust_credit->$_( delete $options{$_} )
6790 if exists($options{$_});
6793 $cust_credit->insert(%options);
6797 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
6799 Creates a one-time charge for this customer. If there is an error, returns
6800 the error, otherwise returns false.
6802 New-style, with a hashref of options:
6804 my $error = $cust_main->charge(
6808 'start_date' => str2time('7/4/2009'),
6809 'pkg' => 'Description',
6810 'comment' => 'Comment',
6811 'additional' => [], #extra invoice detail
6812 'classnum' => 1, #pkg_class
6814 'setuptax' => '', # or 'Y' for tax exempt
6817 'taxclass' => 'Tax class',
6820 'taxproduct' => 2, #part_pkg_taxproduct
6821 'override' => {}, #XXX describe
6823 #will be filled in with the new object
6824 'cust_pkg_ref' => \$cust_pkg,
6826 #generate an invoice immediately
6828 'invoice_terms' => '', #with these terms
6834 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
6840 my ( $amount, $quantity, $start_date, $classnum );
6841 my ( $pkg, $comment, $additional );
6842 my ( $setuptax, $taxclass ); #internal taxes
6843 my ( $taxproduct, $override ); #vendor (CCH) taxes
6845 my $cust_pkg_ref = '';
6846 my ( $bill_now, $invoice_terms ) = ( 0, '' );
6847 if ( ref( $_[0] ) ) {
6848 $amount = $_[0]->{amount};
6849 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
6850 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
6851 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
6852 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
6853 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
6854 : '$'. sprintf("%.2f",$amount);
6855 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
6856 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
6857 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
6858 $additional = $_[0]->{additional} || [];
6859 $taxproduct = $_[0]->{taxproductnum};
6860 $override = { '' => $_[0]->{tax_override} };
6861 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
6862 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
6863 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
6868 $pkg = @_ ? shift : 'One-time charge';
6869 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
6871 $taxclass = @_ ? shift : '';
6875 local $SIG{HUP} = 'IGNORE';
6876 local $SIG{INT} = 'IGNORE';
6877 local $SIG{QUIT} = 'IGNORE';
6878 local $SIG{TERM} = 'IGNORE';
6879 local $SIG{TSTP} = 'IGNORE';
6880 local $SIG{PIPE} = 'IGNORE';
6882 my $oldAutoCommit = $FS::UID::AutoCommit;
6883 local $FS::UID::AutoCommit = 0;
6886 my $part_pkg = new FS::part_pkg ( {
6888 'comment' => $comment,
6892 'classnum' => ( $classnum ? $classnum : '' ),
6893 'setuptax' => $setuptax,
6894 'taxclass' => $taxclass,
6895 'taxproductnum' => $taxproduct,
6898 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
6899 ( 0 .. @$additional - 1 )
6901 'additional_count' => scalar(@$additional),
6902 'setup_fee' => $amount,
6905 my $error = $part_pkg->insert( options => \%options,
6906 tax_overrides => $override,
6909 $dbh->rollback if $oldAutoCommit;
6913 my $pkgpart = $part_pkg->pkgpart;
6914 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
6915 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
6916 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
6917 $error = $type_pkgs->insert;
6919 $dbh->rollback if $oldAutoCommit;
6924 my $cust_pkg = new FS::cust_pkg ( {
6925 'custnum' => $self->custnum,
6926 'pkgpart' => $pkgpart,
6927 'quantity' => $quantity,
6928 'start_date' => $start_date,
6929 'no_auto' => $no_auto,
6932 $error = $cust_pkg->insert;
6934 $dbh->rollback if $oldAutoCommit;
6936 } elsif ( $cust_pkg_ref ) {
6937 ${$cust_pkg_ref} = $cust_pkg;
6941 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
6942 'pkg_list' => [ $cust_pkg ],
6945 $dbh->rollback if $oldAutoCommit;
6950 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6955 #=item charge_postal_fee
6957 #Applies a one time charge this customer. If there is an error,
6958 #returns the error, returns the cust_pkg charge object or false
6959 #if there was no charge.
6963 # This should be a customer event. For that to work requires that bill
6964 # also be a customer event.
6966 sub charge_postal_fee {
6969 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
6970 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
6972 my $cust_pkg = new FS::cust_pkg ( {
6973 'custnum' => $self->custnum,
6974 'pkgpart' => $pkgpart,
6978 my $error = $cust_pkg->insert;
6979 $error ? $error : $cust_pkg;
6984 Returns all the invoices (see L<FS::cust_bill>) for this customer.
6990 map { $_ } #return $self->num_cust_bill unless wantarray;
6991 sort { $a->_date <=> $b->_date }
6992 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6995 =item open_cust_bill
6997 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
7002 sub open_cust_bill {
7006 'table' => 'cust_bill',
7007 'hashref' => { 'custnum' => $self->custnum, },
7008 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
7009 'order_by' => 'ORDER BY _date ASC',
7014 =item cust_statements
7016 Returns all the statements (see L<FS::cust_statement>) for this customer.
7020 sub cust_statement {
7022 map { $_ } #return $self->num_cust_statement unless wantarray;
7023 sort { $a->_date <=> $b->_date }
7024 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
7029 Returns all the credits (see L<FS::cust_credit>) for this customer.
7035 map { $_ } #return $self->num_cust_credit unless wantarray;
7036 sort { $a->_date <=> $b->_date }
7037 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
7040 =item cust_credit_pkgnum
7042 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
7043 package when using experimental package balances.
7047 sub cust_credit_pkgnum {
7048 my( $self, $pkgnum ) = @_;
7049 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
7050 sort { $a->_date <=> $b->_date }
7051 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
7052 'pkgnum' => $pkgnum,
7059 Returns all the payments (see L<FS::cust_pay>) for this customer.
7065 return $self->num_cust_pay unless wantarray;
7066 sort { $a->_date <=> $b->_date }
7067 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
7072 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
7073 called automatically when the cust_pay method is used in a scalar context.
7079 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
7080 my $sth = dbh->prepare($sql) or die dbh->errstr;
7081 $sth->execute($self->custnum) or die $sth->errstr;
7082 $sth->fetchrow_arrayref->[0];
7085 =item cust_pay_pkgnum
7087 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
7088 package when using experimental package balances.
7092 sub cust_pay_pkgnum {
7093 my( $self, $pkgnum ) = @_;
7094 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
7095 sort { $a->_date <=> $b->_date }
7096 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
7097 'pkgnum' => $pkgnum,
7104 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
7110 map { $_ } #return $self->num_cust_pay_void unless wantarray;
7111 sort { $a->_date <=> $b->_date }
7112 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
7115 =item cust_pay_batch
7117 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
7121 sub cust_pay_batch {
7123 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
7124 sort { $a->paybatchnum <=> $b->paybatchnum }
7125 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
7128 =item cust_pay_pending
7130 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
7131 (without status "done").
7135 sub cust_pay_pending {
7137 return $self->num_cust_pay_pending unless wantarray;
7138 sort { $a->_date <=> $b->_date }
7139 qsearch( 'cust_pay_pending', {
7140 'custnum' => $self->custnum,
7141 'status' => { op=>'!=', value=>'done' },
7146 =item cust_pay_pending_attempt
7148 Returns all payment attempts / declined payments for this customer, as pending
7149 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
7150 a corresponding payment (see L<FS::cust_pay>).
7154 sub cust_pay_pending_attempt {
7156 return $self->num_cust_pay_pending_attempt unless wantarray;
7157 sort { $a->_date <=> $b->_date }
7158 qsearch( 'cust_pay_pending', {
7159 'custnum' => $self->custnum,
7166 =item num_cust_pay_pending
7168 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7169 customer (without status "done"). Also called automatically when the
7170 cust_pay_pending method is used in a scalar context.
7174 sub num_cust_pay_pending {
7177 " SELECT COUNT(*) FROM cust_pay_pending ".
7178 " WHERE custnum = ? AND status != 'done' ",
7183 =item num_cust_pay_pending_attempt
7185 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7186 customer, with status "done" but without a corresp. Also called automatically when the
7187 cust_pay_pending method is used in a scalar context.
7191 sub num_cust_pay_pending_attempt {
7194 " SELECT COUNT(*) FROM cust_pay_pending ".
7195 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
7202 Returns all the refunds (see L<FS::cust_refund>) for this customer.
7208 map { $_ } #return $self->num_cust_refund unless wantarray;
7209 sort { $a->_date <=> $b->_date }
7210 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
7213 =item display_custnum
7215 Returns the displayed customer number for this customer: agent_custid if
7216 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
7220 sub display_custnum {
7222 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
7223 return $self->agent_custid;
7225 return $self->custnum;
7231 Returns a name string for this customer, either "Company (Last, First)" or
7238 my $name = $self->contact;
7239 $name = $self->company. " ($name)" if $self->company;
7245 Returns a name string for this (service/shipping) contact, either
7246 "Company (Last, First)" or "Last, First".
7252 if ( $self->get('ship_last') ) {
7253 my $name = $self->ship_contact;
7254 $name = $self->ship_company. " ($name)" if $self->ship_company;
7263 Returns a name string for this customer, either "Company" or "First Last".
7269 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
7272 =item ship_name_short
7274 Returns a name string for this (service/shipping) contact, either "Company"
7279 sub ship_name_short {
7281 if ( $self->get('ship_last') ) {
7282 $self->ship_company !~ /^\s*$/
7283 ? $self->ship_company
7284 : $self->ship_contact_firstlast;
7286 $self->name_company_or_firstlast;
7292 Returns this customer's full (billing) contact name only, "Last, First"
7298 $self->get('last'). ', '. $self->first;
7303 Returns this customer's full (shipping) contact name only, "Last, First"
7309 $self->get('ship_last')
7310 ? $self->get('ship_last'). ', '. $self->ship_first
7314 =item contact_firstlast
7316 Returns this customers full (billing) contact name only, "First Last".
7320 sub contact_firstlast {
7322 $self->first. ' '. $self->get('last');
7325 =item ship_contact_firstlast
7327 Returns this customer's full (shipping) contact name only, "First Last".
7331 sub ship_contact_firstlast {
7333 $self->get('ship_last')
7334 ? $self->first. ' '. $self->get('ship_last')
7335 : $self->contact_firstlast;
7340 Returns this customer's full country name
7346 code2country($self->country);
7349 =item geocode DATA_VENDOR
7351 Returns a value for the customer location as encoded by DATA_VENDOR.
7352 Currently this only makes sense for "CCH" as DATA_VENDOR.
7357 my ($self, $data_vendor) = (shift, shift); #always cch for now
7359 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
7360 return $geocode if $geocode;
7362 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7366 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7367 if $self->country eq 'US';
7371 #CCH specific location stuff
7372 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7374 my @cust_tax_location =
7376 'table' => 'cust_tax_location',
7377 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7378 'extra_sql' => $extra_sql,
7379 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
7382 $geocode = $cust_tax_location[0]->geocode
7383 if scalar(@cust_tax_location);
7392 Returns a status string for this customer, currently:
7396 =item prospect - No packages have ever been ordered
7398 =item ordered - Recurring packages all are new (not yet billed).
7400 =item active - One or more recurring packages is active
7402 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7404 =item suspended - All non-cancelled recurring packages are suspended
7406 =item cancelled - All recurring packages are cancelled
7412 sub status { shift->cust_status(@_); }
7416 # prospect ordered active inactive suspended cancelled
7417 for my $status ( FS::cust_main->statuses() ) {
7418 my $method = $status.'_sql';
7419 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7420 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7421 $sth->execute( ($self->custnum) x $numnum )
7422 or die "Error executing 'SELECT $sql': ". $sth->errstr;
7423 return $status if $sth->fetchrow_arrayref->[0];
7427 =item ucfirst_cust_status
7429 =item ucfirst_status
7431 Returns the status with the first character capitalized.
7435 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7437 sub ucfirst_cust_status {
7439 ucfirst($self->cust_status);
7444 Returns a hex triplet color string for this customer's status.
7448 use vars qw(%statuscolor);
7449 tie %statuscolor, 'Tie::IxHash',
7450 'prospect' => '7e0079', #'000000', #black? naw, purple
7451 'active' => '00CC00', #green
7452 'ordered' => '009999', #teal? cyan?
7453 'inactive' => '0000CC', #blue
7454 'suspended' => 'FF9900', #yellow
7455 'cancelled' => 'FF0000', #red
7458 sub statuscolor { shift->cust_statuscolor(@_); }
7460 sub cust_statuscolor {
7462 $statuscolor{$self->cust_status};
7467 Returns an array of hashes representing the customer's RT tickets.
7474 my $num = $conf->config('cust_main-max_tickets') || 10;
7477 if ( $conf->config('ticket_system') ) {
7478 unless ( $conf->config('ticket_system-custom_priority_field') ) {
7480 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7484 foreach my $priority (
7485 $conf->config('ticket_system-custom_priority_field-values'), ''
7487 last if scalar(@tickets) >= $num;
7489 @{ FS::TicketSystem->customer_tickets( $self->custnum,
7490 $num - scalar(@tickets),
7500 # Return services representing svc_accts in customer support packages
7501 sub support_services {
7503 my %packages = map { $_ => 1 } $conf->config('support_packages');
7505 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7506 grep { $_->part_svc->svcdb eq 'svc_acct' }
7507 map { $_->cust_svc }
7508 grep { exists $packages{ $_->pkgpart } }
7509 $self->ncancelled_pkgs;
7513 # Return a list of latitude/longitude for one of the services (if any)
7514 sub service_coordinates {
7518 grep { $_->latitude && $_->longitude }
7520 map { $_->cust_svc }
7521 $self->ncancelled_pkgs;
7523 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7528 =head1 CLASS METHODS
7534 Class method that returns the list of possible status strings for customers
7535 (see L<the status method|/status>). For example:
7537 @statuses = FS::cust_main->statuses();
7542 #my $self = shift; #could be class...
7548 Returns an SQL expression identifying prospective cust_main records (customers
7549 with no packages ever ordered)
7553 use vars qw($select_count_pkgs);
7554 $select_count_pkgs =
7555 "SELECT COUNT(*) FROM cust_pkg
7556 WHERE cust_pkg.custnum = cust_main.custnum";
7558 sub select_count_pkgs_sql {
7563 " 0 = ( $select_count_pkgs ) ";
7568 Returns an SQL expression identifying ordered cust_main records (customers with
7569 recurring packages not yet setup).
7574 FS::cust_main->none_active_sql.
7575 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
7580 Returns an SQL expression identifying active cust_main records (customers with
7581 active recurring packages).
7586 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7589 =item none_active_sql
7591 Returns an SQL expression identifying cust_main records with no active
7592 recurring packages. This includes customers of status prospect, ordered,
7593 inactive, and suspended.
7597 sub none_active_sql {
7598 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7603 Returns an SQL expression identifying inactive cust_main records (customers with
7604 no active recurring packages, but otherwise unsuspended/uncancelled).
7609 FS::cust_main->none_active_sql.
7610 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
7616 Returns an SQL expression identifying suspended cust_main records.
7621 sub suspended_sql { susp_sql(@_); }
7623 FS::cust_main->none_active_sql.
7624 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
7630 Returns an SQL expression identifying cancelled cust_main records.
7634 sub cancelled_sql { cancel_sql(@_); }
7637 my $recurring_sql = FS::cust_pkg->recurring_sql;
7638 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7641 0 < ( $select_count_pkgs )
7642 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
7643 AND 0 = ( $select_count_pkgs AND $recurring_sql
7644 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7646 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7652 =item uncancelled_sql
7654 Returns an SQL expression identifying un-cancelled cust_main records.
7658 sub uncancelled_sql { uncancel_sql(@_); }
7659 sub uncancel_sql { "
7660 ( 0 < ( $select_count_pkgs
7661 AND ( cust_pkg.cancel IS NULL
7662 OR cust_pkg.cancel = 0
7665 OR 0 = ( $select_count_pkgs )
7671 Returns an SQL fragment to retreive the balance.
7676 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7677 WHERE cust_bill.custnum = cust_main.custnum )
7678 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
7679 WHERE cust_pay.custnum = cust_main.custnum )
7680 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
7681 WHERE cust_credit.custnum = cust_main.custnum )
7682 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
7683 WHERE cust_refund.custnum = cust_main.custnum )
7686 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
7688 Returns an SQL fragment to retreive the balance for this customer, optionally
7689 considering invoices with date earlier than START_TIME, and not
7690 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7691 total_unapplied_payments).
7693 Times are specified as SQL fragments or numeric
7694 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7695 L<Date::Parse> for conversion functions. The empty string can be passed
7696 to disable that time constraint completely.
7698 Available options are:
7702 =item unapplied_date
7704 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)
7709 set to true to remove all customer comparison clauses, for totals
7714 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
7719 JOIN clause (typically used with the total option)
7723 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
7724 time will be ignored. Note that START_TIME and END_TIME only limit the date
7725 range for invoices and I<unapplied> payments, credits, and refunds.
7731 sub balance_date_sql {
7732 my( $class, $start, $end, %opt ) = @_;
7734 my $cutoff = $opt{'cutoff'};
7736 my $owed = FS::cust_bill->owed_sql($cutoff);
7737 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
7738 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
7739 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7741 my $j = $opt{'join'} || '';
7743 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
7744 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
7745 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
7746 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
7748 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
7749 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
7750 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
7751 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
7756 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
7758 Returns an SQL fragment to retreive the total unapplied payments for this
7759 customer, only considering invoices with date earlier than START_TIME, and
7760 optionally not later than END_TIME.
7762 Times are specified as SQL fragments or numeric
7763 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7764 L<Date::Parse> for conversion functions. The empty string can be passed
7765 to disable that time constraint completely.
7767 Available options are:
7771 sub unapplied_payments_date_sql {
7772 my( $class, $start, $end, %opt ) = @_;
7774 my $cutoff = $opt{'cutoff'};
7776 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7778 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
7779 'unapplied_date'=>1 );
7781 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
7784 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7786 Helper method for balance_date_sql; name (and usage) subject to change
7787 (suggestions welcome).
7789 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
7790 cust_refund, cust_credit or cust_pay).
7792 If TABLE is "cust_bill" or the unapplied_date option is true, only
7793 considers records with date earlier than START_TIME, and optionally not
7794 later than END_TIME .
7798 sub _money_table_where {
7799 my( $class, $table, $start, $end, %opt ) = @_;
7802 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
7803 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
7804 push @where, "$table._date <= $start" if defined($start) && length($start);
7805 push @where, "$table._date > $end" if defined($end) && length($end);
7807 push @where, @{$opt{'where'}} if $opt{'where'};
7808 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
7814 =item search HASHREF
7818 Returns a qsearch hash expression to search for parameters specified in
7819 HASHREF. Valid parameters are
7827 =item cancelled_pkgs
7833 listref of start date, end date
7843 =item current_balance
7845 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
7849 =item flattened_pkgs
7858 my ($class, $params) = @_;
7869 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
7871 "cust_main.agentnum = $1";
7875 # do the same for user
7878 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
7880 "cust_main.usernum = $1";
7887 #prospect ordered active inactive suspended cancelled
7888 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
7889 my $method = $params->{'status'}. '_sql';
7890 #push @where, $class->$method();
7891 push @where, FS::cust_main->$method();
7895 # parse cancelled package checkbox
7900 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
7901 unless $params->{'cancelled_pkgs'};
7904 # parse without census tract checkbox
7907 push @where, "(censustract = '' or censustract is null)"
7908 if $params->{'no_censustract'};
7914 foreach my $field (qw( signupdate )) {
7916 next unless exists($params->{$field});
7918 my($beginning, $ending, $hour) = @{$params->{$field}};
7921 "cust_main.$field IS NOT NULL",
7922 "cust_main.$field >= $beginning",
7923 "cust_main.$field <= $ending";
7925 # XXX: do this for mysql and/or pull it out of here
7927 if ($dbh->{Driver}->{Name} eq 'Pg') {
7928 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
7931 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
7935 $orderby ||= "ORDER BY cust_main.$field";
7943 if ( $params->{'classnum'} ) {
7945 my @classnum = ref( $params->{'classnum'} )
7946 ? @{ $params->{'classnum'} }
7947 : ( $params->{'classnum'} );
7949 @classnum = grep /^(\d*)$/, @classnum;
7952 push @where, '( '. join(' OR ', map {
7953 $_ ? "cust_main.classnum = $_"
7954 : "cust_main.classnum IS NULL"
7967 if ( $params->{'payby'} ) {
7969 my @payby = ref( $params->{'payby'} )
7970 ? @{ $params->{'payby'} }
7971 : ( $params->{'payby'} );
7973 @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
7975 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
7981 # paydate_year / paydate_month
7984 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
7986 $params->{'paydate_month'} =~ /^(\d\d?)$/
7987 or die "paydate_year without paydate_month?";
7991 'paydate IS NOT NULL',
7993 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
8001 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
8003 if ( $1 eq 'NULL' ) {
8005 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
8008 "cust_main.invoice_terms IS NOT NULL",
8009 "cust_main.invoice_terms = '$1'";
8017 if ( $params->{'current_balance'} ) {
8019 #my $balance_sql = $class->balance_sql();
8020 my $balance_sql = FS::cust_main->balance_sql();
8022 my @current_balance =
8023 ref( $params->{'current_balance'} )
8024 ? @{ $params->{'current_balance'} }
8025 : ( $params->{'current_balance'} );
8027 push @where, map { s/current_balance/$balance_sql/; $_ }
8036 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
8038 "cust_main.custbatch = '$1'";
8042 # setup queries, subs, etc. for the search
8045 $orderby ||= 'ORDER BY custnum';
8047 # here is the agent virtualization
8048 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
8050 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
8052 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
8054 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
8056 my $select = join(', ',
8057 'cust_main.custnum',
8058 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
8061 my(@extra_headers) = ();
8062 my(@extra_fields) = ();
8064 if ($params->{'flattened_pkgs'}) {
8066 if ($dbh->{Driver}->{Name} eq 'Pg') {
8068 $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";
8070 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
8071 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
8072 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
8074 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
8075 "omitting packing information from report.";
8078 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";
8080 my $sth = dbh->prepare($header_query) or die dbh->errstr;
8081 $sth->execute() or die $sth->errstr;
8082 my $headerrow = $sth->fetchrow_arrayref;
8083 my $headercount = $headerrow ? $headerrow->[0] : 0;
8084 while($headercount) {
8085 unshift @extra_headers, "Package ". $headercount;
8086 unshift @extra_fields, eval q!sub {my $c = shift;
8087 my @a = split '\|', $c->magic;
8088 my $p = $a[!.--$headercount. q!];
8096 'table' => 'cust_main',
8097 'select' => $select,
8099 'extra_sql' => $extra_sql,
8100 'order_by' => $orderby,
8101 'count_query' => $count_query,
8102 'extra_headers' => \@extra_headers,
8103 'extra_fields' => \@extra_fields,
8108 =item email_search_result HASHREF
8112 Emails a notice to the specified customers.
8114 Valid parameters are those of the L<search> method, plus the following:
8136 Optional job queue job for status updates.
8140 Returns an error message, or false for success.
8142 If an error occurs during any email, stops the enture send and returns that
8143 error. Presumably if you're getting SMTP errors aborting is better than
8144 retrying everything.
8148 sub email_search_result {
8149 my($class, $params) = @_;
8151 my $from = delete $params->{from};
8152 my $subject = delete $params->{subject};
8153 my $html_body = delete $params->{html_body};
8154 my $text_body = delete $params->{text_body};
8157 my $job = delete $params->{'job'}
8158 or die "email_search_result must run from the job queue.\n";
8160 $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
8161 unless ref($params->{'payby'});
8163 my $sql_query = $class->search($params);
8165 my $count_query = delete($sql_query->{'count_query'});
8166 my $count_sth = dbh->prepare($count_query)
8167 or die "Error preparing $count_query: ". dbh->errstr;
8169 or die "Error executing $count_query: ". $count_sth->errstr;
8170 my $count_arrayref = $count_sth->fetchrow_arrayref;
8171 my $num_cust = $count_arrayref->[0];
8173 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
8174 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
8177 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
8178 my @retry_jobs = ();
8181 #eventually order+limit magic to reduce memory use?
8182 foreach my $cust_main ( qsearch($sql_query) ) {
8184 #progressbar first, so that the count is right
8186 if ( time - $min_sec > $last ) {
8187 my $error = $job->update_statustext(
8188 int( 100 * $num / $num_cust )
8190 die $error if $error;
8194 my $to = $cust_main->invoicing_list_emailonly_scalar;
8200 'subject' => $subject,
8201 'html_body' => $html_body,
8202 'text_body' => $text_body,
8205 $error = send_email( generate_email( @message ) );
8208 # queue the sending of this message so that the user can see what we
8209 # tried to do, and retry if desired
8210 my $queue = new FS::queue {
8211 'job' => 'FS::Misc::process_send_email',
8212 'custnum' => $cust_main->custnum,
8213 'status' => 'failed',
8214 'statustext' => $error,
8216 $queue->insert(@message);
8217 push @retry_jobs, $queue;
8224 if($success == 0 and
8225 (scalar(@retry_jobs) > 10 or $num == $num_cust)
8227 # 10 is arbitrary, but if we have enough failures, that's
8228 # probably a configuration or network problem, and we
8229 # abort the batch and run away screaming.
8230 # We NEVER do this if anything was successfully sent.
8231 $_->delete foreach (@retry_jobs);
8232 return "multiple failures: '$error'\n";
8237 # fail the job, but with a status message that makes it clear
8238 # something was sent.
8239 return "Sent $success, failed ".scalar(@retry_jobs).". Failed attempts placed in job queue.\n";
8245 sub process_email_search_result {
8247 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
8249 my $param = thaw(decode_base64(shift));
8250 warn Dumper($param) if $DEBUG;
8252 $param->{'job'} = $job;
8254 $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
8255 unless ref($param->{'payby'});
8257 my $error = FS::cust_main->email_search_result( $param );
8258 die $error if $error;
8262 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
8264 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
8265 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
8266 specified (the appropriate ship_ field is also searched).
8268 Additional options are the same as FS::Record::qsearch
8273 my( $self, $fuzzy, $hash, @opt) = @_;
8278 check_and_rebuild_fuzzyfiles();
8279 foreach my $field ( keys %$fuzzy ) {
8281 my $all = $self->all_X($field);
8282 next unless scalar(@$all);
8285 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
8288 foreach ( keys %match ) {
8289 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
8290 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
8293 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
8296 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
8298 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
8306 Returns a masked version of the named field
8311 my ($self,$field) = @_;
8315 'x'x(length($self->getfield($field))-4).
8316 substr($self->getfield($field), (length($self->getfield($field))-4));
8326 =item smart_search OPTION => VALUE ...
8328 Accepts the following options: I<search>, the string to search for. The string
8329 will be searched for as a customer number, phone number, name or company name,
8330 as an exact, or, in some cases, a substring or fuzzy match (see the source code
8331 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
8332 skip fuzzy matching when an exact match is found.
8334 Any additional options are treated as an additional qualifier on the search
8337 Returns a (possibly empty) array of FS::cust_main objects.
8344 #here is the agent virtualization
8345 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8349 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
8350 my $search = delete $options{'search'};
8351 ( my $alphanum_search = $search ) =~ s/\W//g;
8353 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8355 #false laziness w/Record::ut_phone
8356 my $phonen = "$1-$2-$3";
8357 $phonen .= " x$4" if $4;
8359 push @cust_main, qsearch( {
8360 'table' => 'cust_main',
8361 'hashref' => { %options },
8362 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8364 join(' OR ', map "$_ = '$phonen'",
8365 qw( daytime night fax
8366 ship_daytime ship_night ship_fax )
8369 " AND $agentnums_sql", #agent virtualization
8372 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8373 #try looking for matches with extensions unless one was specified
8375 push @cust_main, qsearch( {
8376 'table' => 'cust_main',
8377 'hashref' => { %options },
8378 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8380 join(' OR ', map "$_ LIKE '$phonen\%'",
8382 ship_daytime ship_night )
8385 " AND $agentnums_sql", #agent virtualization
8390 # custnum search (also try agent_custid), with some tweaking options if your
8391 # legacy cust "numbers" have letters
8394 if ( $search =~ /^\s*(\d+)\s*$/
8395 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8396 && $search =~ /^\s*(\w\w?\d+)\s*$/
8398 || ( $conf->exists('address1-search' )
8399 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
8406 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
8407 push @cust_main, qsearch( {
8408 'table' => 'cust_main',
8409 'hashref' => { 'custnum' => $num, %options },
8410 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8414 push @cust_main, qsearch( {
8415 'table' => 'cust_main',
8416 'hashref' => { 'agent_custid' => $num, %options },
8417 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8420 if ( $conf->exists('address1-search') ) {
8421 my $len = length($num);
8423 foreach my $prefix ( '', 'ship_' ) {
8424 push @cust_main, qsearch( {
8425 'table' => 'cust_main',
8426 'hashref' => { %options, },
8428 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8429 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
8430 " AND $agentnums_sql",
8435 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8437 my($company, $last, $first) = ( $1, $2, $3 );
8439 # "Company (Last, First)"
8440 #this is probably something a browser remembered,
8441 #so just do an exact search (but case-insensitive, so USPS standardization
8442 #doesn't throw a wrench in the works)
8444 foreach my $prefix ( '', 'ship_' ) {
8445 push @cust_main, qsearch( {
8446 'table' => 'cust_main',
8447 'hashref' => { %options },
8449 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8451 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
8452 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
8453 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
8459 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8460 # try (ship_){last,company}
8464 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8465 # # full strings the browser remembers won't work
8466 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8468 use Lingua::EN::NameParse;
8469 my $NameParse = new Lingua::EN::NameParse(
8471 allow_reversed => 1,
8474 my($last, $first) = ( '', '' );
8475 #maybe disable this too and just rely on NameParse?
8476 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8478 ($last, $first) = ( $1, $2 );
8480 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
8481 } elsif ( ! $NameParse->parse($value) ) {
8483 my %name = $NameParse->components;
8484 $first = $name{'given_name_1'};
8485 $last = $name{'surname_1'};
8489 if ( $first && $last ) {
8491 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8494 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8496 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8497 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8500 push @cust_main, qsearch( {
8501 'table' => 'cust_main',
8502 'hashref' => \%options,
8503 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8506 # or it just be something that was typed in... (try that in a sec)
8510 my $q_value = dbh->quote($value);
8513 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8514 $sql .= " ( LOWER(last) = $q_value
8515 OR LOWER(company) = $q_value
8516 OR LOWER(ship_last) = $q_value
8517 OR LOWER(ship_company) = $q_value
8519 $sql .= " OR LOWER(address1) = $q_value
8520 OR LOWER(ship_address1) = $q_value
8522 if $conf->exists('address1-search');
8525 push @cust_main, qsearch( {
8526 'table' => 'cust_main',
8527 'hashref' => \%options,
8528 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8531 #no exact match, trying substring/fuzzy
8532 #always do substring & fuzzy (unless they're explicity config'ed off)
8533 #getting complaints searches are not returning enough
8534 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8536 #still some false laziness w/search (was search/cust_main.cgi)
8541 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
8542 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8545 if ( $first && $last ) {
8548 { 'first' => { op=>'ILIKE', value=>"%$first%" },
8549 'last' => { op=>'ILIKE', value=>"%$last%" },
8551 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
8552 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
8559 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
8560 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
8564 if ( $conf->exists('address1-search') ) {
8566 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
8567 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
8571 foreach my $hashref ( @hashrefs ) {
8573 push @cust_main, qsearch( {
8574 'table' => 'cust_main',
8575 'hashref' => { %$hashref,
8578 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8587 " AND $agentnums_sql", #extra_sql #agent virtualization
8590 if ( $first && $last ) {
8591 push @cust_main, FS::cust_main->fuzzy_search(
8592 { 'last' => $last, #fuzzy hashref
8593 'first' => $first }, #
8597 foreach my $field ( 'last', 'company' ) {
8599 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8601 if ( $conf->exists('address1-search') ) {
8603 FS::cust_main->fuzzy_search( { 'address1' => $value }, @fuzopts );
8610 #eliminate duplicates
8612 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8620 Accepts the following options: I<email>, the email address to search for. The
8621 email address will be searched for as an email invoice destination and as an
8624 #Any additional options are treated as an additional qualifier on the search
8625 #(i.e. I<agentnum>).
8627 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8637 my $email = delete $options{'email'};
8639 #we're only being used by RT at the moment... no agent virtualization yet
8640 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8644 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8646 my ( $user, $domain ) = ( $1, $2 );
8648 warn "$me smart_search: searching for $user in domain $domain"
8654 'table' => 'cust_main_invoice',
8655 'hashref' => { 'dest' => $email },
8662 map $_->cust_svc->cust_pkg,
8664 'table' => 'svc_acct',
8665 'hashref' => { 'username' => $user, },
8667 'AND ( SELECT domain FROM svc_domain
8668 WHERE svc_acct.domsvc = svc_domain.svcnum
8669 ) = '. dbh->quote($domain),
8675 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8677 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8684 =item check_and_rebuild_fuzzyfiles
8688 sub check_and_rebuild_fuzzyfiles {
8689 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8690 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8693 =item rebuild_fuzzyfiles
8697 sub rebuild_fuzzyfiles {
8699 use Fcntl qw(:flock);
8701 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8702 mkdir $dir, 0700 unless -d $dir;
8704 foreach my $fuzzy ( @fuzzyfields ) {
8706 open(LOCK,">>$dir/cust_main.$fuzzy")
8707 or die "can't open $dir/cust_main.$fuzzy: $!";
8709 or die "can't lock $dir/cust_main.$fuzzy: $!";
8711 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8712 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8714 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8715 my $sth = dbh->prepare("SELECT $field FROM cust_main".
8716 " WHERE $field != '' AND $field IS NOT NULL");
8717 $sth->execute or die $sth->errstr;
8719 while ( my $row = $sth->fetchrow_arrayref ) {
8720 print CACHE $row->[0]. "\n";
8725 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8727 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8738 my( $self, $field ) = @_;
8739 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8740 open(CACHE,"<$dir/cust_main.$field")
8741 or die "can't open $dir/cust_main.$field: $!";
8742 my @array = map { chomp; $_; } <CACHE>;
8747 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
8751 sub append_fuzzyfiles {
8752 #my( $first, $last, $company ) = @_;
8754 &check_and_rebuild_fuzzyfiles;
8756 use Fcntl qw(:flock);
8758 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8760 foreach my $field (@fuzzyfields) {
8765 open(CACHE,">>$dir/cust_main.$field")
8766 or die "can't open $dir/cust_main.$field: $!";
8767 flock(CACHE,LOCK_EX)
8768 or die "can't lock $dir/cust_main.$field: $!";
8770 print CACHE "$value\n";
8772 flock(CACHE,LOCK_UN)
8773 or die "can't unlock $dir/cust_main.$field: $!";
8788 #warn join('-',keys %$param);
8789 my $fh = $param->{filehandle};
8790 my @fields = @{$param->{fields}};
8792 eval "use Text::CSV_XS;";
8795 my $csv = new Text::CSV_XS;
8802 local $SIG{HUP} = 'IGNORE';
8803 local $SIG{INT} = 'IGNORE';
8804 local $SIG{QUIT} = 'IGNORE';
8805 local $SIG{TERM} = 'IGNORE';
8806 local $SIG{TSTP} = 'IGNORE';
8807 local $SIG{PIPE} = 'IGNORE';
8809 my $oldAutoCommit = $FS::UID::AutoCommit;
8810 local $FS::UID::AutoCommit = 0;
8813 #while ( $columns = $csv->getline($fh) ) {
8815 while ( defined($line=<$fh>) ) {
8817 $csv->parse($line) or do {
8818 $dbh->rollback if $oldAutoCommit;
8819 return "can't parse: ". $csv->error_input();
8822 my @columns = $csv->fields();
8823 #warn join('-',@columns);
8826 foreach my $field ( @fields ) {
8827 $row{$field} = shift @columns;
8830 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
8831 unless ( $cust_main ) {
8832 $dbh->rollback if $oldAutoCommit;
8833 return "unknown custnum $row{'custnum'}";
8836 if ( $row{'amount'} > 0 ) {
8837 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8839 $dbh->rollback if $oldAutoCommit;
8843 } elsif ( $row{'amount'} < 0 ) {
8844 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8847 $dbh->rollback if $oldAutoCommit;
8857 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8859 return "Empty file!" unless $imported;
8865 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8867 Deprecated. Use event notification and message templates
8868 (L<FS::msg_template>) instead.
8870 Sends a templated email notification to the customer (see L<Text::Template>).
8872 OPTIONS is a hash and may include
8874 I<from> - the email sender (default is invoice_from)
8876 I<to> - comma-separated scalar or arrayref of recipients
8877 (default is invoicing_list)
8879 I<subject> - The subject line of the sent email notification
8880 (default is "Notice from company_name")
8882 I<extra_fields> - a hashref of name/value pairs which will be substituted
8885 The following variables are vavailable in the template.
8887 I<$first> - the customer first name
8888 I<$last> - the customer last name
8889 I<$company> - the customer company
8890 I<$payby> - a description of the method of payment for the customer
8891 # would be nice to use FS::payby::shortname
8892 I<$payinfo> - the account information used to collect for this customer
8893 I<$expdate> - the expiration of the customer payment in seconds from epoch
8898 my ($self, $template, %options) = @_;
8900 return unless $conf->exists($template);
8902 my $from = $conf->config('invoice_from', $self->agentnum)
8903 if $conf->exists('invoice_from', $self->agentnum);
8904 $from = $options{from} if exists($options{from});
8906 my $to = join(',', $self->invoicing_list_emailonly);
8907 $to = $options{to} if exists($options{to});
8909 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
8910 if $conf->exists('company_name', $self->agentnum);
8911 $subject = $options{subject} if exists($options{subject});
8913 my $notify_template = new Text::Template (TYPE => 'ARRAY',
8914 SOURCE => [ map "$_\n",
8915 $conf->config($template)]
8917 or die "can't create new Text::Template object: Text::Template::ERROR";
8918 $notify_template->compile()
8919 or die "can't compile template: Text::Template::ERROR";
8921 $FS::notify_template::_template::company_name =
8922 $conf->config('company_name', $self->agentnum);
8923 $FS::notify_template::_template::company_address =
8924 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
8926 my $paydate = $self->paydate || '2037-12-31';
8927 $FS::notify_template::_template::first = $self->first;
8928 $FS::notify_template::_template::last = $self->last;
8929 $FS::notify_template::_template::company = $self->company;
8930 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
8931 my $payby = $self->payby;
8932 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8933 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8935 #credit cards expire at the end of the month/year of their exp date
8936 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8937 $FS::notify_template::_template::payby = 'credit card';
8938 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8939 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8941 }elsif ($payby eq 'COMP') {
8942 $FS::notify_template::_template::payby = 'complimentary account';
8944 $FS::notify_template::_template::payby = 'current method';
8946 $FS::notify_template::_template::expdate = $expire_time;
8948 for (keys %{$options{extra_fields}}){
8950 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
8953 send_email(from => $from,
8955 subject => $subject,
8956 body => $notify_template->fill_in( PACKAGE =>
8957 'FS::notify_template::_template' ),
8962 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8964 Generates a templated notification to the customer (see L<Text::Template>).
8966 OPTIONS is a hash and may include
8968 I<extra_fields> - a hashref of name/value pairs which will be substituted
8969 into the template. These values may override values mentioned below
8970 and those from the customer record.
8972 The following variables are available in the template instead of or in addition
8973 to the fields of the customer record.
8975 I<$payby> - a description of the method of payment for the customer
8976 # would be nice to use FS::payby::shortname
8977 I<$payinfo> - the masked account information used to collect for this customer
8978 I<$expdate> - the expiration of the customer payment method in seconds from epoch
8979 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
8983 # a lot like cust_bill::print_latex
8984 sub generate_letter {
8985 my ($self, $template, %options) = @_;
8987 return unless $conf->exists($template);
8989 my $letter_template = new Text::Template
8991 SOURCE => [ map "$_\n", $conf->config($template)],
8992 DELIMITERS => [ '[@--', '--@]' ],
8994 or die "can't create new Text::Template object: Text::Template::ERROR";
8996 $letter_template->compile()
8997 or die "can't compile template: Text::Template::ERROR";
8999 my %letter_data = map { $_ => $self->$_ } $self->fields;
9000 $letter_data{payinfo} = $self->mask_payinfo;
9002 #my $paydate = $self->paydate || '2037-12-31';
9003 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
9005 my $payby = $self->payby;
9006 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
9007 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
9009 #credit cards expire at the end of the month/year of their exp date
9010 if ($payby eq 'CARD' || $payby eq 'DCRD') {
9011 $letter_data{payby} = 'credit card';
9012 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
9013 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
9015 }elsif ($payby eq 'COMP') {
9016 $letter_data{payby} = 'complimentary account';
9018 $letter_data{payby} = 'current method';
9020 $letter_data{expdate} = $expire_time;
9022 for (keys %{$options{extra_fields}}){
9023 $letter_data{$_} = $options{extra_fields}->{$_};
9026 unless(exists($letter_data{returnaddress})){
9027 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
9028 $self->agent_template)
9030 if ( length($retadd) ) {
9031 $letter_data{returnaddress} = $retadd;
9032 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
9033 $letter_data{returnaddress} =
9034 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
9038 ( $conf->config('company_name', $self->agentnum),
9039 $conf->config('company_address', $self->agentnum),
9043 $letter_data{returnaddress} = '~';
9047 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
9049 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
9051 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
9053 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
9057 ) or die "can't open temp file: $!\n";
9058 print $lh $conf->config_binary('logo.eps', $self->agentnum)
9059 or die "can't write temp file: $!\n";
9061 $letter_data{'logo_file'} = $lh->filename;
9063 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
9067 ) or die "can't open temp file: $!\n";
9069 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
9071 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
9072 return ($1, $letter_data{'logo_file'});
9076 =item print_ps TEMPLATE
9078 Returns an postscript letter filled in from TEMPLATE, as a scalar.
9084 my($file, $lfile) = $self->generate_letter(@_);
9085 my $ps = FS::Misc::generate_ps($file);
9086 unlink($file.'.tex');
9092 =item print TEMPLATE
9094 Prints the filled in template.
9096 TEMPLATE is the name of a L<Text::Template> to fill in and print.
9100 sub queueable_print {
9103 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
9104 or die "invalid customer number: " . $opt{custvnum};
9106 my $error = $self->print( $opt{template} );
9107 die $error if $error;
9111 my ($self, $template) = (shift, shift);
9112 do_print [ $self->print_ps($template) ];
9115 #these three subs should just go away once agent stuff is all config overrides
9117 sub agent_template {
9119 $self->_agent_plandata('agent_templatename');
9122 sub agent_invoice_from {
9124 $self->_agent_plandata('agent_invoice_from');
9127 sub _agent_plandata {
9128 my( $self, $option ) = @_;
9130 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
9131 #agent-specific Conf
9133 use FS::part_event::Condition;
9135 my $agentnum = $self->agentnum;
9137 my $regexp = regexp_sql();
9139 my $part_event_option =
9141 'select' => 'part_event_option.*',
9142 'table' => 'part_event_option',
9144 LEFT JOIN part_event USING ( eventpart )
9145 LEFT JOIN part_event_option AS peo_agentnum
9146 ON ( part_event.eventpart = peo_agentnum.eventpart
9147 AND peo_agentnum.optionname = 'agentnum'
9148 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
9150 LEFT JOIN part_event_condition
9151 ON ( part_event.eventpart = part_event_condition.eventpart
9152 AND part_event_condition.conditionname = 'cust_bill_age'
9154 LEFT JOIN part_event_condition_option
9155 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
9156 AND part_event_condition_option.optionname = 'age'
9159 #'hashref' => { 'optionname' => $option },
9160 #'hashref' => { 'part_event_option.optionname' => $option },
9162 " WHERE part_event_option.optionname = ". dbh->quote($option).
9163 " AND action = 'cust_bill_send_agent' ".
9164 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
9165 " AND peo_agentnum.optionname = 'agentnum' ".
9166 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
9168 CASE WHEN part_event_condition_option.optionname IS NULL
9170 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
9172 , part_event.weight".
9176 unless ( $part_event_option ) {
9177 return $self->agent->invoice_template || ''
9178 if $option eq 'agent_templatename';
9182 $part_event_option->optionvalue;
9186 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
9188 Subroutine (not a method), designed to be called from the queue.
9190 Takes a list of options and values.
9192 Pulls up the customer record via the custnum option and calls bill_and_collect.
9197 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
9199 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
9200 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
9202 $cust_main->bill_and_collect( %args );
9205 sub process_bill_and_collect {
9207 my $param = thaw(decode_base64(shift));
9208 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
9209 or die "custnum '$param->{custnum}' not found!\n";
9210 $param->{'job'} = $job;
9211 $param->{'fatal'} = 1; # runs from job queue, will be caught
9212 $param->{'retry'} = 1;
9214 $cust_main->bill_and_collect( %$param );
9217 sub _upgrade_data { #class method
9218 my ($class, %opts) = @_;
9220 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
9221 my $sth = dbh->prepare($sql) or die dbh->errstr;
9222 $sth->execute or die $sth->errstr;
9224 local($ignore_expired_card) = 1;
9225 local($skip_fuzzyfiles) = 1;
9226 $class->_upgrade_otaker(%opts);
9236 The delete method should possibly take an FS::cust_main object reference
9237 instead of a scalar customer number.
9239 Bill and collect options should probably be passed as references instead of a
9242 There should probably be a configuration file with a list of allowed credit
9245 No multiple currency support (probably a larger project than just this module).
9247 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
9249 Birthdates rely on negative epoch values.
9251 The payby for card/check batches is broken. With mixed batching, bad
9254 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
9258 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
9259 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
9260 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.