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;
60 use FS::cust_credit_bill;
61 use FS::cust_bill_pay;
62 use FS::prepay_credit;
66 use FS::part_event_condition;
70 use FS::payment_gateway;
71 use FS::agent_payment_gateway;
75 @EXPORT_OK = qw( smart_search );
77 $realtime_bop_decline_quiet = 0;
79 # 1 is mostly method/subroutine entry and options
80 # 2 traces progress of some operations
81 # 3 is even more information including possibly sensitive data
83 $me = '[FS::cust_main]';
86 $ignore_expired_card = 0;
89 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
91 @encrypted_fields = ('payinfo', 'paycvv');
92 sub nohistory_fields { ('payinfo', 'paycvv'); }
94 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
96 #ask FS::UID to run this stuff for us later
97 #$FS::UID::callback{'FS::cust_main'} = sub {
98 install_callback FS::UID sub {
100 #yes, need it for stuff below (prolly should be cached)
105 my ( $hashref, $cache ) = @_;
106 if ( exists $hashref->{'pkgnum'} ) {
107 #@{ $self->{'_pkgnum'} } = ();
108 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
109 $self->{'_pkgnum'} = $subcache;
110 #push @{ $self->{'_pkgnum'} },
111 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
117 FS::cust_main - Object methods for cust_main records
123 $record = new FS::cust_main \%hash;
124 $record = new FS::cust_main { 'column' => 'value' };
126 $error = $record->insert;
128 $error = $new_record->replace($old_record);
130 $error = $record->delete;
132 $error = $record->check;
134 @cust_pkg = $record->all_pkgs;
136 @cust_pkg = $record->ncancelled_pkgs;
138 @cust_pkg = $record->suspended_pkgs;
140 $error = $record->bill;
141 $error = $record->bill %options;
142 $error = $record->bill 'time' => $time;
144 $error = $record->collect;
145 $error = $record->collect %options;
146 $error = $record->collect 'invoice_time' => $time,
151 An FS::cust_main object represents a customer. FS::cust_main inherits from
152 FS::Record. The following fields are currently supported:
158 Primary key (assigned automatically for new customers)
162 Agent (see L<FS::agent>)
166 Advertising source (see L<FS::part_referral>)
178 Cocial security number (optional)
194 (optional, see L<FS::cust_main_county>)
198 (see L<FS::cust_main_county>)
204 (see L<FS::cust_main_county>)
240 (optional, see L<FS::cust_main_county>)
244 (see L<FS::cust_main_county>)
250 (see L<FS::cust_main_county>)
266 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
270 Payment Information (See L<FS::payinfo_Mixin> for data format)
274 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
278 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
282 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
286 Start date month (maestro/solo cards only)
290 Start date year (maestro/solo cards only)
294 Issue number (maestro/solo cards only)
298 Name on card or billing name
302 IP address from which payment information was received
306 Tax exempt, empty or `Y'
310 Order taker (see L<FS::access_user>)
316 =item referral_custnum
318 Referring customer number
322 Enable individual CDR spooling, empty or `Y'
326 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
330 Discourage individual CDR printing, empty or `Y'
340 Creates a new customer. To add the customer to the database, see L<"insert">.
342 Note that this stores the hash reference, not a distinct copy of the hash it
343 points to. You can ask the object for a copy with the I<hash> method.
347 sub table { 'cust_main'; }
349 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
351 Adds this customer to the database. If there is an error, returns the error,
352 otherwise returns false.
354 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
355 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
356 are inserted atomicly, or the transaction is rolled back. Passing an empty
357 hash reference is equivalent to not supplying this parameter. There should be
358 a better explanation of this, but until then, here's an example:
361 tie %hash, 'Tie::RefHash'; #this part is important
363 $cust_pkg => [ $svc_acct ],
366 $cust_main->insert( \%hash );
368 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
369 be set as the invoicing list (see L<"invoicing_list">). Errors return as
370 expected and rollback the entire transaction; it is not necessary to call
371 check_invoicing_list first. The invoicing_list is set after the records in the
372 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
373 invoicing_list destination to the newly-created svc_acct. Here's an example:
375 $cust_main->insert( {}, [ $email, 'POST' ] );
377 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
379 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
380 on the supplied jobnum (they will not run until the specific job completes).
381 This can be used to defer provisioning until some action completes (such
382 as running the customer's credit card successfully).
384 The I<noexport> option is deprecated. If I<noexport> is set true, no
385 provisioning jobs (exports) are scheduled. (You can schedule them later with
386 the B<reexport> method.)
388 The I<tax_exemption> option can be set to an arrayref of tax names.
389 FS::cust_main_exemption records will be created and inserted.
395 my $cust_pkgs = @_ ? shift : {};
396 my $invoicing_list = @_ ? shift : '';
398 warn "$me insert called with options ".
399 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
402 local $SIG{HUP} = 'IGNORE';
403 local $SIG{INT} = 'IGNORE';
404 local $SIG{QUIT} = 'IGNORE';
405 local $SIG{TERM} = 'IGNORE';
406 local $SIG{TSTP} = 'IGNORE';
407 local $SIG{PIPE} = 'IGNORE';
409 my $oldAutoCommit = $FS::UID::AutoCommit;
410 local $FS::UID::AutoCommit = 0;
413 my $prepay_identifier = '';
414 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
416 if ( $self->payby eq 'PREPAY' ) {
418 $self->payby('BILL');
419 $prepay_identifier = $self->payinfo;
422 warn " looking up prepaid card $prepay_identifier\n"
425 my $error = $self->get_prepay( $prepay_identifier,
426 'amount_ref' => \$amount,
427 'seconds_ref' => \$seconds,
428 'upbytes_ref' => \$upbytes,
429 'downbytes_ref' => \$downbytes,
430 'totalbytes_ref' => \$totalbytes,
433 $dbh->rollback if $oldAutoCommit;
434 #return "error applying prepaid card (transaction rolled back): $error";
438 $payby = 'PREP' if $amount;
440 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
443 $self->payby('BILL');
444 $amount = $self->paid;
448 warn " inserting $self\n"
451 $self->signupdate(time) unless $self->signupdate;
453 $self->auto_agent_custid()
454 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
456 my $error = $self->SUPER::insert;
458 $dbh->rollback if $oldAutoCommit;
459 #return "inserting cust_main record (transaction rolled back): $error";
463 warn " setting invoicing list\n"
466 if ( $invoicing_list ) {
467 $error = $self->check_invoicing_list( $invoicing_list );
469 $dbh->rollback if $oldAutoCommit;
470 #return "checking invoicing_list (transaction rolled back): $error";
473 $self->invoicing_list( $invoicing_list );
476 warn " setting cust_main_exemption\n"
479 my $tax_exemption = delete $options{'tax_exemption'};
480 if ( $tax_exemption ) {
481 foreach my $taxname ( @$tax_exemption ) {
482 my $cust_main_exemption = new FS::cust_main_exemption {
483 'custnum' => $self->custnum,
484 'taxname' => $taxname,
486 my $error = $cust_main_exemption->insert;
488 $dbh->rollback if $oldAutoCommit;
489 return "inserting cust_main_exemption (transaction rolled back): $error";
494 if ( $conf->config('cust_main-skeleton_tables')
495 && $conf->config('cust_main-skeleton_custnum') ) {
497 warn " inserting skeleton records\n"
500 my $error = $self->start_copy_skel;
502 $dbh->rollback if $oldAutoCommit;
508 warn " ordering packages\n"
511 $error = $self->order_pkgs( $cust_pkgs,
513 'seconds_ref' => \$seconds,
514 'upbytes_ref' => \$upbytes,
515 'downbytes_ref' => \$downbytes,
516 'totalbytes_ref' => \$totalbytes,
519 $dbh->rollback if $oldAutoCommit;
524 $dbh->rollback if $oldAutoCommit;
525 return "No svc_acct record to apply pre-paid time";
527 if ( $upbytes || $downbytes || $totalbytes ) {
528 $dbh->rollback if $oldAutoCommit;
529 return "No svc_acct record to apply pre-paid data";
533 warn " inserting initial $payby payment of $amount\n"
535 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
537 $dbh->rollback if $oldAutoCommit;
538 return "inserting payment (transaction rolled back): $error";
542 unless ( $import || $skip_fuzzyfiles ) {
543 warn " queueing fuzzyfiles update\n"
545 $error = $self->queue_fuzzyfiles_update;
547 $dbh->rollback if $oldAutoCommit;
548 return "updating fuzzy search cache: $error";
553 warn " exporting\n" if $DEBUG > 1;
555 my $export_args = $options{'export_args'} || [];
558 map qsearch( 'part_export', {exportnum=>$_} ),
559 $conf->config('cust_main-exports'); #, $agentnum
561 foreach my $part_export ( @part_export ) {
562 my $error = $part_export->export_insert($self, @$export_args);
564 $dbh->rollback if $oldAutoCommit;
565 return "exporting to ". $part_export->exporttype.
566 " (transaction rolled back): $error";
570 #foreach my $depend_jobnum ( @$depend_jobnums ) {
571 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
573 # foreach my $jobnum ( @jobnums ) {
574 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
575 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
577 # my $error = $queue->depend_insert($depend_jobnum);
579 # $dbh->rollback if $oldAutoCommit;
580 # return "error queuing job dependancy: $error";
587 #if ( exists $options{'jobnums'} ) {
588 # push @{ $options{'jobnums'} }, @jobnums;
591 warn " insert complete; committing transaction\n"
594 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
599 use File::CounterFile;
600 sub auto_agent_custid {
603 my $format = $conf->config('cust_main-auto_agent_custid');
605 if ( $format eq '1YMMXXXXXXXX' ) {
607 my $counter = new File::CounterFile 'cust_main.agent_custid';
610 my $ym = 100000000000 + time2str('%y%m00000000', time);
611 if ( $ym > $counter->value ) {
612 $counter->{'value'} = $agent_custid = $ym;
613 $counter->{'updated'} = 1;
615 $agent_custid = $counter->inc;
621 die "Unknown cust_main-auto_agent_custid format: $format";
624 $self->agent_custid($agent_custid);
628 sub start_copy_skel {
631 #'mg_user_preference' => {},
632 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
633 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
634 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
635 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
636 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
639 _copy_skel( 'cust_main', #tablename
640 $conf->config('cust_main-skeleton_custnum'), #sourceid
641 $self->custnum, #destid
642 @tables, #child tables
646 #recursive subroutine, not a method
648 my( $table, $sourceid, $destid, %child_tables ) = @_;
651 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
652 ( $table, $primary_key ) = ( $1, $2 );
654 my $dbdef_table = dbdef->table($table);
655 $primary_key = $dbdef_table->primary_key
656 or return "$table has no primary key".
657 " (or do you need to run dbdef-create?)";
660 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
661 join (', ', keys %child_tables). "\n"
664 foreach my $child_table_def ( keys %child_tables ) {
668 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
669 ( $child_table, $child_pkey ) = ( $1, $2 );
671 $child_table = $child_table_def;
673 $child_pkey = dbdef->table($child_table)->primary_key;
674 # or return "$table has no primary key".
675 # " (or do you need to run dbdef-create?)\n";
679 if ( keys %{ $child_tables{$child_table_def} } ) {
681 return "$child_table has no primary key".
682 " (run dbdef-create or try specifying it?)\n"
685 #false laziness w/Record::insert and only works on Pg
686 #refactor the proper last-inserted-id stuff out of Record::insert if this
687 # ever gets use for anything besides a quick kludge for one customer
688 my $default = dbdef->table($child_table)->column($child_pkey)->default;
689 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
690 or return "can't parse $child_table.$child_pkey default value ".
691 " for sequence name: $default";
696 my @sel_columns = grep { $_ ne $primary_key }
697 dbdef->table($child_table)->columns;
698 my $sel_columns = join(', ', @sel_columns );
700 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
701 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
702 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
704 my $sel_st = "SELECT $sel_columns FROM $child_table".
705 " WHERE $primary_key = $sourceid";
708 my $sel_sth = dbh->prepare( $sel_st )
709 or return dbh->errstr;
711 $sel_sth->execute or return $sel_sth->errstr;
713 while ( my $row = $sel_sth->fetchrow_hashref ) {
715 warn " selected row: ".
716 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
720 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
721 my $ins_sth =dbh->prepare($statement)
722 or return dbh->errstr;
723 my @param = ( $destid, map $row->{$_}, @ins_columns );
724 warn " $statement: [ ". join(', ', @param). " ]\n"
726 $ins_sth->execute( @param )
727 or return $ins_sth->errstr;
729 #next unless keys %{ $child_tables{$child_table} };
730 next unless $sequence;
732 #another section of that laziness
733 my $seq_sql = "SELECT currval('$sequence')";
734 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
735 $seq_sth->execute or return $seq_sth->errstr;
736 my $insertid = $seq_sth->fetchrow_arrayref->[0];
738 # don't drink soap! recurse! recurse! okay!
740 _copy_skel( $child_table_def,
741 $row->{$child_pkey}, #sourceid
743 %{ $child_tables{$child_table_def} },
745 return $error if $error;
755 =item order_pkg HASHREF | OPTION => VALUE ...
757 Orders a single package.
759 Options may be passed as a list of key/value pairs or as a hash reference.
770 Optional FS::cust_location object
774 Optional arryaref of FS::svc_* service objects.
778 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
779 jobs will have a dependancy on the supplied job (they will not run until the
780 specific job completes). This can be used to defer provisioning until some
781 action completes (such as running the customer's credit card successfully).
785 Optional subject for a ticket created and attached to this customer
789 Optional queue name for ticket additions
797 my $opt = ref($_[0]) ? shift : { @_ };
799 warn "$me order_pkg called with options ".
800 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
803 my $cust_pkg = $opt->{'cust_pkg'};
804 my $svcs = $opt->{'svcs'} || [];
806 my %svc_options = ();
807 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
808 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
810 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
811 qw( ticket_subject ticket_queue );
813 local $SIG{HUP} = 'IGNORE';
814 local $SIG{INT} = 'IGNORE';
815 local $SIG{QUIT} = 'IGNORE';
816 local $SIG{TERM} = 'IGNORE';
817 local $SIG{TSTP} = 'IGNORE';
818 local $SIG{PIPE} = 'IGNORE';
820 my $oldAutoCommit = $FS::UID::AutoCommit;
821 local $FS::UID::AutoCommit = 0;
824 if ( $opt->{'cust_location'} &&
825 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
826 my $error = $opt->{'cust_location'}->insert;
828 $dbh->rollback if $oldAutoCommit;
829 return "inserting cust_location (transaction rolled back): $error";
831 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
834 $cust_pkg->custnum( $self->custnum );
836 my $error = $cust_pkg->insert( %insert_params );
838 $dbh->rollback if $oldAutoCommit;
839 return "inserting cust_pkg (transaction rolled back): $error";
842 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
843 if ( $svc_something->svcnum ) {
844 my $old_cust_svc = $svc_something->cust_svc;
845 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
846 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
847 $error = $new_cust_svc->replace($old_cust_svc);
849 $svc_something->pkgnum( $cust_pkg->pkgnum );
850 if ( $svc_something->isa('FS::svc_acct') ) {
851 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
852 qw( seconds upbytes downbytes totalbytes ) ) {
853 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
854 ${ $opt->{$_.'_ref'} } = 0;
857 $error = $svc_something->insert(%svc_options);
860 $dbh->rollback if $oldAutoCommit;
861 return "inserting svc_ (transaction rolled back): $error";
865 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
870 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
871 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
873 Like the insert method on an existing record, this method orders multiple
874 packages and included services atomicaly. Pass a Tie::RefHash data structure
875 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
876 There should be a better explanation of this, but until then, here's an
880 tie %hash, 'Tie::RefHash'; #this part is important
882 $cust_pkg => [ $svc_acct ],
885 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
887 Services can be new, in which case they are inserted, or existing unaudited
888 services, in which case they are linked to the newly-created package.
890 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
891 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
893 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
894 on the supplied jobnum (they will not run until the specific job completes).
895 This can be used to defer provisioning until some action completes (such
896 as running the customer's credit card successfully).
898 The I<noexport> option is deprecated. If I<noexport> is set true, no
899 provisioning jobs (exports) are scheduled. (You can schedule them later with
900 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
901 on the cust_main object is not recommended, as existing services will also be
904 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
905 provided, the scalars (provided by references) will be incremented by the
906 values of the prepaid card.`
912 my $cust_pkgs = shift;
913 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
915 $seconds_ref ||= $options{'seconds_ref'};
917 warn "$me order_pkgs called with options ".
918 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
921 local $SIG{HUP} = 'IGNORE';
922 local $SIG{INT} = 'IGNORE';
923 local $SIG{QUIT} = 'IGNORE';
924 local $SIG{TERM} = 'IGNORE';
925 local $SIG{TSTP} = 'IGNORE';
926 local $SIG{PIPE} = 'IGNORE';
928 my $oldAutoCommit = $FS::UID::AutoCommit;
929 local $FS::UID::AutoCommit = 0;
932 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
934 foreach my $cust_pkg ( keys %$cust_pkgs ) {
936 my $error = $self->order_pkg(
937 'cust_pkg' => $cust_pkg,
938 'svcs' => $cust_pkgs->{$cust_pkg},
939 'seconds_ref' => $seconds_ref,
940 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
945 $dbh->rollback if $oldAutoCommit;
951 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
955 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
957 Recharges this (existing) customer with the specified prepaid card (see
958 L<FS::prepay_credit>), specified either by I<identifier> or as an
959 FS::prepay_credit object. If there is an error, returns the error, otherwise
962 Optionally, five scalar references can be passed as well. They will have their
963 values filled in with the amount, number of seconds, and number of upload,
964 download, and total bytes applied by this prepaid card.
968 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
969 #the only place that uses these args
970 sub recharge_prepay {
971 my( $self, $prepay_credit, $amountref, $secondsref,
972 $upbytesref, $downbytesref, $totalbytesref ) = @_;
974 local $SIG{HUP} = 'IGNORE';
975 local $SIG{INT} = 'IGNORE';
976 local $SIG{QUIT} = 'IGNORE';
977 local $SIG{TERM} = 'IGNORE';
978 local $SIG{TSTP} = 'IGNORE';
979 local $SIG{PIPE} = 'IGNORE';
981 my $oldAutoCommit = $FS::UID::AutoCommit;
982 local $FS::UID::AutoCommit = 0;
985 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
987 my $error = $self->get_prepay( $prepay_credit,
988 'amount_ref' => \$amount,
989 'seconds_ref' => \$seconds,
990 'upbytes_ref' => \$upbytes,
991 'downbytes_ref' => \$downbytes,
992 'totalbytes_ref' => \$totalbytes,
994 || $self->increment_seconds($seconds)
995 || $self->increment_upbytes($upbytes)
996 || $self->increment_downbytes($downbytes)
997 || $self->increment_totalbytes($totalbytes)
998 || $self->insert_cust_pay_prepay( $amount,
1000 ? $prepay_credit->identifier
1005 $dbh->rollback if $oldAutoCommit;
1009 if ( defined($amountref) ) { $$amountref = $amount; }
1010 if ( defined($secondsref) ) { $$secondsref = $seconds; }
1011 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1012 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1013 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1015 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1020 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1022 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1023 specified either by I<identifier> or as an FS::prepay_credit object.
1025 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
1026 incremented by the values of the prepaid card.
1028 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1029 check or set this customer's I<agentnum>.
1031 If there is an error, returns the error, otherwise returns false.
1037 my( $self, $prepay_credit, %opt ) = @_;
1039 local $SIG{HUP} = 'IGNORE';
1040 local $SIG{INT} = 'IGNORE';
1041 local $SIG{QUIT} = 'IGNORE';
1042 local $SIG{TERM} = 'IGNORE';
1043 local $SIG{TSTP} = 'IGNORE';
1044 local $SIG{PIPE} = 'IGNORE';
1046 my $oldAutoCommit = $FS::UID::AutoCommit;
1047 local $FS::UID::AutoCommit = 0;
1050 unless ( ref($prepay_credit) ) {
1052 my $identifier = $prepay_credit;
1054 $prepay_credit = qsearchs(
1056 { 'identifier' => $prepay_credit },
1061 unless ( $prepay_credit ) {
1062 $dbh->rollback if $oldAutoCommit;
1063 return "Invalid prepaid card: ". $identifier;
1068 if ( $prepay_credit->agentnum ) {
1069 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1070 $dbh->rollback if $oldAutoCommit;
1071 return "prepaid card not valid for agent ". $self->agentnum;
1073 $self->agentnum($prepay_credit->agentnum);
1076 my $error = $prepay_credit->delete;
1078 $dbh->rollback if $oldAutoCommit;
1079 return "removing prepay_credit (transaction rolled back): $error";
1082 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1083 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1085 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1090 =item increment_upbytes SECONDS
1092 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1093 the specified number of upbytes. If there is an error, returns the error,
1094 otherwise returns false.
1098 sub increment_upbytes {
1099 _increment_column( shift, 'upbytes', @_);
1102 =item increment_downbytes SECONDS
1104 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1105 the specified number of downbytes. If there is an error, returns the error,
1106 otherwise returns false.
1110 sub increment_downbytes {
1111 _increment_column( shift, 'downbytes', @_);
1114 =item increment_totalbytes SECONDS
1116 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1117 the specified number of totalbytes. If there is an error, returns the error,
1118 otherwise returns false.
1122 sub increment_totalbytes {
1123 _increment_column( shift, 'totalbytes', @_);
1126 =item increment_seconds SECONDS
1128 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1129 the specified number of seconds. If there is an error, returns the error,
1130 otherwise returns false.
1134 sub increment_seconds {
1135 _increment_column( shift, 'seconds', @_);
1138 =item _increment_column AMOUNT
1140 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1141 the specified number of seconds or bytes. If there is an error, returns
1142 the error, otherwise returns false.
1146 sub _increment_column {
1147 my( $self, $column, $amount ) = @_;
1148 warn "$me increment_column called: $column, $amount\n"
1151 return '' unless $amount;
1153 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1154 $self->ncancelled_pkgs;
1156 if ( ! @cust_pkg ) {
1157 return 'No packages with primary or single services found'.
1158 ' to apply pre-paid time';
1159 } elsif ( scalar(@cust_pkg) > 1 ) {
1160 #maybe have a way to specify the package/account?
1161 return 'Multiple packages found to apply pre-paid time';
1164 my $cust_pkg = $cust_pkg[0];
1165 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1169 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1171 if ( ! @cust_svc ) {
1172 return 'No account found to apply pre-paid time';
1173 } elsif ( scalar(@cust_svc) > 1 ) {
1174 return 'Multiple accounts found to apply pre-paid time';
1177 my $svc_acct = $cust_svc[0]->svc_x;
1178 warn " found service svcnum ". $svc_acct->pkgnum.
1179 ' ('. $svc_acct->email. ")\n"
1182 $column = "increment_$column";
1183 $svc_acct->$column($amount);
1187 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1189 Inserts a prepayment in the specified amount for this customer. An optional
1190 second argument can specify the prepayment identifier for tracking purposes.
1191 If there is an error, returns the error, otherwise returns false.
1195 sub insert_cust_pay_prepay {
1196 shift->insert_cust_pay('PREP', @_);
1199 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1201 Inserts a cash payment in the specified amount for this customer. An optional
1202 second argument can specify the payment identifier for tracking purposes.
1203 If there is an error, returns the error, otherwise returns false.
1207 sub insert_cust_pay_cash {
1208 shift->insert_cust_pay('CASH', @_);
1211 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1213 Inserts a Western Union payment in the specified amount for this customer. An
1214 optional second argument can specify the prepayment identifier for tracking
1215 purposes. If there is an error, returns the error, otherwise returns false.
1219 sub insert_cust_pay_west {
1220 shift->insert_cust_pay('WEST', @_);
1223 sub insert_cust_pay {
1224 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1225 my $payinfo = scalar(@_) ? shift : '';
1227 my $cust_pay = new FS::cust_pay {
1228 'custnum' => $self->custnum,
1229 'paid' => sprintf('%.2f', $amount),
1230 #'_date' => #date the prepaid card was purchased???
1232 'payinfo' => $payinfo,
1240 This method is deprecated. See the I<depend_jobnum> option to the insert and
1241 order_pkgs methods for a better way to defer provisioning.
1243 Re-schedules all exports by calling the B<reexport> method of all associated
1244 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1245 otherwise returns false.
1252 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1253 "use the depend_jobnum option to insert or order_pkgs to delay export";
1255 local $SIG{HUP} = 'IGNORE';
1256 local $SIG{INT} = 'IGNORE';
1257 local $SIG{QUIT} = 'IGNORE';
1258 local $SIG{TERM} = 'IGNORE';
1259 local $SIG{TSTP} = 'IGNORE';
1260 local $SIG{PIPE} = 'IGNORE';
1262 my $oldAutoCommit = $FS::UID::AutoCommit;
1263 local $FS::UID::AutoCommit = 0;
1266 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1267 my $error = $cust_pkg->reexport;
1269 $dbh->rollback if $oldAutoCommit;
1274 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1279 =item delete NEW_CUSTNUM
1281 This deletes the customer. If there is an error, returns the error, otherwise
1284 This will completely remove all traces of the customer record. This is not
1285 what you want when a customer cancels service; for that, cancel all of the
1286 customer's packages (see L</cancel>).
1288 If the customer has any uncancelled packages, you need to pass a new (valid)
1289 customer number for those packages to be transferred to. Cancelled packages
1290 will be deleted. Did I mention that this is NOT what you want when a customer
1291 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1293 You can't delete a customer with invoices (see L<FS::cust_bill>),
1294 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1295 refunds (see L<FS::cust_refund>).
1302 local $SIG{HUP} = 'IGNORE';
1303 local $SIG{INT} = 'IGNORE';
1304 local $SIG{QUIT} = 'IGNORE';
1305 local $SIG{TERM} = 'IGNORE';
1306 local $SIG{TSTP} = 'IGNORE';
1307 local $SIG{PIPE} = 'IGNORE';
1309 my $oldAutoCommit = $FS::UID::AutoCommit;
1310 local $FS::UID::AutoCommit = 0;
1313 if ( $self->cust_bill ) {
1314 $dbh->rollback if $oldAutoCommit;
1315 return "Can't delete a customer with invoices";
1317 if ( $self->cust_credit ) {
1318 $dbh->rollback if $oldAutoCommit;
1319 return "Can't delete a customer with credits";
1321 if ( $self->cust_pay ) {
1322 $dbh->rollback if $oldAutoCommit;
1323 return "Can't delete a customer with payments";
1325 if ( $self->cust_refund ) {
1326 $dbh->rollback if $oldAutoCommit;
1327 return "Can't delete a customer with refunds";
1330 my @cust_pkg = $self->ncancelled_pkgs;
1332 my $new_custnum = shift;
1333 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1334 $dbh->rollback if $oldAutoCommit;
1335 return "Invalid new customer number: $new_custnum";
1337 foreach my $cust_pkg ( @cust_pkg ) {
1338 my %hash = $cust_pkg->hash;
1339 $hash{'custnum'} = $new_custnum;
1340 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1341 my $error = $new_cust_pkg->replace($cust_pkg,
1342 options => { $cust_pkg->options },
1345 $dbh->rollback if $oldAutoCommit;
1350 my @cancelled_cust_pkg = $self->all_pkgs;
1351 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1352 my $error = $cust_pkg->delete;
1354 $dbh->rollback if $oldAutoCommit;
1359 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1360 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1362 my $error = $cust_main_invoice->delete;
1364 $dbh->rollback if $oldAutoCommit;
1369 foreach my $cust_main_exemption (
1370 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } )
1372 my $error = $cust_main_exemption->delete;
1374 $dbh->rollback if $oldAutoCommit;
1379 my $error = $self->SUPER::delete;
1381 $dbh->rollback if $oldAutoCommit;
1385 # cust_main exports!
1387 #my $export_args = $options{'export_args'} || [];
1390 map qsearch( 'part_export', {exportnum=>$_} ),
1391 $conf->config('cust_main-exports'); #, $agentnum
1393 foreach my $part_export ( @part_export ) {
1394 my $error = $part_export->export_delete( $self ); #, @$export_args);
1396 $dbh->rollback if $oldAutoCommit;
1397 return "exporting to ". $part_export->exporttype.
1398 " (transaction rolled back): $error";
1402 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1407 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1410 Replaces the OLD_RECORD with this one in the database. If there is an error,
1411 returns the error, otherwise returns false.
1413 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1414 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1415 expected and rollback the entire transaction; it is not necessary to call
1416 check_invoicing_list first. Here's an example:
1418 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1420 Currently available options are: I<tax_exemption>.
1422 The I<tax_exemption> option can be set to an arrayref of tax names.
1423 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1430 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1432 : $self->replace_old;
1436 warn "$me replace called\n"
1439 my $curuser = $FS::CurrentUser::CurrentUser;
1440 if ( $self->payby eq 'COMP'
1441 && $self->payby ne $old->payby
1442 && ! $curuser->access_right('Complimentary customer')
1445 return "You are not permitted to create complimentary accounts.";
1448 local($ignore_expired_card) = 1
1449 if $old->payby =~ /^(CARD|DCRD)$/
1450 && $self->payby =~ /^(CARD|DCRD)$/
1451 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1453 local $SIG{HUP} = 'IGNORE';
1454 local $SIG{INT} = 'IGNORE';
1455 local $SIG{QUIT} = 'IGNORE';
1456 local $SIG{TERM} = 'IGNORE';
1457 local $SIG{TSTP} = 'IGNORE';
1458 local $SIG{PIPE} = 'IGNORE';
1460 my $oldAutoCommit = $FS::UID::AutoCommit;
1461 local $FS::UID::AutoCommit = 0;
1464 my $error = $self->SUPER::replace($old);
1467 $dbh->rollback if $oldAutoCommit;
1471 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1472 my $invoicing_list = shift @param;
1473 $error = $self->check_invoicing_list( $invoicing_list );
1475 $dbh->rollback if $oldAutoCommit;
1478 $self->invoicing_list( $invoicing_list );
1481 my %options = @param;
1483 my $tax_exemption = delete $options{'tax_exemption'};
1484 if ( $tax_exemption ) {
1486 my %cust_main_exemption =
1487 map { $_->taxname => $_ }
1488 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1490 foreach my $taxname ( @$tax_exemption ) {
1492 next if delete $cust_main_exemption{$taxname};
1494 my $cust_main_exemption = new FS::cust_main_exemption {
1495 'custnum' => $self->custnum,
1496 'taxname' => $taxname,
1498 my $error = $cust_main_exemption->insert;
1500 $dbh->rollback if $oldAutoCommit;
1501 return "inserting cust_main_exemption (transaction rolled back): $error";
1505 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1506 my $error = $cust_main_exemption->delete;
1508 $dbh->rollback if $oldAutoCommit;
1509 return "deleting cust_main_exemption (transaction rolled back): $error";
1515 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1516 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1517 && $self->get('payinfo') !~ /^99\d{14}$/
1519 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1524 # card/check/lec info has changed, want to retry realtime_ invoice events
1525 my $error = $self->retry_realtime;
1527 $dbh->rollback if $oldAutoCommit;
1532 unless ( $import || $skip_fuzzyfiles ) {
1533 $error = $self->queue_fuzzyfiles_update;
1535 $dbh->rollback if $oldAutoCommit;
1536 return "updating fuzzy search cache: $error";
1540 # cust_main exports!
1542 my $export_args = $options{'export_args'} || [];
1545 map qsearch( 'part_export', {exportnum=>$_} ),
1546 $conf->config('cust_main-exports'); #, $agentnum
1548 foreach my $part_export ( @part_export ) {
1549 my $error = $part_export->export_replace( $self, $old, @$export_args);
1551 $dbh->rollback if $oldAutoCommit;
1552 return "exporting to ". $part_export->exporttype.
1553 " (transaction rolled back): $error";
1557 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1562 =item queue_fuzzyfiles_update
1564 Used by insert & replace to update the fuzzy search cache
1568 sub queue_fuzzyfiles_update {
1571 local $SIG{HUP} = 'IGNORE';
1572 local $SIG{INT} = 'IGNORE';
1573 local $SIG{QUIT} = 'IGNORE';
1574 local $SIG{TERM} = 'IGNORE';
1575 local $SIG{TSTP} = 'IGNORE';
1576 local $SIG{PIPE} = 'IGNORE';
1578 my $oldAutoCommit = $FS::UID::AutoCommit;
1579 local $FS::UID::AutoCommit = 0;
1582 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1583 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1585 $dbh->rollback if $oldAutoCommit;
1586 return "queueing job (transaction rolled back): $error";
1589 if ( $self->ship_last ) {
1590 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1591 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1593 $dbh->rollback if $oldAutoCommit;
1594 return "queueing job (transaction rolled back): $error";
1598 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1605 Checks all fields to make sure this is a valid customer record. If there is
1606 an error, returns the error, otherwise returns false. Called by the insert
1607 and replace methods.
1614 warn "$me check BEFORE: \n". $self->_dump
1618 $self->ut_numbern('custnum')
1619 || $self->ut_number('agentnum')
1620 || $self->ut_textn('agent_custid')
1621 || $self->ut_number('refnum')
1622 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1623 || $self->ut_textn('custbatch')
1624 || $self->ut_name('last')
1625 || $self->ut_name('first')
1626 || $self->ut_snumbern('birthdate')
1627 || $self->ut_snumbern('signupdate')
1628 || $self->ut_textn('company')
1629 || $self->ut_text('address1')
1630 || $self->ut_textn('address2')
1631 || $self->ut_text('city')
1632 || $self->ut_textn('county')
1633 || $self->ut_textn('state')
1634 || $self->ut_country('country')
1635 || $self->ut_anything('comments')
1636 || $self->ut_numbern('referral_custnum')
1637 || $self->ut_textn('stateid')
1638 || $self->ut_textn('stateid_state')
1639 || $self->ut_textn('invoice_terms')
1640 || $self->ut_alphan('geocode')
1641 || $self->ut_floatn('cdr_termination_percentage')
1644 #barf. need message catalogs. i18n. etc.
1645 $error .= "Please select an advertising source."
1646 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1647 return $error if $error;
1649 return "Unknown agent"
1650 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1652 return "Unknown refnum"
1653 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1655 return "Unknown referring custnum: ". $self->referral_custnum
1656 unless ! $self->referral_custnum
1657 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1659 if ( $self->censustract ne '' ) {
1660 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1661 or return "Illegal census tract: ". $self->censustract;
1663 $self->censustract("$1.$2");
1666 if ( $self->ss eq '' ) {
1671 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1672 or return "Illegal social security number: ". $self->ss;
1673 $self->ss("$1-$2-$3");
1677 # bad idea to disable, causes billing to fail because of no tax rates later
1678 # unless ( $import ) {
1679 unless ( qsearch('cust_main_county', {
1680 'country' => $self->country,
1683 return "Unknown state/county/country: ".
1684 $self->state. "/". $self->county. "/". $self->country
1685 unless qsearch('cust_main_county',{
1686 'state' => $self->state,
1687 'county' => $self->county,
1688 'country' => $self->country,
1694 $self->ut_phonen('daytime', $self->country)
1695 || $self->ut_phonen('night', $self->country)
1696 || $self->ut_phonen('fax', $self->country)
1697 || $self->ut_zip('zip', $self->country)
1699 return $error if $error;
1701 if ( $conf->exists('cust_main-require_phone')
1702 && ! length($self->daytime) && ! length($self->night)
1705 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1707 : FS::Msgcat::_gettext('daytime');
1708 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1710 : FS::Msgcat::_gettext('night');
1712 return "$daytime_label or $night_label is required"
1716 if ( $self->has_ship_address
1717 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1718 $self->addr_fields )
1722 $self->ut_name('ship_last')
1723 || $self->ut_name('ship_first')
1724 || $self->ut_textn('ship_company')
1725 || $self->ut_text('ship_address1')
1726 || $self->ut_textn('ship_address2')
1727 || $self->ut_text('ship_city')
1728 || $self->ut_textn('ship_county')
1729 || $self->ut_textn('ship_state')
1730 || $self->ut_country('ship_country')
1732 return $error if $error;
1734 #false laziness with above
1735 unless ( qsearchs('cust_main_county', {
1736 'country' => $self->ship_country,
1739 return "Unknown ship_state/ship_county/ship_country: ".
1740 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1741 unless qsearch('cust_main_county',{
1742 'state' => $self->ship_state,
1743 'county' => $self->ship_county,
1744 'country' => $self->ship_country,
1750 $self->ut_phonen('ship_daytime', $self->ship_country)
1751 || $self->ut_phonen('ship_night', $self->ship_country)
1752 || $self->ut_phonen('ship_fax', $self->ship_country)
1753 || $self->ut_zip('ship_zip', $self->ship_country)
1755 return $error if $error;
1757 return "Unit # is required."
1758 if $self->ship_address2 =~ /^\s*$/
1759 && $conf->exists('cust_main-require_address2');
1761 } else { # ship_ info eq billing info, so don't store dup info in database
1763 $self->setfield("ship_$_", '')
1764 foreach $self->addr_fields;
1766 return "Unit # is required."
1767 if $self->address2 =~ /^\s*$/
1768 && $conf->exists('cust_main-require_address2');
1772 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1773 # or return "Illegal payby: ". $self->payby;
1775 FS::payby->can_payby($self->table, $self->payby)
1776 or return "Illegal payby: ". $self->payby;
1778 $error = $self->ut_numbern('paystart_month')
1779 || $self->ut_numbern('paystart_year')
1780 || $self->ut_numbern('payissue')
1781 || $self->ut_textn('paytype')
1783 return $error if $error;
1785 if ( $self->payip eq '' ) {
1788 $error = $self->ut_ip('payip');
1789 return $error if $error;
1792 # If it is encrypted and the private key is not availaible then we can't
1793 # check the credit card.
1794 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1796 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1798 my $payinfo = $self->payinfo;
1799 $payinfo =~ s/\D//g;
1800 $payinfo =~ /^(\d{13,16})$/
1801 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1803 $self->payinfo($payinfo);
1805 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1807 return gettext('unknown_card_type')
1808 if $self->payinfo !~ /^99\d{14}$/ #token
1809 && cardtype($self->payinfo) eq "Unknown";
1811 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1813 return 'Banned credit card: banned on '.
1814 time2str('%a %h %o at %r', $ban->_date).
1815 ' by '. $ban->otaker.
1816 ' (ban# '. $ban->bannum. ')';
1819 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1820 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1821 $self->paycvv =~ /^(\d{4})$/
1822 or return "CVV2 (CID) for American Express cards is four digits.";
1825 $self->paycvv =~ /^(\d{3})$/
1826 or return "CVV2 (CVC2/CID) is three digits.";
1833 my $cardtype = cardtype($payinfo);
1834 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1836 return "Start date or issue number is required for $cardtype cards"
1837 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1839 return "Start month must be between 1 and 12"
1840 if $self->paystart_month
1841 and $self->paystart_month < 1 || $self->paystart_month > 12;
1843 return "Start year must be 1990 or later"
1844 if $self->paystart_year
1845 and $self->paystart_year < 1990;
1847 return "Issue number must be beween 1 and 99"
1849 and $self->payissue < 1 || $self->payissue > 99;
1852 $self->paystart_month('');
1853 $self->paystart_year('');
1854 $self->payissue('');
1857 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1859 my $payinfo = $self->payinfo;
1860 $payinfo =~ s/[^\d\@]//g;
1861 if ( $conf->exists('echeck-nonus') ) {
1862 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1863 $payinfo = "$1\@$2";
1865 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1866 $payinfo = "$1\@$2";
1868 $self->payinfo($payinfo);
1871 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1873 return 'Banned ACH account: banned on '.
1874 time2str('%a %h %o at %r', $ban->_date).
1875 ' by '. $ban->otaker.
1876 ' (ban# '. $ban->bannum. ')';
1879 } elsif ( $self->payby eq 'LECB' ) {
1881 my $payinfo = $self->payinfo;
1882 $payinfo =~ s/\D//g;
1883 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1885 $self->payinfo($payinfo);
1888 } elsif ( $self->payby eq 'BILL' ) {
1890 $error = $self->ut_textn('payinfo');
1891 return "Illegal P.O. number: ". $self->payinfo if $error;
1894 } elsif ( $self->payby eq 'COMP' ) {
1896 my $curuser = $FS::CurrentUser::CurrentUser;
1897 if ( ! $self->custnum
1898 && ! $curuser->access_right('Complimentary customer')
1901 return "You are not permitted to create complimentary accounts."
1904 $error = $self->ut_textn('payinfo');
1905 return "Illegal comp account issuer: ". $self->payinfo if $error;
1908 } elsif ( $self->payby eq 'PREPAY' ) {
1910 my $payinfo = $self->payinfo;
1911 $payinfo =~ s/\W//g; #anything else would just confuse things
1912 $self->payinfo($payinfo);
1913 $error = $self->ut_alpha('payinfo');
1914 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1915 return "Unknown prepayment identifier"
1916 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1921 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1922 return "Expiration date required"
1923 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1927 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1928 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1929 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1930 ( $m, $y ) = ( $2, "19$1" );
1931 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1932 ( $m, $y ) = ( $3, "20$2" );
1934 return "Illegal expiration date: ". $self->paydate;
1936 $self->paydate("$y-$m-01");
1937 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1938 return gettext('expired_card')
1940 && !$ignore_expired_card
1941 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1944 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1945 ( ! $conf->exists('require_cardname')
1946 || $self->payby !~ /^(CARD|DCRD)$/ )
1948 $self->payname( $self->first. " ". $self->getfield('last') );
1950 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1951 or return gettext('illegal_name'). " payname: ". $self->payname;
1955 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1956 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1960 $self->otaker(getotaker) unless $self->otaker;
1962 warn "$me check AFTER: \n". $self->_dump
1965 $self->SUPER::check;
1970 Returns a list of fields which have ship_ duplicates.
1975 qw( last first company
1976 address1 address2 city county state zip country
1981 =item has_ship_address
1983 Returns true if this customer record has a separate shipping address.
1987 sub has_ship_address {
1989 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1994 Returns a list of key/value pairs, with the following keys: address1, adddress2,
1995 city, county, state, zip, country. The shipping address is used if present.
1999 #geocode? dependent on tax-ship_address config, not available in cust_location
2000 #mostly. not yet then.
2004 my $prefix = $self->has_ship_address ? 'ship_' : '';
2006 map { $_ => $self->get($prefix.$_) }
2007 qw( address1 address2 city county state zip country geocode );
2008 #fields that cust_location has
2011 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2013 Returns all packages (see L<FS::cust_pkg>) for this customer.
2019 my $extra_qsearch = ref($_[0]) ? shift : {};
2021 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
2024 if ( $self->{'_pkgnum'} ) {
2025 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2027 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2030 sort sort_packages @cust_pkg;
2035 Synonym for B<all_pkgs>.
2040 shift->all_pkgs(@_);
2045 Returns all locations (see L<FS::cust_location>) for this customer.
2051 qsearch('cust_location', { 'custnum' => $self->custnum } );
2054 =item location_label [ OPTION => VALUE ... ]
2056 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2064 used to separate the address elements (defaults to ', ')
2066 =item escape_function
2068 a callback used for escaping the text of the address elements
2074 # false laziness with FS::cust_location::line
2076 sub location_label {
2080 my $separator = $opt{join_string} || ', ';
2081 my $escape = $opt{escape_function} || sub{ shift };
2083 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2084 my $prefix = length($self->ship_last) ? 'ship_' : '';
2087 foreach (qw ( address1 address2 ) ) {
2088 my $method = "$prefix$_";
2089 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2094 foreach (qw ( city county state zip ) ) {
2095 my $method = "$prefix$_";
2096 if ( $self->$method ) {
2097 $line .= ' (' if $method eq 'county';
2098 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2099 $line .= ' )' if $method eq 'county';
2103 $line .= $separator. &$escape(code2country($self->country))
2104 if $self->country ne $cydefault;
2109 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2111 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2115 sub ncancelled_pkgs {
2117 my $extra_qsearch = ref($_[0]) ? shift : {};
2119 return $self->num_ncancelled_pkgs unless wantarray;
2122 if ( $self->{'_pkgnum'} ) {
2124 warn "$me ncancelled_pkgs: returning cached objects"
2127 @cust_pkg = grep { ! $_->getfield('cancel') }
2128 values %{ $self->{'_pkgnum'}->cache };
2132 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2133 $self->custnum. "\n"
2136 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2138 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2142 sort sort_packages @cust_pkg;
2148 my $extra_qsearch = ref($_[0]) ? shift : {};
2150 $extra_qsearch->{'select'} ||= '*';
2151 $extra_qsearch->{'select'} .=
2152 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2156 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2161 'table' => 'cust_pkg',
2162 'hashref' => { 'custnum' => $self->custnum },
2167 # This should be generalized to use config options to determine order.
2170 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2171 return $locationsort if $locationsort;
2173 if ( $a->get('cancel') xor $b->get('cancel') ) {
2174 return -1 if $b->get('cancel');
2175 return 1 if $a->get('cancel');
2176 #shouldn't get here...
2179 my $a_num_cust_svc = $a->num_cust_svc;
2180 my $b_num_cust_svc = $b->num_cust_svc;
2181 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2182 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2183 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2184 my @a_cust_svc = $a->cust_svc;
2185 my @b_cust_svc = $b->cust_svc;
2186 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2187 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2188 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
2189 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2194 =item suspended_pkgs
2196 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2200 sub suspended_pkgs {
2202 grep { $_->susp } $self->ncancelled_pkgs;
2205 =item unflagged_suspended_pkgs
2207 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2208 customer (thouse packages without the `manual_flag' set).
2212 sub unflagged_suspended_pkgs {
2214 return $self->suspended_pkgs
2215 unless dbdef->table('cust_pkg')->column('manual_flag');
2216 grep { ! $_->manual_flag } $self->suspended_pkgs;
2219 =item unsuspended_pkgs
2221 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2226 sub unsuspended_pkgs {
2228 grep { ! $_->susp } $self->ncancelled_pkgs;
2231 =item next_bill_date
2233 Returns the next date this customer will be billed, as a UNIX timestamp, or
2234 undef if no active package has a next bill date.
2238 sub next_bill_date {
2240 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2243 =item num_cancelled_pkgs
2245 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2250 sub num_cancelled_pkgs {
2251 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2254 sub num_ncancelled_pkgs {
2255 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2259 my( $self ) = shift;
2260 my $sql = scalar(@_) ? shift : '';
2261 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2262 my $sth = dbh->prepare(
2263 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2264 ) or die dbh->errstr;
2265 $sth->execute($self->custnum) or die $sth->errstr;
2266 $sth->fetchrow_arrayref->[0];
2271 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2272 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2273 on success or a list of errors.
2279 grep { $_->unsuspend } $self->suspended_pkgs;
2284 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2286 Returns a list: an empty list on success or a list of errors.
2292 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2295 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2297 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2298 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2299 of a list of pkgparts; the hashref has the following keys:
2303 =item pkgparts - listref of pkgparts
2305 =item (other options are passed to the suspend method)
2310 Returns a list: an empty list on success or a list of errors.
2314 sub suspend_if_pkgpart {
2316 my (@pkgparts, %opt);
2317 if (ref($_[0]) eq 'HASH'){
2318 @pkgparts = @{$_[0]{pkgparts}};
2323 grep { $_->suspend(%opt) }
2324 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2325 $self->unsuspended_pkgs;
2328 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2330 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2331 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2332 instead of a list of pkgparts; the hashref has the following keys:
2336 =item pkgparts - listref of pkgparts
2338 =item (other options are passed to the suspend method)
2342 Returns a list: an empty list on success or a list of errors.
2346 sub suspend_unless_pkgpart {
2348 my (@pkgparts, %opt);
2349 if (ref($_[0]) eq 'HASH'){
2350 @pkgparts = @{$_[0]{pkgparts}};
2355 grep { $_->suspend(%opt) }
2356 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2357 $self->unsuspended_pkgs;
2360 =item cancel [ OPTION => VALUE ... ]
2362 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2364 Available options are:
2368 =item quiet - can be set true to supress email cancellation notices.
2370 =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.
2372 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2374 =item nobill - can be set true to skip billing if it might otherwise be done.
2378 Always returns a list: an empty list on success or a list of errors.
2382 # nb that dates are not specified as valid options to this method
2385 my( $self, %opt ) = @_;
2387 warn "$me cancel called on customer ". $self->custnum. " with options ".
2388 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2391 return ( 'access denied' )
2392 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2394 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2396 #should try decryption (we might have the private key)
2397 # and if not maybe queue a job for the server that does?
2398 return ( "Can't (yet) ban encrypted credit cards" )
2399 if $self->is_encrypted($self->payinfo);
2401 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2402 my $error = $ban->insert;
2403 return ( $error ) if $error;
2407 my @pkgs = $self->ncancelled_pkgs;
2409 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2411 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2412 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2416 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2417 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2420 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2423 sub _banned_pay_hashref {
2434 'payby' => $payby2ban{$self->payby},
2435 'payinfo' => md5_base64($self->payinfo),
2436 #don't ever *search* on reason! #'reason' =>
2442 Returns all notes (see L<FS::cust_main_note>) for this customer.
2449 qsearch( 'cust_main_note',
2450 { 'custnum' => $self->custnum },
2452 'ORDER BY _DATE DESC'
2458 Returns the agent (see L<FS::agent>) for this customer.
2464 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2469 Returns the agent name (see L<FS::agent>) for this customer.
2475 $self->agent->agent;
2480 Returns the customer class, as an FS::cust_class object, or the empty string
2481 if there is no customer class.
2487 if ( $self->classnum ) {
2488 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2496 Returns the customer category name, or the empty string if there is no customer
2503 my $cust_class = $self->cust_class;
2505 ? $cust_class->categoryname
2511 Returns the customer class name, or the empty string if there is no customer
2518 my $cust_class = $self->cust_class;
2520 ? $cust_class->classname
2525 =item bill_and_collect
2527 Cancels and suspends any packages due, generates bills, applies payments and
2528 credits, and applies collection events to run cards, send bills and notices,
2531 By default, warns on errors and continues with the next operation (but see the
2532 "fatal" flag below).
2534 Options are passed as name-value pairs. Currently available options are:
2540 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:
2544 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2548 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.
2552 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2556 If set true, re-charges setup fees.
2560 If set any errors prevent subsequent operations from continusing. If set
2561 specifically to "return", returns the error (or false, if there is no error).
2562 Any other true value causes errors to die.
2566 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)
2570 Optional FS::queue entry to receive status updates.
2574 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2575 options of those methods are also available.
2579 sub bill_and_collect {
2580 my( $self, %options ) = @_;
2584 #$options{actual_time} not $options{time} because freeside-daily -d is for
2585 #pre-printing invoices
2587 $options{'actual_time'} ||= time;
2588 my $job = $options{'job'};
2590 $job->update_statustext('0,cleaning expired packages') if $job;
2591 $error = $self->cancel_expired_pkgs( $options{actual_time} );
2593 $error = "Error expiring custnum ". $self->custnum. ": $error";
2594 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2595 elsif ( $options{fatal} ) { die $error; }
2596 else { warn $error; }
2599 $error = $self->suspend_adjourned_pkgs( $options{actual_time} );
2601 $error = "Error adjourning custnum ". $self->custnum. ": $error";
2602 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2603 elsif ( $options{fatal} ) { die $error; }
2604 else { warn $error; }
2607 $job->update_statustext('20,billing packages') if $job;
2608 $error = $self->bill( %options );
2610 $error = "Error billing custnum ". $self->custnum. ": $error";
2611 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2612 elsif ( $options{fatal} ) { die $error; }
2613 else { warn $error; }
2616 $job->update_statustext('50,applying payments and credits') if $job;
2617 $error = $self->apply_payments_and_credits;
2619 $error = "Error applying custnum ". $self->custnum. ": $error";
2620 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2621 elsif ( $options{fatal} ) { die $error; }
2622 else { warn $error; }
2625 $job->update_statustext('70,running collection events') if $job;
2626 unless ( $conf->exists('cancelled_cust-noevents')
2627 && ! $self->num_ncancelled_pkgs
2629 $error = $self->collect( %options );
2631 $error = "Error collecting custnum ". $self->custnum. ": $error";
2632 if ($options{fatal} && $options{fatal} eq 'return') { return $error; }
2633 elsif ($options{fatal} ) { die $error; }
2634 else { warn $error; }
2637 $job->update_statustext('100,finished') if $job;
2643 sub cancel_expired_pkgs {
2644 my ( $self, $time, %options ) = @_;
2646 my @cancel_pkgs = $self->ncancelled_pkgs( {
2647 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2652 foreach my $cust_pkg ( @cancel_pkgs ) {
2653 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2654 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2655 'reason_otaker' => $cpr->otaker
2659 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2662 scalar(@errors) ? join(' / ', @errors) : '';
2666 sub suspend_adjourned_pkgs {
2667 my ( $self, $time, %options ) = @_;
2669 my @susp_pkgs = $self->ncancelled_pkgs( {
2671 " AND ( susp IS NULL OR susp = 0 )
2672 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
2673 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2678 #only because there's no SQL test for is_prepaid :/
2680 grep { ( $_->part_pkg->is_prepaid
2685 && $_->adjourn <= $time
2693 foreach my $cust_pkg ( @susp_pkgs ) {
2694 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2695 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2696 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2697 'reason_otaker' => $cpr->otaker
2701 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2704 scalar(@errors) ? join(' / ', @errors) : '';
2710 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2711 conjunction with the collect method by calling B<bill_and_collect>.
2713 If there is an error, returns the error, otherwise returns false.
2715 Options are passed as name-value pairs. Currently available options are:
2721 If set true, re-charges setup fees.
2725 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:
2729 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2733 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2735 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2739 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2743 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.
2747 This boolean value informs the us that the package is being cancelled. This
2748 typically might mean not charging the normal recurring fee but only usage
2749 fees since the last billing. Setup charges may be charged. Not all package
2750 plans support this feature (they tend to charge 0).
2754 Optional terms to be printed on this invoice. Otherwise, customer-specific
2755 terms or the default terms are used.
2762 my( $self, %options ) = @_;
2763 return '' if $self->payby eq 'COMP';
2764 warn "$me bill customer ". $self->custnum. "\n"
2767 my $time = $options{'time'} || time;
2768 my $invoice_time = $options{'invoice_time'} || $time;
2770 $options{'not_pkgpart'} ||= {};
2771 $options{'not_pkgpart'} = { map { $_ => 1 }
2772 split(/\s*,\s*/, $options{'not_pkgpart'})
2774 unless ref($options{'not_pkgpart'});
2776 local $SIG{HUP} = 'IGNORE';
2777 local $SIG{INT} = 'IGNORE';
2778 local $SIG{QUIT} = 'IGNORE';
2779 local $SIG{TERM} = 'IGNORE';
2780 local $SIG{TSTP} = 'IGNORE';
2781 local $SIG{PIPE} = 'IGNORE';
2783 my $oldAutoCommit = $FS::UID::AutoCommit;
2784 local $FS::UID::AutoCommit = 0;
2787 warn "$me acquiring lock on customer ". $self->custnum. "\n"
2790 $self->select_for_update; #mutex
2792 warn "$me running pre-bill events for customer ". $self->custnum. "\n"
2795 my $error = $self->do_cust_event(
2796 'debug' => ( $options{'debug'} || 0 ),
2797 'time' => $invoice_time,
2798 'check_freq' => $options{'check_freq'},
2799 'stage' => 'pre-bill',
2802 $dbh->rollback if $oldAutoCommit;
2806 warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
2809 #keep auto-charge and non-auto-charge line items separate
2810 my @passes = ( '', 'no_auto' );
2812 my %cust_bill_pkg = map { $_ => [] } @passes;
2815 # find the packages which are due for billing, find out how much they are
2816 # & generate invoice database.
2819 my %total_setup = map { my $z = 0; $_ => \$z; } @passes;
2820 my %total_recur = map { my $z = 0; $_ => \$z; } @passes;
2822 my %taxlisthash = map { $_ => {} } @passes;
2824 my @precommit_hooks = ();
2826 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
2827 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2829 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2831 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2833 #? to avoid use of uninitialized value errors... ?
2834 $cust_pkg->setfield('bill', '')
2835 unless defined($cust_pkg->bill);
2837 #my $part_pkg = $cust_pkg->part_pkg;
2839 my $real_pkgpart = $cust_pkg->pkgpart;
2840 my %hash = $cust_pkg->hash;
2842 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2844 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2846 my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
2849 $self->_make_lines( 'part_pkg' => $part_pkg,
2850 'cust_pkg' => $cust_pkg,
2851 'precommit_hooks' => \@precommit_hooks,
2852 'line_items' => $cust_bill_pkg{$pass},
2853 'setup' => $total_setup{$pass},
2854 'recur' => $total_recur{$pass},
2855 'tax_matrix' => $taxlisthash{$pass},
2857 'real_pkgpart' => $real_pkgpart,
2858 'options' => \%options,
2861 $dbh->rollback if $oldAutoCommit;
2865 } #foreach my $part_pkg
2867 } #foreach my $cust_pkg
2869 #if the customer isn't on an automatic payby, everything can go on a single
2871 #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
2872 #merge everything into one list
2875 foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
2877 my @cust_bill_pkg = @{ $cust_bill_pkg{$pass} };
2879 next unless @cust_bill_pkg; #don't create an invoice w/o line items
2881 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2882 !$conf->exists('postal_invoice-recurring_only')
2886 my $postal_pkg = $self->charge_postal_fee();
2887 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2889 $dbh->rollback if $oldAutoCommit;
2890 return "can't charge postal invoice fee for customer ".
2891 $self->custnum. ": $postal_pkg";
2893 } elsif ( $postal_pkg ) {
2895 my $real_pkgpart = $postal_pkg->pkgpart;
2896 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2897 my %postal_options = %options;
2898 delete $postal_options{cancel};
2900 $self->_make_lines( 'part_pkg' => $part_pkg,
2901 'cust_pkg' => $postal_pkg,
2902 'precommit_hooks' => \@precommit_hooks,
2903 'line_items' => \@cust_bill_pkg,
2904 'setup' => $total_setup{$pass},
2905 'recur' => $total_recur{$pass},
2906 'tax_matrix' => $taxlisthash{$pass},
2908 'real_pkgpart' => $real_pkgpart,
2909 'options' => \%postal_options,
2912 $dbh->rollback if $oldAutoCommit;
2921 my $listref_or_error =
2922 $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
2924 unless ( ref( $listref_or_error ) ) {
2925 $dbh->rollback if $oldAutoCommit;
2926 return $listref_or_error;
2929 foreach my $taxline ( @$listref_or_error ) {
2930 ${ $total_setup{$pass} } =
2931 sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
2932 push @cust_bill_pkg, $taxline;
2935 #add tax adjustments
2936 warn "adding tax adjustments...\n" if $DEBUG > 2;
2937 foreach my $cust_tax_adjustment (
2938 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
2944 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
2946 my $itemdesc = $cust_tax_adjustment->taxname;
2947 $itemdesc = '' if $itemdesc eq 'Tax';
2949 push @cust_bill_pkg, new FS::cust_bill_pkg {
2955 'itemdesc' => $itemdesc,
2956 'itemcomment' => $cust_tax_adjustment->comment,
2957 'cust_tax_adjustment' => $cust_tax_adjustment,
2958 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
2963 my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
2965 my @cust_bill = $self->cust_bill;
2966 my $balance = $self->balance;
2967 my $previous_balance = scalar(@cust_bill)
2968 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
2971 $previous_balance += $cust_bill[$#cust_bill]->charged
2972 if scalar(@cust_bill);
2973 #my $balance_adjustments =
2974 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
2976 #create the new invoice
2977 my $cust_bill = new FS::cust_bill ( {
2978 'custnum' => $self->custnum,
2979 '_date' => ( $invoice_time ),
2980 'charged' => $charged,
2981 'billing_balance' => $balance,
2982 'previous_balance' => $previous_balance,
2983 'invoice_terms' => $options{'invoice_terms'},
2985 $error = $cust_bill->insert;
2987 $dbh->rollback if $oldAutoCommit;
2988 return "can't create invoice for customer #". $self->custnum. ": $error";
2991 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2992 $cust_bill_pkg->invnum($cust_bill->invnum);
2993 my $error = $cust_bill_pkg->insert;
2995 $dbh->rollback if $oldAutoCommit;
2996 return "can't create invoice line item: $error";
3000 } #foreach my $pass ( keys %cust_bill_pkg )
3002 foreach my $hook ( @precommit_hooks ) {
3004 &{$hook}; #($self) ?
3007 $dbh->rollback if $oldAutoCommit;
3008 return "$@ running precommit hook $hook\n";
3012 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3016 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
3018 This is a weird one. Perhaps it should not even be exposed.
3020 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
3021 Usually used internally by bill method B<bill>.
3023 If there is an error, returns the error, otherwise returns reference to a
3024 list of line items suitable for insertion.
3030 An array ref of the line items being billed.
3034 A strange beast. The keys to this hash are internal identifiers consisting
3035 of the name of the tax object type, a space, and its unique identifier ( e.g.
3036 'cust_main_county 23' ). The values of the hash are listrefs. The first
3037 item in the list is the tax object. The remaining items are either line
3038 items or floating point values (currency amounts).
3040 The taxes are calculated on this entity. Calculated exemption records are
3041 transferred to the LINEITEMREF items on the assumption that they are related.
3047 This specifies the date appearing on the associated invoice. Some
3048 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
3053 sub calculate_taxes {
3054 my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
3056 my @tax_line_items = ();
3058 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
3060 # keys are tax names (as printed on invoices / itemdesc )
3061 # values are listrefs of taxlisthash keys (internal identifiers)
3064 # keys are taxlisthash keys (internal identifiers)
3065 # values are (cumulative) amounts
3068 # keys are taxlisthash keys (internal identifiers)
3069 # values are listrefs of cust_bill_pkg_tax_location hashrefs
3070 my %tax_location = ();
3072 # keys are taxlisthash keys (internal identifiers)
3073 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
3074 my %tax_rate_location = ();
3076 foreach my $tax ( keys %$taxlisthash ) {
3077 my $tax_object = shift @{ $taxlisthash->{$tax} };
3078 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
3079 warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
3080 my $hashref_or_error =
3081 $tax_object->taxline( $taxlisthash->{$tax},
3082 'custnum' => $self->custnum,
3083 'invoice_time' => $invoice_time
3085 return $hashref_or_error unless ref($hashref_or_error);
3087 unshift @{ $taxlisthash->{$tax} }, $tax_object;
3089 my $name = $hashref_or_error->{'name'};
3090 my $amount = $hashref_or_error->{'amount'};
3092 #warn "adding $amount as $name\n";
3093 $taxname{ $name } ||= [];
3094 push @{ $taxname{ $name } }, $tax;
3096 $tax{ $tax } += $amount;
3098 $tax_location{ $tax } ||= [];
3099 if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
3100 push @{ $tax_location{ $tax } },
3102 'taxnum' => $tax_object->taxnum,
3103 'taxtype' => ref($tax_object),
3104 'pkgnum' => $tax_object->get('pkgnum'),
3105 'locationnum' => $tax_object->get('locationnum'),
3106 'amount' => sprintf('%.2f', $amount ),
3110 $tax_rate_location{ $tax } ||= [];
3111 if ( ref($tax_object) eq 'FS::tax_rate' ) {
3112 my $taxratelocationnum =
3113 $tax_object->tax_rate_location->taxratelocationnum;
3114 push @{ $tax_rate_location{ $tax } },
3116 'taxnum' => $tax_object->taxnum,
3117 'taxtype' => ref($tax_object),
3118 'amount' => sprintf('%.2f', $amount ),
3119 'locationtaxid' => $tax_object->location,
3120 'taxratelocationnum' => $taxratelocationnum,
3126 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
3127 my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
3128 foreach my $tax ( keys %$taxlisthash ) {
3129 foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
3130 next unless ref($_) eq 'FS::cust_bill_pkg';
3132 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
3133 splice( @{ $_->_cust_tax_exempt_pkg } );
3137 #consolidate and create tax line items
3138 warn "consolidating and generating...\n" if $DEBUG > 2;
3139 foreach my $taxname ( keys %taxname ) {
3142 my @cust_bill_pkg_tax_location = ();
3143 my @cust_bill_pkg_tax_rate_location = ();
3144 warn "adding $taxname\n" if $DEBUG > 1;
3145 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
3146 next if $seen{$taxitem}++;
3147 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
3148 $tax += $tax{$taxitem};
3149 push @cust_bill_pkg_tax_location,
3150 map { new FS::cust_bill_pkg_tax_location $_ }
3151 @{ $tax_location{ $taxitem } };
3152 push @cust_bill_pkg_tax_rate_location,
3153 map { new FS::cust_bill_pkg_tax_rate_location $_ }
3154 @{ $tax_rate_location{ $taxitem } };
3158 $tax = sprintf('%.2f', $tax );
3160 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
3166 if ( $pkg_category and
3167 $conf->config('invoice_latexsummary') ||
3168 $conf->config('invoice_htmlsummary')
3172 my %hash = ( 'section' => $pkg_category->categoryname );
3173 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3177 push @tax_line_items, new FS::cust_bill_pkg {
3183 'itemdesc' => $taxname,
3184 'display' => \@display,
3185 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3186 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
3195 my ($self, %params) = @_;
3197 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
3198 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
3199 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
3200 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
3201 my $total_setup = $params{setup} or die "no setup accumulator specified";
3202 my $total_recur = $params{recur} or die "no recur accumulator specified";
3203 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
3204 my $time = $params{'time'} or die "no time specified";
3205 my (%options) = %{$params{options}};
3208 my $real_pkgpart = $params{real_pkgpart};
3209 my %hash = $cust_pkg->hash;
3210 my $old_cust_pkg = new FS::cust_pkg \%hash;
3216 $cust_pkg->pkgpart($part_pkg->pkgpart);
3224 if ( $options{'resetup'}
3225 || ( ! $cust_pkg->setup
3226 && ( ! $cust_pkg->start_date
3227 || $cust_pkg->start_date <= $time
3229 && ( ! $conf->exists('disable_setup_suspended_pkgs')
3230 || ( $conf->exists('disable_setup_suspended_pkgs') &&
3231 ! $cust_pkg->getfield('susp')
3238 warn " bill setup\n" if $DEBUG > 1;
3241 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
3242 return "$@ running calc_setup for $cust_pkg\n"
3245 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
3247 $cust_pkg->setfield('setup', $time)
3248 unless $cust_pkg->setup;
3249 #do need it, but it won't get written to the db
3250 #|| $cust_pkg->pkgpart != $real_pkgpart;
3252 $cust_pkg->setfield('start_date', '')
3253 if $cust_pkg->start_date;
3258 # bill recurring fee
3261 #XXX unit stuff here too
3265 if ( ! $cust_pkg->get('susp')
3266 and ! $cust_pkg->get('start_date')
3267 and ( $part_pkg->getfield('freq') ne '0'
3268 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3270 || ( $part_pkg->plan eq 'voip_cdr'
3271 && $part_pkg->option('bill_every_call')
3273 || ( $options{cancel} )
3276 # XXX should this be a package event? probably. events are called
3277 # at collection time at the moment, though...
3278 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
3279 if $part_pkg->can('reset_usage');
3280 #don't want to reset usage just cause we want a line item??
3281 #&& $part_pkg->pkgpart == $real_pkgpart;
3283 warn " bill recur\n" if $DEBUG > 1;
3286 # XXX shared with $recur_prog
3287 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
3291 #over two params! lets at least switch to a hashref for the rest...
3292 my $increment_next_bill = ( $part_pkg->freq ne '0'
3293 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3294 && !$options{cancel}
3296 my %param = ( 'precommit_hooks' => $precommit_hooks,
3297 'increment_next_bill' => $increment_next_bill,
3298 'discounts' => \@discounts,
3301 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
3302 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
3303 return "$@ running $method for $cust_pkg\n"
3306 if ( $increment_next_bill ) {
3308 my $next_bill = $part_pkg->add_freq($sdate);
3309 return "unparsable frequency: ". $part_pkg->freq
3310 if $next_bill == -1;
3312 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
3313 # only for figuring next bill date, nothing else, so, reset $sdate again
3315 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
3316 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
3317 $cust_pkg->last_bill($sdate);
3319 $cust_pkg->setfield('bill', $next_bill );
3325 warn "\$setup is undefined" unless defined($setup);
3326 warn "\$recur is undefined" unless defined($recur);
3327 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
3330 # If there's line items, create em cust_bill_pkg records
3331 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
3336 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
3337 # hmm.. and if just the options are modified in some weird price plan?
3339 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
3342 my $error = $cust_pkg->replace( $old_cust_pkg,
3343 'options' => { $cust_pkg->options },
3345 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
3346 if $error; #just in case
3349 $setup = sprintf( "%.2f", $setup );
3350 $recur = sprintf( "%.2f", $recur );
3351 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
3352 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3354 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3355 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3358 if ( $setup != 0 || $recur != 0 ) {
3360 warn " charges (setup=$setup, recur=$recur); adding line items\n"
3363 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3365 warn " adding customer package invoice detail: $_\n"
3366 foreach @cust_pkg_detail;
3368 push @details, @cust_pkg_detail;
3370 my $cust_bill_pkg = new FS::cust_bill_pkg {
3371 'pkgnum' => $cust_pkg->pkgnum,
3373 'unitsetup' => $unitsetup,
3375 'unitrecur' => $unitrecur,
3376 'quantity' => $cust_pkg->quantity,
3377 'details' => \@details,
3378 'discounts' => \@discounts,
3379 'hidden' => $part_pkg->hidden,
3382 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3383 $cust_bill_pkg->sdate( $hash{last_bill} );
3384 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
3385 $cust_bill_pkg->edate( $time ) if $options{cancel};
3386 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3387 $cust_bill_pkg->sdate( $sdate );
3388 $cust_bill_pkg->edate( $cust_pkg->bill );
3389 #$cust_bill_pkg->edate( $time ) if $options{cancel};
3392 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3393 unless $part_pkg->pkgpart == $real_pkgpart;
3395 $$total_setup += $setup;
3396 $$total_recur += $recur;
3403 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3404 return $error if $error;
3406 push @$cust_bill_pkgs, $cust_bill_pkg;
3408 } #if $setup != 0 || $recur != 0
3418 my $part_pkg = shift;
3419 my $taxlisthash = shift;
3420 my $cust_bill_pkg = shift;
3421 my $cust_pkg = shift;
3422 my $invoice_time = shift;
3423 my $real_pkgpart = shift;
3424 my $options = shift;
3426 my %cust_bill_pkg = ();
3430 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3431 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3432 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3433 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3435 if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3437 if ( $conf->exists('enable_taxproducts')
3438 && ( scalar($part_pkg->part_pkg_taxoverride)
3439 || $part_pkg->has_taxproduct
3444 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3445 return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3448 foreach my $class (@classes) {
3449 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3450 return $err_or_ref unless ref($err_or_ref);
3451 $taxes{$class} = $err_or_ref;
3454 unless (exists $taxes{''}) {
3455 my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3456 return $err_or_ref unless ref($err_or_ref);
3457 $taxes{''} = $err_or_ref;
3462 my @loc_keys = qw( city county state country );
3464 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3465 my $cust_location = $cust_pkg->cust_location;
3466 %taxhash = map { $_ => $cust_location->$_() } @loc_keys;
3469 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3472 %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3475 $taxhash{'taxclass'} = $part_pkg->taxclass;
3478 my %taxhash_elim = %taxhash;
3479 my @elim = qw( city county state );
3482 #first try a match with taxclass
3483 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3485 if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
3486 #then try a match without taxclass
3487 my %no_taxclass = %taxhash_elim;
3488 $no_taxclass{ 'taxclass' } = '';
3489 @taxes = qsearch( 'cust_main_county', \%no_taxclass );
3492 $taxhash_elim{ shift(@elim) } = '';
3494 } while ( !scalar(@taxes) && scalar(@elim) );
3496 @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3498 if $self->cust_main_exemption; #just to be safe
3500 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3502 $_->set('pkgnum', $cust_pkg->pkgnum );
3503 $_->set('locationnum', $cust_pkg->locationnum );
3507 $taxes{''} = [ @taxes ];
3508 $taxes{'setup'} = [ @taxes ];
3509 $taxes{'recur'} = [ @taxes ];
3510 $taxes{$_} = [ @taxes ] foreach (@classes);
3512 # # maybe eliminate this entirely, along with all the 0% records
3513 # unless ( @taxes ) {
3515 # "fatal: can't find tax rate for state/county/country/taxclass ".
3516 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
3519 } #if $conf->exists('enable_taxproducts') ...
3524 my $separate = $conf->exists('separate_usage');
3525 my $usage_mandate = $cust_pkg->part_pkg->option('usage_mandate', 'Hush!');
3526 if ( $separate || $cust_bill_pkg->hidden || $usage_mandate ) {
3528 my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3529 my %hash = $cust_bill_pkg->hidden # maybe for all bill linked?
3530 ? ( 'section' => $temp_pkg->part_pkg->categoryname )
3533 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
3534 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
3536 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3537 push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3539 push @display, new FS::cust_bill_pkg_display
3542 ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3546 if ($separate && $section && $summary) {
3547 push @display, new FS::cust_bill_pkg_display { type => 'U',
3552 if ($usage_mandate || $section && $summary) {
3553 $hash{post_total} = 'Y';
3556 $hash{section} = $section if ($separate || $usage_mandate);
3557 push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3560 $cust_bill_pkg->set('display', \@display);
3562 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3563 foreach my $key (keys %tax_cust_bill_pkg) {
3564 my @taxes = @{ $taxes{$key} || [] };
3565 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3567 my %localtaxlisthash = ();
3568 foreach my $tax ( @taxes ) {
3570 my $taxname = ref( $tax ). ' '. $tax->taxnum;
3571 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3572 # ' locationnum'. $cust_pkg->locationnum
3573 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3575 $taxlisthash->{ $taxname } ||= [ $tax ];
3576 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
3578 $localtaxlisthash{ $taxname } ||= [ $tax ];
3579 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
3583 warn "finding taxed taxes...\n" if $DEBUG > 2;
3584 foreach my $tax ( keys %localtaxlisthash ) {
3585 my $tax_object = shift @{ $localtaxlisthash{$tax} };
3586 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3588 next unless $tax_object->can('tax_on_tax');
3590 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3591 my $totname = ref( $tot ). ' '. $tot->taxnum;
3593 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3595 next unless exists( $localtaxlisthash{ $totname } ); # only increase
3597 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3598 my $hashref_or_error =
3599 $tax_object->taxline( $localtaxlisthash{$tax},
3600 'custnum' => $self->custnum,
3601 'invoice_time' => $invoice_time,
3603 return $hashref_or_error
3604 unless ref($hashref_or_error);
3606 $taxlisthash->{ $totname } ||= [ $tot ];
3607 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
3619 my $part_pkg = shift;
3623 my $geocode = $self->geocode('cch');
3625 my @taxclassnums = map { $_->taxclassnum }
3626 $part_pkg->part_pkg_taxoverride($class);
3628 unless (@taxclassnums) {
3629 @taxclassnums = map { $_->taxclassnum }
3630 grep { $_->taxable eq 'Y' }
3631 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3633 warn "Found taxclassnum values of ". join(',', @taxclassnums)
3638 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3640 @taxes = qsearch({ 'table' => 'tax_rate',
3641 'hashref' => { 'geocode' => $geocode, },
3642 'extra_sql' => $extra_sql,
3644 if scalar(@taxclassnums);
3646 warn "Found taxes ".
3647 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
3654 =item collect [ HASHREF | OPTION => VALUE ... ]
3656 (Attempt to) collect money for this customer's outstanding invoices (see
3657 L<FS::cust_bill>). Usually used after the bill method.
3659 Actions are now triggered by billing events; see L<FS::part_event> and the
3660 billing events web interface. Old-style invoice events (see
3661 L<FS::part_bill_event>) have been deprecated.
3663 If there is an error, returns the error, otherwise returns false.
3665 Options are passed as name-value pairs.
3667 Currently available options are:
3673 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.
3677 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3681 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3685 set true to surpress email card/ACH decline notices.
3689 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)
3695 # allows for one time override of normal customer billing method
3700 my( $self, %options ) = @_;
3701 my $invoice_time = $options{'invoice_time'} || time;
3704 local $SIG{HUP} = 'IGNORE';
3705 local $SIG{INT} = 'IGNORE';
3706 local $SIG{QUIT} = 'IGNORE';
3707 local $SIG{TERM} = 'IGNORE';
3708 local $SIG{TSTP} = 'IGNORE';
3709 local $SIG{PIPE} = 'IGNORE';
3711 my $oldAutoCommit = $FS::UID::AutoCommit;
3712 local $FS::UID::AutoCommit = 0;
3715 $self->select_for_update; #mutex
3718 my $balance = $self->balance;
3719 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3722 if ( exists($options{'retry_card'}) ) {
3723 carp 'retry_card option passed to collect is deprecated; use retry';
3724 $options{'retry'} ||= $options{'retry_card'};
3726 if ( exists($options{'retry'}) && $options{'retry'} ) {
3727 my $error = $self->retry_realtime;
3729 $dbh->rollback if $oldAutoCommit;
3734 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3736 #never want to roll back an event just because it returned an error
3737 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3739 $self->do_cust_event(
3740 'debug' => ( $options{'debug'} || 0 ),
3741 'time' => $invoice_time,
3742 'check_freq' => $options{'check_freq'},
3743 'stage' => 'collect',
3748 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3750 Runs billing events; see L<FS::part_event> and the billing events web
3753 If there is an error, returns the error, otherwise returns false.
3755 Options are passed as name-value pairs.
3757 Currently available options are:
3763 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.
3767 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3771 "collect" (the default) or "pre-bill"
3775 set true to surpress email card/ACH decline notices.
3779 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)
3785 # allows for one time override of normal customer billing method
3789 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3792 my( $self, %options ) = @_;
3793 my $time = $options{'time'} || time;
3796 local $SIG{HUP} = 'IGNORE';
3797 local $SIG{INT} = 'IGNORE';
3798 local $SIG{QUIT} = 'IGNORE';
3799 local $SIG{TERM} = 'IGNORE';
3800 local $SIG{TSTP} = 'IGNORE';
3801 local $SIG{PIPE} = 'IGNORE';
3803 my $oldAutoCommit = $FS::UID::AutoCommit;
3804 local $FS::UID::AutoCommit = 0;
3807 $self->select_for_update; #mutex
3810 my $balance = $self->balance;
3811 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
3814 # if ( exists($options{'retry_card'}) ) {
3815 # carp 'retry_card option passed to collect is deprecated; use retry';
3816 # $options{'retry'} ||= $options{'retry_card'};
3818 # if ( exists($options{'retry'}) && $options{'retry'} ) {
3819 # my $error = $self->retry_realtime;
3821 # $dbh->rollback if $oldAutoCommit;
3826 # false laziness w/pay_batch::import_results
3828 my $due_cust_event = $self->due_cust_event(
3829 'debug' => ( $options{'debug'} || 0 ),
3831 'check_freq' => $options{'check_freq'},
3832 'stage' => ( $options{'stage'} || 'collect' ),
3834 unless( ref($due_cust_event) ) {
3835 $dbh->rollback if $oldAutoCommit;
3836 return $due_cust_event;
3839 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3840 #never want to roll back an event just because it or a different one
3842 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3844 foreach my $cust_event ( @$due_cust_event ) {
3848 #re-eval event conditions (a previous event could have changed things)
3849 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
3850 #don't leave stray "new/locked" records around
3851 my $error = $cust_event->delete;
3852 return $error if $error;
3857 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
3858 warn " running cust_event ". $cust_event->eventnum. "\n"
3861 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
3862 if ( my $error = $cust_event->do_event() ) {
3863 #XXX wtf is this? figure out a proper dealio with return value
3875 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
3877 Inserts database records for and returns an ordered listref of new events due
3878 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
3879 events are due, an empty listref is returned. If there is an error, returns a
3880 scalar error message.
3882 To actually run the events, call each event's test_condition method, and if
3883 still true, call the event's do_event method.
3885 Options are passed as a hashref or as a list of name-value pairs. Available
3892 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.
3896 "collect" (the default) or "pre-bill"
3900 "Current time" for the events.
3904 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)
3908 Only return events for the specified eventtable (by default, events of all eventtables are returned)
3912 Explicitly pass the objects to be tested (typically used with eventtable).
3916 Set to true to return the objects, but not actually insert them into the
3923 sub due_cust_event {
3925 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
3928 #my $DEBUG = $opt{'debug'}
3929 local($DEBUG) = $opt{'debug'}
3930 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
3932 warn "$me due_cust_event called with options ".
3933 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
3936 $opt{'time'} ||= time;
3938 local $SIG{HUP} = 'IGNORE';
3939 local $SIG{INT} = 'IGNORE';
3940 local $SIG{QUIT} = 'IGNORE';
3941 local $SIG{TERM} = 'IGNORE';
3942 local $SIG{TSTP} = 'IGNORE';
3943 local $SIG{PIPE} = 'IGNORE';
3945 my $oldAutoCommit = $FS::UID::AutoCommit;
3946 local $FS::UID::AutoCommit = 0;
3949 $self->select_for_update #mutex
3950 unless $opt{testonly};
3953 # find possible events (initial search)
3956 my @cust_event = ();
3958 my @eventtable = $opt{'eventtable'}
3959 ? ( $opt{'eventtable'} )
3960 : FS::part_event->eventtables_runorder;
3962 foreach my $eventtable ( @eventtable ) {
3965 if ( $opt{'objects'} ) {
3967 @objects = @{ $opt{'objects'} };
3971 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
3972 @objects = ( $eventtable eq 'cust_main' )
3974 : ( $self->$eventtable() );
3978 my @e_cust_event = ();
3980 my $cross = "CROSS JOIN $eventtable";
3981 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
3982 unless $eventtable eq 'cust_main';
3984 foreach my $object ( @objects ) {
3986 #this first search uses the condition_sql magic for optimization.
3987 #the more possible events we can eliminate in this step the better
3989 my $cross_where = '';
3990 my $pkey = $object->primary_key;
3991 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
3993 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
3995 FS::part_event_condition->where_conditions_sql( $eventtable,
3996 'time'=>$opt{'time'}
3998 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
4000 $extra_sql = "AND $extra_sql" if $extra_sql;
4002 #here is the agent virtualization
4003 $extra_sql .= " AND ( part_event.agentnum IS NULL
4004 OR part_event.agentnum = ". $self->agentnum. ' )';
4006 $extra_sql .= " $order";
4008 warn "searching for events for $eventtable ". $object->$pkey. "\n"
4009 if $opt{'debug'} > 2;
4010 my @part_event = qsearch( {
4011 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
4012 'select' => 'part_event.*',
4013 'table' => 'part_event',
4014 'addl_from' => "$cross $join",
4015 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
4016 'eventtable' => $eventtable,
4019 'extra_sql' => "AND $cross_where $extra_sql",
4023 my $pkey = $object->primary_key;
4024 warn " ". scalar(@part_event).
4025 " possible events found for $eventtable ". $object->$pkey(). "\n";
4028 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
4032 warn " ". scalar(@e_cust_event).
4033 " subtotal possible cust events found for $eventtable\n"
4036 push @cust_event, @e_cust_event;
4040 warn " ". scalar(@cust_event).
4041 " total possible cust events found in initial search\n"
4049 $opt{stage} ||= 'collect';
4051 grep { my $stage = $_->part_event->event_stage;
4052 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
4062 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
4063 'stats_hashref' => \%unsat ),
4066 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
4069 warn " invalid conditions not eliminated with condition_sql:\n".
4070 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
4071 if keys %unsat && $DEBUG; # > 1;
4077 unless( $opt{testonly} ) {
4078 foreach my $cust_event ( @cust_event ) {
4080 my $error = $cust_event->insert();
4082 $dbh->rollback if $oldAutoCommit;
4089 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4095 warn " returning events: ". Dumper(@cust_event). "\n"
4102 =item retry_realtime
4104 Schedules realtime / batch credit card / electronic check / LEC billing
4105 events for for retry. Useful if card information has changed or manual
4106 retry is desired. The 'collect' method must be called to actually retry
4109 Implementation details: For either this customer, or for each of this
4110 customer's open invoices, changes the status of the first "done" (with
4111 statustext error) realtime processing event to "failed".
4115 sub retry_realtime {
4118 local $SIG{HUP} = 'IGNORE';
4119 local $SIG{INT} = 'IGNORE';
4120 local $SIG{QUIT} = 'IGNORE';
4121 local $SIG{TERM} = 'IGNORE';
4122 local $SIG{TSTP} = 'IGNORE';
4123 local $SIG{PIPE} = 'IGNORE';
4125 my $oldAutoCommit = $FS::UID::AutoCommit;
4126 local $FS::UID::AutoCommit = 0;
4129 #a little false laziness w/due_cust_event (not too bad, really)
4131 my $join = FS::part_event_condition->join_conditions_sql;
4132 my $order = FS::part_event_condition->order_conditions_sql;
4135 . join ( ' OR ' , map {
4136 "( part_event.eventtable = " . dbh->quote($_)
4137 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
4138 } FS::part_event->eventtables)
4141 #here is the agent virtualization
4142 my $agent_virt = " ( part_event.agentnum IS NULL
4143 OR part_event.agentnum = ". $self->agentnum. ' )';
4145 #XXX this shouldn't be hardcoded, actions should declare it...
4146 my @realtime_events = qw(
4147 cust_bill_realtime_card
4148 cust_bill_realtime_check
4149 cust_bill_realtime_lec
4153 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
4158 my @cust_event = qsearchs({
4159 'table' => 'cust_event',
4160 'select' => 'cust_event.*',
4161 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
4162 'hashref' => { 'status' => 'done' },
4163 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
4164 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
4167 my %seen_invnum = ();
4168 foreach my $cust_event (@cust_event) {
4170 #max one for the customer, one for each open invoice
4171 my $cust_X = $cust_event->cust_X;
4172 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
4176 or $cust_event->part_event->eventtable eq 'cust_bill'
4179 my $error = $cust_event->retry;
4181 $dbh->rollback if $oldAutoCommit;
4182 return "error scheduling event for retry: $error";
4187 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4195 =item realtime_collect [ OPTION => VALUE ... ]
4197 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4198 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4199 gateway. See L<http://420.am/business-onlinepayment> and
4200 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4202 On failure returns an error message.
4204 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.
4206 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4208 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
4209 then it is deduced from the customer record.
4211 If no I<amount> is specified, then the customer balance is used.
4213 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4214 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4215 if set, will override the value from the customer record.
4217 I<description> is a free-text field passed to the gateway. It defaults to
4218 the value defined by the business-onlinepayment-description configuration
4219 option, or "Internet services" if that is unset.
4221 If an I<invnum> is specified, this payment (if successful) is applied to the
4222 specified invoice. If you don't specify an I<invnum> you might want to
4223 call the B<apply_payments> method or set the I<apply> option.
4225 I<apply> can be set to true to apply a resulting payment.
4227 I<quiet> can be set true to surpress email decline notices.
4229 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4230 resulting paynum, if any.
4232 I<payunique> is a unique identifier for this payment.
4234 I<session_id> is a session identifier associated with this payment.
4236 I<depend_jobnum> allows payment capture to unlock export jobs
4240 sub realtime_collect {
4241 my( $self, %options ) = @_;
4244 warn "$me realtime_collect:\n";
4245 warn " $_ => $options{$_}\n" foreach keys %options;
4248 $options{amount} = $self->balance unless exists( $options{amount} );
4249 $options{method} = FS::payby->payby2bop($self->payby)
4250 unless exists( $options{method} );
4252 return $self->realtime_bop({%options});
4256 =item realtime_bop { [ ARG => VALUE ... ] }
4258 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4259 via a Business::OnlinePayment realtime gateway. See
4260 L<http://420.am/business-onlinepayment> for supported gateways.
4262 Required arguments in the hashref are I<method>, and I<amount>
4264 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4266 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4268 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4269 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4270 if set, will override the value from the customer record.
4272 I<description> is a free-text field passed to the gateway. It defaults to
4273 the value defined by the business-onlinepayment-description configuration
4274 option, or "Internet services" if that is unset.
4276 If an I<invnum> is specified, this payment (if successful) is applied to the
4277 specified invoice. If you don't specify an I<invnum> you might want to
4278 call the B<apply_payments> method or set the I<apply> option.
4280 I<apply> can be set to true to apply a resulting payment.
4282 I<quiet> can be set true to surpress email decline notices.
4284 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4285 resulting paynum, if any.
4287 I<payunique> is a unique identifier for this payment.
4289 I<session_id> is a session identifier associated with this payment.
4291 I<depend_jobnum> allows payment capture to unlock export jobs
4293 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4297 # some helper routines
4298 sub _bop_recurring_billing {
4299 my( $self, %opt ) = @_;
4301 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
4303 if ( defined($method) && $method eq 'transaction_is_recur' ) {
4305 return 1 if $opt{'trans_is_recur'};
4309 my %hash = ( 'custnum' => $self->custnum,
4314 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4315 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4325 sub _payment_gateway {
4326 my ($self, $options) = @_;
4328 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4329 unless exists($options->{payment_gateway});
4331 $options->{payment_gateway};
4335 my ($self, $options) = @_;
4338 'login' => $options->{payment_gateway}->gateway_username,
4339 'password' => $options->{payment_gateway}->gateway_password,
4344 my ($self, $options) = @_;
4346 $options->{payment_gateway}->gatewaynum
4347 ? $options->{payment_gateway}->options
4348 : @{ $options->{payment_gateway}->get('options') };
4353 my ($self, $options) = @_;
4355 unless ( $options->{'description'} ) {
4356 if ( $conf->exists('business-onlinepayment-description') ) {
4357 my $dtempl = $conf->config('business-onlinepayment-description');
4359 my $agent = $self->agent->agent;
4361 $options->{'description'} = eval qq("$dtempl");
4363 $options->{'description'} = 'Internet services';
4367 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4368 $options->{invnum} ||= '';
4369 $options->{payname} = $self->payname unless exists( $options->{payname} );
4373 my ($self, $options) = @_;
4376 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4377 $content{customer_ip} = $payip if length($payip);
4379 $content{invoice_number} = $options->{'invnum'}
4380 if exists($options->{'invnum'}) && length($options->{'invnum'});
4382 $content{email_customer} =
4383 ( $conf->exists('business-onlinepayment-email_customer')
4384 || $conf->exists('business-onlinepayment-email-override') );
4386 my ($payname, $payfirst, $paylast);
4387 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
4388 ($payname = $options->{payname}) =~
4389 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4390 or return "Illegal payname $payname";
4391 ($payfirst, $paylast) = ($1, $2);
4393 $payfirst = $self->getfield('first');
4394 $paylast = $self->getfield('last');
4395 $payname = "$payfirst $paylast";
4398 $content{last_name} = $paylast;
4399 $content{first_name} = $payfirst;
4401 $content{name} = $payname;
4403 $content{address} = exists($options->{'address1'})
4404 ? $options->{'address1'}
4406 my $address2 = exists($options->{'address2'})
4407 ? $options->{'address2'}
4409 $content{address} .= ", ". $address2 if length($address2);
4411 $content{city} = exists($options->{city})
4414 $content{state} = exists($options->{state})
4417 $content{zip} = exists($options->{zip})
4420 $content{country} = exists($options->{country})
4421 ? $options->{country}
4424 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4425 $content{phone} = $self->daytime || $self->night;
4430 my %bop_method2payby = (
4440 if (ref($_[0]) eq 'HASH') {
4441 %options = %{$_[0]};
4443 my ( $method, $amount ) = ( shift, shift );
4445 $options{method} = $method;
4446 $options{amount} = $amount;
4450 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
4451 warn " $_ => $options{$_}\n" foreach keys %options;
4454 return $self->fake_bop(%options) if $options{'fake'};
4456 $self->_bop_defaults(\%options);
4459 # set trans_is_recur based on invnum if there is one
4462 my $trans_is_recur = 0;
4463 if ( $options{'invnum'} ) {
4465 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
4466 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
4469 map { $_->part_pkg }
4471 map { $_->cust_pkg }
4472 $cust_bill->cust_bill_pkg;
4475 if grep { $_->freq ne '0' } @part_pkg;
4483 my $payment_gateway = $self->_payment_gateway( \%options );
4484 my $namespace = $payment_gateway->gateway_namespace;
4486 eval "use $namespace";
4490 # check for banned credit card/ACH
4493 my $ban = qsearchs('banned_pay', {
4494 'payby' => $bop_method2payby{$options{method}},
4495 'payinfo' => md5_base64($options{payinfo}),
4497 return "Banned credit card" if $ban;
4503 my $bop_content = $self->_bop_content(\%options);
4504 return $bop_content unless ref($bop_content);
4506 my @invoicing_list = $self->invoicing_list_emailonly;
4507 if ( $conf->exists('emailinvoiceautoalways')
4508 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4509 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4510 push @invoicing_list, $self->all_emails;
4513 my $email = ($conf->exists('business-onlinepayment-email-override'))
4514 ? $conf->config('business-onlinepayment-email-override')
4515 : $invoicing_list[0];
4519 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
4521 $content{card_number} = $options{payinfo};
4522 $paydate = exists($options{'paydate'})
4523 ? $options{'paydate'}
4525 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4526 $content{expiration} = "$2/$1";
4528 my $paycvv = exists($options{'paycvv'})
4529 ? $options{'paycvv'}
4531 $content{cvv2} = $paycvv
4534 my $paystart_month = exists($options{'paystart_month'})
4535 ? $options{'paystart_month'}
4536 : $self->paystart_month;
4538 my $paystart_year = exists($options{'paystart_year'})
4539 ? $options{'paystart_year'}
4540 : $self->paystart_year;
4542 $content{card_start} = "$paystart_month/$paystart_year"
4543 if $paystart_month && $paystart_year;
4545 my $payissue = exists($options{'payissue'})
4546 ? $options{'payissue'}
4548 $content{issue_number} = $payissue if $payissue;
4550 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
4551 'trans_is_recur' => $trans_is_recur,
4555 $content{recurring_billing} = 'YES';
4556 $content{acct_code} = 'rebill'
4557 if $conf->exists('credit_card-recurring_billing_acct_code');
4560 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
4561 ( $content{account_number}, $content{routing_code} ) =
4562 split('@', $options{payinfo});
4563 $content{bank_name} = $options{payname};
4564 $content{bank_state} = exists($options{'paystate'})
4565 ? $options{'paystate'}
4566 : $self->getfield('paystate');
4567 $content{account_type} = exists($options{'paytype'})
4568 ? uc($options{'paytype'}) || 'CHECKING'
4569 : uc($self->getfield('paytype')) || 'CHECKING';
4570 $content{account_name} = $self->getfield('first'). ' '.
4571 $self->getfield('last');
4573 $content{customer_org} = $self->company ? 'B' : 'I';
4574 $content{state_id} = exists($options{'stateid'})
4575 ? $options{'stateid'}
4576 : $self->getfield('stateid');
4577 $content{state_id_state} = exists($options{'stateid_state'})
4578 ? $options{'stateid_state'}
4579 : $self->getfield('stateid_state');
4580 $content{customer_ssn} = exists($options{'ss'})
4583 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
4584 $content{phone} = $options{payinfo};
4585 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4592 # run transaction(s)
4595 my $balance = exists( $options{'balance'} )
4596 ? $options{'balance'}
4599 $self->select_for_update; #mutex ... just until we get our pending record in
4601 #the checks here are intended to catch concurrent payments
4602 #double-form-submission prevention is taken care of in cust_pay_pending::check
4605 return "The customer's balance has changed; $options{method} transaction aborted."
4606 if $self->balance < $balance;
4607 #&& $self->balance < $options{amount}; #might as well anyway?
4609 #also check and make sure there aren't *other* pending payments for this cust
4611 my @pending = qsearch('cust_pay_pending', {
4612 'custnum' => $self->custnum,
4613 'status' => { op=>'!=', value=>'done' }
4615 return "A payment is already being processed for this customer (".
4616 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4617 "); $options{method} transaction aborted."
4618 if scalar(@pending);
4620 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4622 my $cust_pay_pending = new FS::cust_pay_pending {
4623 'custnum' => $self->custnum,
4624 #'invnum' => $options{'invnum'},
4625 'paid' => $options{amount},
4627 'payby' => $bop_method2payby{$options{method}},
4628 'payinfo' => $options{payinfo},
4629 'paydate' => $paydate,
4630 'recurring_billing' => $content{recurring_billing},
4631 'pkgnum' => $options{'pkgnum'},
4633 'gatewaynum' => $payment_gateway->gatewaynum || '',
4634 'session_id' => $options{session_id} || '',
4635 'jobnum' => $options{depend_jobnum} || '',
4637 $cust_pay_pending->payunique( $options{payunique} )
4638 if defined($options{payunique}) && length($options{payunique});
4639 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4640 return $cpp_new_err if $cpp_new_err;
4642 my( $action1, $action2 ) =
4643 split( /\s*\,\s*/, $payment_gateway->gateway_action );
4645 my $transaction = new $namespace( $payment_gateway->gateway_module,
4646 $self->_bop_options(\%options),
4649 $transaction->content(
4650 'type' => $options{method},
4651 $self->_bop_auth(\%options),
4652 'action' => $action1,
4653 'description' => $options{'description'},
4654 'amount' => $options{amount},
4655 #'invoice_number' => $options{'invnum'},
4656 'customer_id' => $self->custnum,
4658 'reference' => $cust_pay_pending->paypendingnum, #for now
4663 $cust_pay_pending->status('pending');
4664 my $cpp_pending_err = $cust_pay_pending->replace;
4665 return $cpp_pending_err if $cpp_pending_err;
4668 my $BOP_TESTING = 0;
4669 my $BOP_TESTING_SUCCESS = 1;
4671 unless ( $BOP_TESTING ) {
4672 $transaction->test_transaction(1)
4673 if $conf->exists('business-onlinepayment-test_transaction');
4674 $transaction->submit();
4676 if ( $BOP_TESTING_SUCCESS ) {
4677 $transaction->is_success(1);
4678 $transaction->authorization('fake auth');
4680 $transaction->is_success(0);
4681 $transaction->error_message('fake failure');
4685 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4687 return { reference => $cust_pay_pending->paypendingnum,
4688 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
4690 } elsif ( $transaction->is_success() && $action2 ) {
4692 $cust_pay_pending->status('authorized');
4693 my $cpp_authorized_err = $cust_pay_pending->replace;
4694 return $cpp_authorized_err if $cpp_authorized_err;
4696 my $auth = $transaction->authorization;
4697 my $ordernum = $transaction->can('order_number')
4698 ? $transaction->order_number
4702 new Business::OnlinePayment( $payment_gateway->gateway_module,
4703 $self->_bop_options(\%options),
4708 type => $options{method},
4710 $self->_bop_auth(\%options),
4711 order_number => $ordernum,
4712 amount => $options{amount},
4713 authorization => $auth,
4714 description => $options{'description'},
4717 foreach my $field (qw( authorization_source_code returned_ACI
4718 transaction_identifier validation_code
4719 transaction_sequence_num local_transaction_date
4720 local_transaction_time AVS_result_code )) {
4721 $capture{$field} = $transaction->$field() if $transaction->can($field);
4724 $capture->content( %capture );
4726 $capture->test_transaction(1)
4727 if $conf->exists('business-onlinepayment-test_transaction');
4730 unless ( $capture->is_success ) {
4731 my $e = "Authorization successful but capture failed, custnum #".
4732 $self->custnum. ': '. $capture->result_code.
4733 ": ". $capture->error_message;
4741 # remove paycvv after initial transaction
4744 #false laziness w/misc/process/payment.cgi - check both to make sure working
4746 if ( defined $self->dbdef_table->column('paycvv')
4747 && length($self->paycvv)
4748 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
4750 my $error = $self->remove_cvv;
4752 warn "WARNING: error removing cvv: $error\n";
4761 if ( $transaction->can('card_token') && $transaction->card_token ) {
4763 $self->card_token($transaction->card_token);
4765 if ( $options{'payinfo'} eq $self->payinfo ) {
4766 $self->payinfo($transaction->card_token);
4767 my $error = $self->replace;
4769 warn "WARNING: error storing token: $error, but proceeding anyway\n";
4779 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
4791 if (ref($_[0]) eq 'HASH') {
4792 %options = %{$_[0]};
4794 my ( $method, $amount ) = ( shift, shift );
4796 $options{method} = $method;
4797 $options{amount} = $amount;
4800 if ( $options{'fake_failure'} ) {
4801 return "Error: No error; test failure requested with fake_failure";
4805 #if ( $payment_gateway->gatewaynum ) { # agent override
4806 # $paybatch = $payment_gateway->gatewaynum. '-';
4809 #$paybatch .= "$processor:". $transaction->authorization;
4811 #$paybatch .= ':'. $transaction->order_number
4812 # if $transaction->can('order_number')
4813 # && length($transaction->order_number);
4815 my $paybatch = 'FakeProcessor:54:32';
4817 my $cust_pay = new FS::cust_pay ( {
4818 'custnum' => $self->custnum,
4819 'invnum' => $options{'invnum'},
4820 'paid' => $options{amount},
4822 'payby' => $bop_method2payby{$options{method}},
4823 #'payinfo' => $payinfo,
4824 'payinfo' => '4111111111111111',
4825 'paybatch' => $paybatch,
4826 #'paydate' => $paydate,
4827 'paydate' => '2012-05-01',
4829 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
4831 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4834 $cust_pay->invnum(''); #try again with no specific invnum
4835 my $error2 = $cust_pay->insert( $options{'manual'} ?
4836 ( 'manual' => 1 ) : ()
4839 # gah, even with transactions.
4840 my $e = 'WARNING: Card/ACH debited but database not updated - '.
4841 "error inserting (fake!) payment: $error2".
4842 " (previously tried insert with invnum #$options{'invnum'}" .
4849 if ( $options{'paynum_ref'} ) {
4850 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4853 return ''; #no error
4858 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
4860 # Wraps up processing of a realtime credit card, ACH (electronic check) or
4861 # phone bill transaction.
4863 sub _realtime_bop_result {
4864 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
4866 warn "$me _realtime_bop_result: pending transaction ".
4867 $cust_pay_pending->paypendingnum. "\n";
4868 warn " $_ => $options{$_}\n" foreach keys %options;
4871 my $payment_gateway = $options{payment_gateway}
4872 or return "no payment gateway in arguments to _realtime_bop_result";
4874 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
4875 my $cpp_captured_err = $cust_pay_pending->replace;
4876 return $cpp_captured_err if $cpp_captured_err;
4878 if ( $transaction->is_success() ) {
4881 if ( $payment_gateway->gatewaynum ) { # agent override
4882 $paybatch = $payment_gateway->gatewaynum. '-';
4885 $paybatch .= $payment_gateway->gateway_module. ":".
4886 $transaction->authorization;
4888 $paybatch .= ':'. $transaction->order_number
4889 if $transaction->can('order_number')
4890 && length($transaction->order_number);
4892 my $cust_pay = new FS::cust_pay ( {
4893 'custnum' => $self->custnum,
4894 'invnum' => $options{'invnum'},
4895 'paid' => $cust_pay_pending->paid,
4897 'payby' => $cust_pay_pending->payby,
4898 'payinfo' => $options{'payinfo'},
4899 'paybatch' => $paybatch,
4900 'paydate' => $cust_pay_pending->paydate,
4901 'pkgnum' => $cust_pay_pending->pkgnum,
4903 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
4904 $cust_pay->payunique( $options{payunique} )
4905 if defined($options{payunique}) && length($options{payunique});
4907 my $oldAutoCommit = $FS::UID::AutoCommit;
4908 local $FS::UID::AutoCommit = 0;
4911 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
4913 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4916 $cust_pay->invnum(''); #try again with no specific invnum
4917 my $error2 = $cust_pay->insert( $options{'manual'} ?
4918 ( 'manual' => 1 ) : ()
4921 # gah. but at least we have a record of the state we had to abort in
4922 # from cust_pay_pending now.
4923 my $e = "WARNING: $options{method} captured but payment not recorded -".
4924 " error inserting payment (". $payment_gateway->gateway_module.
4926 " (previously tried insert with invnum #$options{'invnum'}" .
4927 ": $error ) - pending payment saved as paypendingnum ".
4928 $cust_pay_pending->paypendingnum. "\n";
4934 my $jobnum = $cust_pay_pending->jobnum;
4936 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
4938 unless ( $placeholder ) {
4939 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4940 my $e = "WARNING: $options{method} captured but job $jobnum not ".
4941 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
4946 $error = $placeholder->delete;
4949 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4950 my $e = "WARNING: $options{method} captured but could not delete ".
4951 "job $jobnum for paypendingnum ".
4952 $cust_pay_pending->paypendingnum. ": $error\n";
4959 if ( $options{'paynum_ref'} ) {
4960 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4963 $cust_pay_pending->status('done');
4964 $cust_pay_pending->statustext('captured');
4965 $cust_pay_pending->paynum($cust_pay->paynum);
4966 my $cpp_done_err = $cust_pay_pending->replace;
4968 if ( $cpp_done_err ) {
4970 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4971 my $e = "WARNING: $options{method} captured but payment not recorded - ".
4972 "error updating status for paypendingnum ".
4973 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
4979 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4981 if ( $options{'apply'} ) {
4982 my $apply_error = $self->apply_payments_and_credits;
4983 if ( $apply_error ) {
4984 warn "WARNING: error applying payment: $apply_error\n";
4985 #but we still should return no error cause the payment otherwise went
4990 return ''; #no error
4996 my $perror = $payment_gateway->gateway_module. " error: ".
4997 $transaction->error_message;
4999 my $jobnum = $cust_pay_pending->jobnum;
5001 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5003 if ( $placeholder ) {
5004 my $error = $placeholder->depended_delete;
5005 $error ||= $placeholder->delete;
5006 warn "error removing provisioning jobs after declined paypendingnum ".
5007 $cust_pay_pending->paypendingnum. "\n";
5009 my $e = "error finding job $jobnum for declined paypendingnum ".
5010 $cust_pay_pending->paypendingnum. "\n";
5016 unless ( $transaction->error_message ) {
5019 if ( $transaction->can('response_page') ) {
5021 'page' => ( $transaction->can('response_page')
5022 ? $transaction->response_page
5025 'code' => ( $transaction->can('response_code')
5026 ? $transaction->response_code
5029 'headers' => ( $transaction->can('response_headers')
5030 ? $transaction->response_headers
5036 "No additional debugging information available for ".
5037 $payment_gateway->gateway_module;
5040 $perror .= "No error_message returned from ".
5041 $payment_gateway->gateway_module. " -- ".
5042 ( ref($t_response) ? Dumper($t_response) : $t_response );
5046 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
5047 && $conf->exists('emaildecline')
5048 && grep { $_ ne 'POST' } $self->invoicing_list
5049 && ! grep { $transaction->error_message =~ /$_/ }
5050 $conf->config('emaildecline-exclude')
5052 my @templ = $conf->config('declinetemplate');
5053 my $template = new Text::Template (
5055 SOURCE => [ map "$_\n", @templ ],
5056 ) or return "($perror) can't create template: $Text::Template::ERROR";
5057 $template->compile()
5058 or return "($perror) can't compile template: $Text::Template::ERROR";
5062 scalar( $conf->config('company_name', $self->agentnum ) ),
5063 'company_address' =>
5064 join("\n", $conf->config('company_address', $self->agentnum ) ),
5065 'error' => $transaction->error_message,
5068 my $error = send_email(
5069 'from' => $conf->config('invoice_from', $self->agentnum ),
5070 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
5071 'subject' => 'Your payment could not be processed',
5072 'body' => [ $template->fill_in(HASH => $templ_hash) ],
5075 $perror .= " (also received error sending decline notification: $error)"
5080 $cust_pay_pending->status('done');
5081 $cust_pay_pending->statustext("declined: $perror");
5082 my $cpp_done_err = $cust_pay_pending->replace;
5083 if ( $cpp_done_err ) {
5084 my $e = "WARNING: $options{method} declined but pending payment not ".
5085 "resolved - error updating status for paypendingnum ".
5086 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5088 $perror = "$e ($perror)";
5096 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
5098 Verifies successful third party processing of a realtime credit card,
5099 ACH (electronic check) or phone bill transaction via a
5100 Business::OnlineThirdPartyPayment realtime gateway. See
5101 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
5103 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
5105 The additional options I<payname>, I<city>, I<state>,
5106 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5107 if set, will override the value from the customer record.
5109 I<description> is a free-text field passed to the gateway. It defaults to
5110 "Internet services".
5112 If an I<invnum> is specified, this payment (if successful) is applied to the
5113 specified invoice. If you don't specify an I<invnum> you might want to
5114 call the B<apply_payments> method.
5116 I<quiet> can be set true to surpress email decline notices.
5118 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
5119 resulting paynum, if any.
5121 I<payunique> is a unique identifier for this payment.
5123 Returns a hashref containing elements bill_error (which will be undefined
5124 upon success) and session_id of any associated session.
5128 sub realtime_botpp_capture {
5129 my( $self, $cust_pay_pending, %options ) = @_;
5131 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5132 warn " $_ => $options{$_}\n" foreach keys %options;
5135 eval "use Business::OnlineThirdPartyPayment";
5139 # select the gateway
5142 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5144 my $payment_gateway = $cust_pay_pending->gatewaynum
5145 ? qsearchs( 'payment_gateway',
5146 { gatewaynum => $cust_pay_pending->gatewaynum }
5148 : $self->agent->payment_gateway( 'method' => $method,
5149 # 'invnum' => $cust_pay_pending->invnum,
5150 # 'payinfo' => $cust_pay_pending->payinfo,
5153 $options{payment_gateway} = $payment_gateway; # for the helper subs
5159 my @invoicing_list = $self->invoicing_list_emailonly;
5160 if ( $conf->exists('emailinvoiceautoalways')
5161 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5162 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5163 push @invoicing_list, $self->all_emails;
5166 my $email = ($conf->exists('business-onlinepayment-email-override'))
5167 ? $conf->config('business-onlinepayment-email-override')
5168 : $invoicing_list[0];
5172 $content{email_customer} =
5173 ( $conf->exists('business-onlinepayment-email_customer')
5174 || $conf->exists('business-onlinepayment-email-override') );
5177 # run transaction(s)
5181 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5182 $self->_bop_options(\%options),
5185 $transaction->reference({ %options });
5187 $transaction->content(
5189 $self->_bop_auth(\%options),
5190 'action' => 'Post Authorization',
5191 'description' => $options{'description'},
5192 'amount' => $cust_pay_pending->paid,
5193 #'invoice_number' => $options{'invnum'},
5194 'customer_id' => $self->custnum,
5195 'referer' => 'http://cleanwhisker.420.am/',
5196 'reference' => $cust_pay_pending->paypendingnum,
5198 'phone' => $self->daytime || $self->night,
5200 # plus whatever is required for bogus capture avoidance
5203 $transaction->submit();
5206 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5209 bill_error => $error,
5210 session_id => $cust_pay_pending->session_id,
5215 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5219 sub default_payment_gateway {
5220 my( $self, $method ) = @_;
5222 die "Real-time processing not enabled\n"
5223 unless $conf->exists('business-onlinepayment');
5225 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5228 my $bop_config = 'business-onlinepayment';
5229 $bop_config .= '-ach'
5230 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5231 my ( $processor, $login, $password, $action, @bop_options ) =
5232 $conf->config($bop_config);
5233 $action ||= 'normal authorization';
5234 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5235 die "No real-time processor is enabled - ".
5236 "did you set the business-onlinepayment configuration value?\n"
5239 ( $processor, $login, $password, $action, @bop_options )
5244 Removes the I<paycvv> field from the database directly.
5246 If there is an error, returns the error, otherwise returns false.
5252 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5253 or return dbh->errstr;
5254 $sth->execute($self->custnum)
5255 or return $sth->errstr;
5260 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5262 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5263 via a Business::OnlinePayment realtime gateway. See
5264 L<http://420.am/business-onlinepayment> for supported gateways.
5266 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5268 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5270 Most gateways require a reference to an original payment transaction to refund,
5271 so you probably need to specify a I<paynum>.
5273 I<amount> defaults to the original amount of the payment if not specified.
5275 I<reason> specifies a reason for the refund.
5277 I<paydate> specifies the expiration date for a credit card overriding the
5278 value from the customer record or the payment record. Specified as yyyy-mm-dd
5280 Implementation note: If I<amount> is unspecified or equal to the amount of the
5281 orignal payment, first an attempt is made to "void" the transaction via
5282 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5283 the normal attempt is made to "refund" ("credit") the transaction via the
5284 gateway is attempted.
5286 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5287 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5288 #if set, will override the value from the customer record.
5290 #If an I<invnum> is specified, this payment (if successful) is applied to the
5291 #specified invoice. If you don't specify an I<invnum> you might want to
5292 #call the B<apply_payments> method.
5296 #some false laziness w/realtime_bop, not enough to make it worth merging
5297 #but some useful small subs should be pulled out
5298 sub realtime_refund_bop {
5302 if (ref($_[0]) eq 'HASH') {
5303 %options = %{$_[0]};
5307 $options{method} = $method;
5311 warn "$me realtime_refund_bop (new): $options{method} refund\n";
5312 warn " $_ => $options{$_}\n" foreach keys %options;
5316 # look up the original payment and optionally a gateway for that payment
5320 my $amount = $options{'amount'};
5322 my( $processor, $login, $password, @bop_options, $namespace ) ;
5323 my( $auth, $order_number ) = ( '', '', '' );
5325 if ( $options{'paynum'} ) {
5327 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
5328 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5329 or return "Unknown paynum $options{'paynum'}";
5330 $amount ||= $cust_pay->paid;
5332 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5333 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5334 $cust_pay->paybatch;
5335 my $gatewaynum = '';
5336 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5338 if ( $gatewaynum ) { #gateway for the payment to be refunded
5340 my $payment_gateway =
5341 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5342 die "payment gateway $gatewaynum not found"
5343 unless $payment_gateway;
5345 $processor = $payment_gateway->gateway_module;
5346 $login = $payment_gateway->gateway_username;
5347 $password = $payment_gateway->gateway_password;
5348 $namespace = $payment_gateway->gateway_namespace;
5349 @bop_options = $payment_gateway->options;
5351 } else { #try the default gateway
5354 my $payment_gateway =
5355 $self->agent->payment_gateway('method' => $options{method});
5357 ( $conf_processor, $login, $password, $namespace ) =
5358 map { my $method = "gateway_$_"; $payment_gateway->$method }
5359 qw( module username password namespace );
5361 @bop_options = $payment_gateway->gatewaynum
5362 ? $payment_gateway->options
5363 : @{ $payment_gateway->get('options') };
5365 return "processor of payment $options{'paynum'} $processor does not".
5366 " match default processor $conf_processor"
5367 unless $processor eq $conf_processor;
5372 } else { # didn't specify a paynum, so look for agent gateway overrides
5373 # like a normal transaction
5375 my $payment_gateway =
5376 $self->agent->payment_gateway( 'method' => $options{method},
5377 #'payinfo' => $payinfo,
5379 my( $processor, $login, $password, $namespace ) =
5380 map { my $method = "gateway_$_"; $payment_gateway->$method }
5381 qw( module username password namespace );
5383 my @bop_options = $payment_gateway->gatewaynum
5384 ? $payment_gateway->options
5385 : @{ $payment_gateway->get('options') };
5388 return "neither amount nor paynum specified" unless $amount;
5390 eval "use $namespace";
5394 'type' => $options{method},
5396 'password' => $password,
5397 'order_number' => $order_number,
5398 'amount' => $amount,
5399 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5401 $content{authorization} = $auth
5402 if length($auth); #echeck/ACH transactions have an order # but no auth
5403 #(at least with authorize.net)
5405 my $disable_void_after;
5406 if ($conf->exists('disable_void_after')
5407 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5408 $disable_void_after = $1;
5411 #first try void if applicable
5412 if ( $cust_pay && $cust_pay->paid == $amount
5414 ( not defined($disable_void_after) )
5415 || ( time < ($cust_pay->_date + $disable_void_after ) )
5418 warn " attempting void\n" if $DEBUG > 1;
5419 my $void = new Business::OnlinePayment( $processor, @bop_options );
5420 if ( $void->can('info') ) {
5421 if ( $cust_pay->payby eq 'CARD'
5422 && $void->info('CC_void_requires_card') )
5424 $content{'card_number'} = $cust_pay->payinfo;
5425 } elsif ( $cust_pay->payby eq 'CHEK'
5426 && $void->info('ECHECK_void_requires_account') )
5428 ( $content{'account_number'}, $content{'routing_code'} ) =
5429 split('@', $cust_pay->payinfo);
5430 $content{'name'} = $self->get('first'). ' '. $self->get('last');
5433 $void->content( 'action' => 'void', %content );
5434 $void->test_transaction(1)
5435 if $conf->exists('business-onlinepayment-test_transaction');
5437 if ( $void->is_success ) {
5438 my $error = $cust_pay->void($options{'reason'});
5440 # gah, even with transactions.
5441 my $e = 'WARNING: Card/ACH voided but database not updated - '.
5442 "error voiding payment: $error";
5446 warn " void successful\n" if $DEBUG > 1;
5451 warn " void unsuccessful, trying refund\n"
5455 my $address = $self->address1;
5456 $address .= ", ". $self->address2 if $self->address2;
5458 my($payname, $payfirst, $paylast);
5459 if ( $self->payname && $options{method} ne 'ECHECK' ) {
5460 $payname = $self->payname;
5461 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5462 or return "Illegal payname $payname";
5463 ($payfirst, $paylast) = ($1, $2);
5465 $payfirst = $self->getfield('first');
5466 $paylast = $self->getfield('last');
5467 $payname = "$payfirst $paylast";
5470 my @invoicing_list = $self->invoicing_list_emailonly;
5471 if ( $conf->exists('emailinvoiceautoalways')
5472 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5473 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5474 push @invoicing_list, $self->all_emails;
5477 my $email = ($conf->exists('business-onlinepayment-email-override'))
5478 ? $conf->config('business-onlinepayment-email-override')
5479 : $invoicing_list[0];
5481 my $payip = exists($options{'payip'})
5484 $content{customer_ip} = $payip
5488 if ( $options{method} eq 'CC' ) {
5491 $content{card_number} = $payinfo = $cust_pay->payinfo;
5492 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
5493 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
5494 ($content{expiration} = "$2/$1"); # where available
5496 $content{card_number} = $payinfo = $self->payinfo;
5497 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
5498 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5499 $content{expiration} = "$2/$1";
5502 } elsif ( $options{method} eq 'ECHECK' ) {
5505 $payinfo = $cust_pay->payinfo;
5507 $payinfo = $self->payinfo;
5509 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
5510 $content{bank_name} = $self->payname;
5511 $content{account_type} = 'CHECKING';
5512 $content{account_name} = $payname;
5513 $content{customer_org} = $self->company ? 'B' : 'I';
5514 $content{customer_ssn} = $self->ss;
5515 } elsif ( $options{method} eq 'LEC' ) {
5516 $content{phone} = $payinfo = $self->payinfo;
5520 my $refund = new Business::OnlinePayment( $processor, @bop_options );
5521 my %sub_content = $refund->content(
5522 'action' => 'credit',
5523 'customer_id' => $self->custnum,
5524 'last_name' => $paylast,
5525 'first_name' => $payfirst,
5527 'address' => $address,
5528 'city' => $self->city,
5529 'state' => $self->state,
5530 'zip' => $self->zip,
5531 'country' => $self->country,
5533 'phone' => $self->daytime || $self->night,
5536 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
5538 $refund->test_transaction(1)
5539 if $conf->exists('business-onlinepayment-test_transaction');
5542 return "$processor error: ". $refund->error_message
5543 unless $refund->is_success();
5545 my $paybatch = "$processor:". $refund->authorization;
5546 $paybatch .= ':'. $refund->order_number
5547 if $refund->can('order_number') && $refund->order_number;
5549 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
5550 my @cust_bill_pay = $cust_pay->cust_bill_pay;
5551 last unless @cust_bill_pay;
5552 my $cust_bill_pay = pop @cust_bill_pay;
5553 my $error = $cust_bill_pay->delete;
5557 my $cust_refund = new FS::cust_refund ( {
5558 'custnum' => $self->custnum,
5559 'paynum' => $options{'paynum'},
5560 'refund' => $amount,
5562 'payby' => $bop_method2payby{$options{method}},
5563 'payinfo' => $payinfo,
5564 'paybatch' => $paybatch,
5565 'reason' => $options{'reason'} || 'card or ACH refund',
5567 my $error = $cust_refund->insert;
5569 $cust_refund->paynum(''); #try again with no specific paynum
5570 my $error2 = $cust_refund->insert;
5572 # gah, even with transactions.
5573 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
5574 "error inserting refund ($processor): $error2".
5575 " (previously tried insert with paynum #$options{'paynum'}" .
5586 =item batch_card OPTION => VALUE...
5588 Adds a payment for this invoice to the pending credit card batch (see
5589 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
5590 runs the payment using a realtime gateway.
5595 my ($self, %options) = @_;
5598 if (exists($options{amount})) {
5599 $amount = $options{amount};
5601 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
5603 return '' unless $amount > 0;
5605 my $invnum = delete $options{invnum};
5606 my $payby = $options{invnum} || $self->payby; #dubious
5608 if ($options{'realtime'}) {
5609 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
5615 my $oldAutoCommit = $FS::UID::AutoCommit;
5616 local $FS::UID::AutoCommit = 0;
5619 #this needs to handle mysql as well as Pg, like svc_acct.pm
5620 #(make it into a common function if folks need to do batching with mysql)
5621 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
5622 or return "Cannot lock pay_batch: " . $dbh->errstr;
5626 'payby' => FS::payby->payby2payment($payby),
5629 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
5631 unless ( $pay_batch ) {
5632 $pay_batch = new FS::pay_batch \%pay_batch;
5633 my $error = $pay_batch->insert;
5635 $dbh->rollback if $oldAutoCommit;
5636 die "error creating new batch: $error\n";
5640 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
5641 'batchnum' => $pay_batch->batchnum,
5642 'custnum' => $self->custnum,
5645 foreach (qw( address1 address2 city state zip country payby payinfo paydate
5647 $options{$_} = '' unless exists($options{$_});
5650 my $cust_pay_batch = new FS::cust_pay_batch ( {
5651 'batchnum' => $pay_batch->batchnum,
5652 'invnum' => $invnum || 0, # is there a better value?
5653 # this field should be
5655 # cust_bill_pay_batch now
5656 'custnum' => $self->custnum,
5657 'last' => $self->getfield('last'),
5658 'first' => $self->getfield('first'),
5659 'address1' => $options{address1} || $self->address1,
5660 'address2' => $options{address2} || $self->address2,
5661 'city' => $options{city} || $self->city,
5662 'state' => $options{state} || $self->state,
5663 'zip' => $options{zip} || $self->zip,
5664 'country' => $options{country} || $self->country,
5665 'payby' => $options{payby} || $self->payby,
5666 'payinfo' => $options{payinfo} || $self->payinfo,
5667 'exp' => $options{paydate} || $self->paydate,
5668 'payname' => $options{payname} || $self->payname,
5669 'amount' => $amount, # consolidating
5672 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
5673 if $old_cust_pay_batch;
5676 if ($old_cust_pay_batch) {
5677 $error = $cust_pay_batch->replace($old_cust_pay_batch)
5679 $error = $cust_pay_batch->insert;
5683 $dbh->rollback if $oldAutoCommit;
5687 my $unapplied = $self->total_unapplied_credits
5688 + $self->total_unapplied_payments
5689 + $self->in_transit_payments;
5690 foreach my $cust_bill ($self->open_cust_bill) {
5691 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
5692 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
5693 'invnum' => $cust_bill->invnum,
5694 'paybatchnum' => $cust_pay_batch->paybatchnum,
5695 'amount' => $cust_bill->owed,
5698 if ($unapplied >= $cust_bill_pay_batch->amount){
5699 $unapplied -= $cust_bill_pay_batch->amount;
5702 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
5703 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
5705 $error = $cust_bill_pay_batch->insert;
5707 $dbh->rollback if $oldAutoCommit;
5712 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5716 =item apply_payments_and_credits [ OPTION => VALUE ... ]
5718 Applies unapplied payments and credits.
5720 In most cases, this new method should be used in place of sequential
5721 apply_payments and apply_credits methods.
5723 A hash of optional arguments may be passed. Currently "manual" is supported.
5724 If true, a payment receipt is sent instead of a statement when
5725 'payment_receipt_email' configuration option is set.
5727 If there is an error, returns the error, otherwise returns false.
5731 sub apply_payments_and_credits {
5732 my( $self, %options ) = @_;
5734 local $SIG{HUP} = 'IGNORE';
5735 local $SIG{INT} = 'IGNORE';
5736 local $SIG{QUIT} = 'IGNORE';
5737 local $SIG{TERM} = 'IGNORE';
5738 local $SIG{TSTP} = 'IGNORE';
5739 local $SIG{PIPE} = 'IGNORE';
5741 my $oldAutoCommit = $FS::UID::AutoCommit;
5742 local $FS::UID::AutoCommit = 0;
5745 $self->select_for_update; #mutex
5747 foreach my $cust_bill ( $self->open_cust_bill ) {
5748 my $error = $cust_bill->apply_payments_and_credits(%options);
5750 $dbh->rollback if $oldAutoCommit;
5751 return "Error applying: $error";
5755 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5760 =item apply_credits OPTION => VALUE ...
5762 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
5763 to outstanding invoice balances in chronological order (or reverse
5764 chronological order if the I<order> option is set to B<newest>) and returns the
5765 value of any remaining unapplied credits available for refund (see
5766 L<FS::cust_refund>).
5768 Dies if there is an error.
5776 local $SIG{HUP} = 'IGNORE';
5777 local $SIG{INT} = 'IGNORE';
5778 local $SIG{QUIT} = 'IGNORE';
5779 local $SIG{TERM} = 'IGNORE';
5780 local $SIG{TSTP} = 'IGNORE';
5781 local $SIG{PIPE} = 'IGNORE';
5783 my $oldAutoCommit = $FS::UID::AutoCommit;
5784 local $FS::UID::AutoCommit = 0;
5787 $self->select_for_update; #mutex
5789 unless ( $self->total_unapplied_credits ) {
5790 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5794 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
5795 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
5797 my @invoices = $self->open_cust_bill;
5798 @invoices = sort { $b->_date <=> $a->_date } @invoices
5799 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
5801 if ( $conf->exists('pkg-balances') ) {
5802 # limit @credits to those w/ a pkgnum grepped from $self
5804 foreach my $i (@invoices) {
5805 foreach my $li ( $i->cust_bill_pkg ) {
5806 $pkgnums{$li->pkgnum} = 1;
5809 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
5814 foreach my $cust_bill ( @invoices ) {
5816 if ( !defined($credit) || $credit->credited == 0) {
5817 $credit = pop @credits or last;
5821 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
5822 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
5824 $owed = $cust_bill->owed;
5826 unless ( $owed > 0 ) {
5827 push @credits, $credit;
5831 my $amount = min( $credit->credited, $owed );
5833 my $cust_credit_bill = new FS::cust_credit_bill ( {
5834 'crednum' => $credit->crednum,
5835 'invnum' => $cust_bill->invnum,
5836 'amount' => $amount,
5838 $cust_credit_bill->pkgnum( $credit->pkgnum )
5839 if $conf->exists('pkg-balances') && $credit->pkgnum;
5840 my $error = $cust_credit_bill->insert;
5842 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5846 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5850 my $total_unapplied_credits = $self->total_unapplied_credits;
5852 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5854 return $total_unapplied_credits;
5857 =item apply_payments [ OPTION => VALUE ... ]
5859 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
5860 to outstanding invoice balances in chronological order.
5862 #and returns the value of any remaining unapplied payments.
5864 A hash of optional arguments may be passed. Currently "manual" is supported.
5865 If true, a payment receipt is sent instead of a statement when
5866 'payment_receipt_email' configuration option is set.
5868 Dies if there is an error.
5872 sub apply_payments {
5873 my( $self, %options ) = @_;
5875 local $SIG{HUP} = 'IGNORE';
5876 local $SIG{INT} = 'IGNORE';
5877 local $SIG{QUIT} = 'IGNORE';
5878 local $SIG{TERM} = 'IGNORE';
5879 local $SIG{TSTP} = 'IGNORE';
5880 local $SIG{PIPE} = 'IGNORE';
5882 my $oldAutoCommit = $FS::UID::AutoCommit;
5883 local $FS::UID::AutoCommit = 0;
5886 $self->select_for_update; #mutex
5890 my @payments = sort { $b->_date <=> $a->_date }
5891 grep { $_->unapplied > 0 }
5894 my @invoices = sort { $a->_date <=> $b->_date}
5895 grep { $_->owed > 0 }
5898 if ( $conf->exists('pkg-balances') ) {
5899 # limit @payments to those w/ a pkgnum grepped from $self
5901 foreach my $i (@invoices) {
5902 foreach my $li ( $i->cust_bill_pkg ) {
5903 $pkgnums{$li->pkgnum} = 1;
5906 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
5911 foreach my $cust_bill ( @invoices ) {
5913 if ( !defined($payment) || $payment->unapplied == 0 ) {
5914 $payment = pop @payments or last;
5918 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
5919 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
5921 $owed = $cust_bill->owed;
5923 unless ( $owed > 0 ) {
5924 push @payments, $payment;
5928 my $amount = min( $payment->unapplied, $owed );
5930 my $cust_bill_pay = new FS::cust_bill_pay ( {
5931 'paynum' => $payment->paynum,
5932 'invnum' => $cust_bill->invnum,
5933 'amount' => $amount,
5935 $cust_bill_pay->pkgnum( $payment->pkgnum )
5936 if $conf->exists('pkg-balances') && $payment->pkgnum;
5937 my $error = $cust_bill_pay->insert(%options);
5939 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5943 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5947 my $total_unapplied_payments = $self->total_unapplied_payments;
5949 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5951 return $total_unapplied_payments;
5956 Returns the total owed for this customer on all invoices
5957 (see L<FS::cust_bill/owed>).
5963 $self->total_owed_date(2145859200); #12/31/2037
5966 =item total_owed_date TIME
5968 Returns the total owed for this customer on all invoices with date earlier than
5969 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
5970 see L<Time::Local> and L<Date::Parse> for conversion functions.
5974 sub total_owed_date {
5978 my $custnum = $self->custnum;
5980 my $owed_sql = FS::cust_bill->owed_sql;
5983 SELECT SUM($owed_sql) FROM cust_bill
5984 WHERE custnum = $custnum
5988 sprintf( "%.2f", $self->scalar_sql($sql) );
5992 =item total_owed_pkgnum PKGNUM
5994 Returns the total owed on all invoices for this customer's specific package
5995 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
5999 sub total_owed_pkgnum {
6000 my( $self, $pkgnum ) = @_;
6001 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
6004 =item total_owed_date_pkgnum TIME PKGNUM
6006 Returns the total owed for this customer's specific package when using
6007 experimental package balances on all invoices with date earlier than
6008 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
6009 see L<Time::Local> and L<Date::Parse> for conversion functions.
6013 sub total_owed_date_pkgnum {
6014 my( $self, $time, $pkgnum ) = @_;
6017 foreach my $cust_bill (
6018 grep { $_->_date <= $time }
6019 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6021 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
6023 sprintf( "%.2f", $total_bill );
6029 Returns the total amount of all payments.
6036 $total += $_->paid foreach $self->cust_pay;
6037 sprintf( "%.2f", $total );
6040 =item total_unapplied_credits
6042 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6043 customer. See L<FS::cust_credit/credited>.
6045 =item total_credited
6047 Old name for total_unapplied_credits. Don't use.
6051 sub total_credited {
6052 #carp "total_credited deprecated, use total_unapplied_credits";
6053 shift->total_unapplied_credits(@_);
6056 sub total_unapplied_credits {
6059 my $custnum = $self->custnum;
6061 my $unapplied_sql = FS::cust_credit->unapplied_sql;
6064 SELECT SUM($unapplied_sql) FROM cust_credit
6065 WHERE custnum = $custnum
6068 sprintf( "%.2f", $self->scalar_sql($sql) );
6072 =item total_unapplied_credits_pkgnum PKGNUM
6074 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6075 customer. See L<FS::cust_credit/credited>.
6079 sub total_unapplied_credits_pkgnum {
6080 my( $self, $pkgnum ) = @_;
6081 my $total_credit = 0;
6082 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
6083 sprintf( "%.2f", $total_credit );
6087 =item total_unapplied_payments
6089 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
6090 See L<FS::cust_pay/unapplied>.
6094 sub total_unapplied_payments {
6097 my $custnum = $self->custnum;
6099 my $unapplied_sql = FS::cust_pay->unapplied_sql;
6102 SELECT SUM($unapplied_sql) FROM cust_pay
6103 WHERE custnum = $custnum
6106 sprintf( "%.2f", $self->scalar_sql($sql) );
6110 =item total_unapplied_payments_pkgnum PKGNUM
6112 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
6113 specific package when using experimental package balances. See
6114 L<FS::cust_pay/unapplied>.
6118 sub total_unapplied_payments_pkgnum {
6119 my( $self, $pkgnum ) = @_;
6120 my $total_unapplied = 0;
6121 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
6122 sprintf( "%.2f", $total_unapplied );
6126 =item total_unapplied_refunds
6128 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
6129 customer. See L<FS::cust_refund/unapplied>.
6133 sub total_unapplied_refunds {
6135 my $custnum = $self->custnum;
6137 my $unapplied_sql = FS::cust_refund->unapplied_sql;
6140 SELECT SUM($unapplied_sql) FROM cust_refund
6141 WHERE custnum = $custnum
6144 sprintf( "%.2f", $self->scalar_sql($sql) );
6150 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6151 total_unapplied_credits minus total_unapplied_payments).
6157 $self->balance_date_range;
6160 =item balance_date TIME
6162 Returns the balance for this customer, only considering invoices with date
6163 earlier than TIME (total_owed_date minus total_credited minus
6164 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
6165 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
6172 $self->balance_date_range(shift);
6175 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
6177 Returns the balance for this customer, optionally considering invoices with
6178 date earlier than START_TIME, and not later than END_TIME
6179 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
6181 Times are specified as SQL fragments or numeric
6182 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
6183 L<Date::Parse> for conversion functions. The empty string can be passed
6184 to disable that time constraint completely.
6186 Available options are:
6190 =item unapplied_date
6192 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)
6198 sub balance_date_range {
6200 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
6201 ') FROM cust_main WHERE custnum='. $self->custnum;
6202 sprintf( "%.2f", $self->scalar_sql($sql) );
6205 =item balance_pkgnum PKGNUM
6207 Returns the balance for this customer's specific package when using
6208 experimental package balances (total_owed plus total_unrefunded, minus
6209 total_unapplied_credits minus total_unapplied_payments)
6213 sub balance_pkgnum {
6214 my( $self, $pkgnum ) = @_;
6217 $self->total_owed_pkgnum($pkgnum)
6218 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6219 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
6220 - $self->total_unapplied_credits_pkgnum($pkgnum)
6221 - $self->total_unapplied_payments_pkgnum($pkgnum)
6225 =item in_transit_payments
6227 Returns the total of requests for payments for this customer pending in
6228 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
6232 sub in_transit_payments {
6234 my $in_transit_payments = 0;
6235 foreach my $pay_batch ( qsearch('pay_batch', {
6238 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6239 'batchnum' => $pay_batch->batchnum,
6240 'custnum' => $self->custnum,
6242 $in_transit_payments += $cust_pay_batch->amount;
6245 sprintf( "%.2f", $in_transit_payments );
6250 Returns a hash of useful information for making a payment.
6260 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6261 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6262 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6266 For credit card transactions:
6278 For electronic check transactions:
6293 $return{balance} = $self->balance;
6295 $return{payname} = $self->payname
6296 || ( $self->first. ' '. $self->get('last') );
6298 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6300 $return{payby} = $self->payby;
6301 $return{stateid_state} = $self->stateid_state;
6303 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6304 $return{card_type} = cardtype($self->payinfo);
6305 $return{payinfo} = $self->paymask;
6307 @return{'month', 'year'} = $self->paydate_monthyear;
6311 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6312 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6313 $return{payinfo1} = $payinfo1;
6314 $return{payinfo2} = $payinfo2;
6315 $return{paytype} = $self->paytype;
6316 $return{paystate} = $self->paystate;
6320 #doubleclick protection
6322 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6328 =item paydate_monthyear
6330 Returns a two-element list consisting of the month and year of this customer's
6331 paydate (credit card expiration date for CARD customers)
6335 sub paydate_monthyear {
6337 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6339 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6346 =item tax_exemption TAXNAME
6351 my( $self, $taxname ) = @_;
6353 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6354 'taxname' => $taxname,
6359 =item cust_main_exemption
6363 sub cust_main_exemption {
6365 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6368 =item invoicing_list [ ARRAYREF ]
6370 If an arguement is given, sets these email addresses as invoice recipients
6371 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
6372 (except as warnings), so use check_invoicing_list first.
6374 Returns a list of email addresses (with svcnum entries expanded).
6376 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
6377 check it without disturbing anything by passing nothing.
6379 This interface may change in the future.
6383 sub invoicing_list {
6384 my( $self, $arrayref ) = @_;
6387 my @cust_main_invoice;
6388 if ( $self->custnum ) {
6389 @cust_main_invoice =
6390 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6392 @cust_main_invoice = ();
6394 foreach my $cust_main_invoice ( @cust_main_invoice ) {
6395 #warn $cust_main_invoice->destnum;
6396 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6397 #warn $cust_main_invoice->destnum;
6398 my $error = $cust_main_invoice->delete;
6399 warn $error if $error;
6402 if ( $self->custnum ) {
6403 @cust_main_invoice =
6404 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6406 @cust_main_invoice = ();
6408 my %seen = map { $_->address => 1 } @cust_main_invoice;
6409 foreach my $address ( @{$arrayref} ) {
6410 next if exists $seen{$address} && $seen{$address};
6411 $seen{$address} = 1;
6412 my $cust_main_invoice = new FS::cust_main_invoice ( {
6413 'custnum' => $self->custnum,
6416 my $error = $cust_main_invoice->insert;
6417 warn $error if $error;
6421 if ( $self->custnum ) {
6423 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6430 =item check_invoicing_list ARRAYREF
6432 Checks these arguements as valid input for the invoicing_list method. If there
6433 is an error, returns the error, otherwise returns false.
6437 sub check_invoicing_list {
6438 my( $self, $arrayref ) = @_;
6440 foreach my $address ( @$arrayref ) {
6442 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6443 return 'Can\'t add FAX invoice destination with a blank FAX number.';
6446 my $cust_main_invoice = new FS::cust_main_invoice ( {
6447 'custnum' => $self->custnum,
6450 my $error = $self->custnum
6451 ? $cust_main_invoice->check
6452 : $cust_main_invoice->checkdest
6454 return $error if $error;
6458 return "Email address required"
6459 if $conf->exists('cust_main-require_invoicing_list_email')
6460 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6465 =item set_default_invoicing_list
6467 Sets the invoicing list to all accounts associated with this customer,
6468 overwriting any previous invoicing list.
6472 sub set_default_invoicing_list {
6474 $self->invoicing_list($self->all_emails);
6479 Returns the email addresses of all accounts provisioned for this customer.
6486 foreach my $cust_pkg ( $self->all_pkgs ) {
6487 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6489 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6490 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6492 $list{$_}=1 foreach map { $_->email } @svc_acct;
6497 =item invoicing_list_addpost
6499 Adds postal invoicing to this customer. If this customer is already configured
6500 to receive postal invoices, does nothing.
6504 sub invoicing_list_addpost {
6506 return if grep { $_ eq 'POST' } $self->invoicing_list;
6507 my @invoicing_list = $self->invoicing_list;
6508 push @invoicing_list, 'POST';
6509 $self->invoicing_list(\@invoicing_list);
6512 =item invoicing_list_emailonly
6514 Returns the list of email invoice recipients (invoicing_list without non-email
6515 destinations such as POST and FAX).
6519 sub invoicing_list_emailonly {
6521 warn "$me invoicing_list_emailonly called"
6523 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
6526 =item invoicing_list_emailonly_scalar
6528 Returns the list of email invoice recipients (invoicing_list without non-email
6529 destinations such as POST and FAX) as a comma-separated scalar.
6533 sub invoicing_list_emailonly_scalar {
6535 warn "$me invoicing_list_emailonly_scalar called"
6537 join(', ', $self->invoicing_list_emailonly);
6540 =item referral_custnum_cust_main
6542 Returns the customer who referred this customer (or the empty string, if
6543 this customer was not referred).
6545 Note the difference with referral_cust_main method: This method,
6546 referral_custnum_cust_main returns the single customer (if any) who referred
6547 this customer, while referral_cust_main returns an array of customers referred
6552 sub referral_custnum_cust_main {
6554 return '' unless $self->referral_custnum;
6555 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6558 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
6560 Returns an array of customers referred by this customer (referral_custnum set
6561 to this custnum). If DEPTH is given, recurses up to the given depth, returning
6562 customers referred by customers referred by this customer and so on, inclusive.
6563 The default behavior is DEPTH 1 (no recursion).
6565 Note the difference with referral_custnum_cust_main method: This method,
6566 referral_cust_main, returns an array of customers referred BY this customer,
6567 while referral_custnum_cust_main returns the single customer (if any) who
6568 referred this customer.
6572 sub referral_cust_main {
6574 my $depth = @_ ? shift : 1;
6575 my $exclude = @_ ? shift : {};
6578 map { $exclude->{$_->custnum}++; $_; }
6579 grep { ! $exclude->{ $_->custnum } }
6580 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
6584 map { $_->referral_cust_main($depth-1, $exclude) }
6591 =item referral_cust_main_ncancelled
6593 Same as referral_cust_main, except only returns customers with uncancelled
6598 sub referral_cust_main_ncancelled {
6600 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
6603 =item referral_cust_pkg [ DEPTH ]
6605 Like referral_cust_main, except returns a flat list of all unsuspended (and
6606 uncancelled) packages for each customer. The number of items in this list may
6607 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
6611 sub referral_cust_pkg {
6613 my $depth = @_ ? shift : 1;
6615 map { $_->unsuspended_pkgs }
6616 grep { $_->unsuspended_pkgs }
6617 $self->referral_cust_main($depth);
6620 =item referring_cust_main
6622 Returns the single cust_main record for the customer who referred this customer
6623 (referral_custnum), or false.
6627 sub referring_cust_main {
6629 return '' unless $self->referral_custnum;
6630 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6633 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
6635 Applies a credit to this customer. If there is an error, returns the error,
6636 otherwise returns false.
6638 REASON can be a text string, an FS::reason object, or a scalar reference to
6639 a reasonnum. If a text string, it will be automatically inserted as a new
6640 reason, and a 'reason_type' option must be passed to indicate the
6641 FS::reason_type for the new reason.
6643 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
6645 Any other options are passed to FS::cust_credit::insert.
6650 my( $self, $amount, $reason, %options ) = @_;
6652 my $cust_credit = new FS::cust_credit {
6653 'custnum' => $self->custnum,
6654 'amount' => $amount,
6657 if ( ref($reason) ) {
6659 if ( ref($reason) eq 'SCALAR' ) {
6660 $cust_credit->reasonnum( $$reason );
6662 $cust_credit->reasonnum( $reason->reasonnum );
6666 $cust_credit->set('reason', $reason)
6669 for (qw( addlinfo eventnum )) {
6670 $cust_credit->$_( delete $options{$_} )
6671 if exists($options{$_});
6674 $cust_credit->insert(%options);
6678 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
6680 Creates a one-time charge for this customer. If there is an error, returns
6681 the error, otherwise returns false.
6683 New-style, with a hashref of options:
6685 my $error = $cust_main->charge(
6689 'start_date' => str2time('7/4/2009'),
6690 'pkg' => 'Description',
6691 'comment' => 'Comment',
6692 'additional' => [], #extra invoice detail
6693 'classnum' => 1, #pkg_class
6695 'setuptax' => '', # or 'Y' for tax exempt
6698 'taxclass' => 'Tax class',
6701 'taxproduct' => 2, #part_pkg_taxproduct
6702 'override' => {}, #XXX describe
6704 #will be filled in with the new object
6705 'cust_pkg_ref' => \$cust_pkg,
6707 #generate an invoice immediately
6709 'invoice_terms' => '', #with these terms
6715 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
6721 my ( $amount, $quantity, $start_date, $classnum );
6722 my ( $pkg, $comment, $additional );
6723 my ( $setuptax, $taxclass ); #internal taxes
6724 my ( $taxproduct, $override ); #vendor (CCH) taxes
6726 my $cust_pkg_ref = '';
6727 my ( $bill_now, $invoice_terms ) = ( 0, '' );
6728 if ( ref( $_[0] ) ) {
6729 $amount = $_[0]->{amount};
6730 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
6731 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
6732 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
6733 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
6734 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
6735 : '$'. sprintf("%.2f",$amount);
6736 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
6737 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
6738 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
6739 $additional = $_[0]->{additional} || [];
6740 $taxproduct = $_[0]->{taxproductnum};
6741 $override = { '' => $_[0]->{tax_override} };
6742 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
6743 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
6744 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
6749 $pkg = @_ ? shift : 'One-time charge';
6750 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
6752 $taxclass = @_ ? shift : '';
6756 local $SIG{HUP} = 'IGNORE';
6757 local $SIG{INT} = 'IGNORE';
6758 local $SIG{QUIT} = 'IGNORE';
6759 local $SIG{TERM} = 'IGNORE';
6760 local $SIG{TSTP} = 'IGNORE';
6761 local $SIG{PIPE} = 'IGNORE';
6763 my $oldAutoCommit = $FS::UID::AutoCommit;
6764 local $FS::UID::AutoCommit = 0;
6767 my $part_pkg = new FS::part_pkg ( {
6769 'comment' => $comment,
6773 'classnum' => ( $classnum ? $classnum : '' ),
6774 'setuptax' => $setuptax,
6775 'taxclass' => $taxclass,
6776 'taxproductnum' => $taxproduct,
6779 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
6780 ( 0 .. @$additional - 1 )
6782 'additional_count' => scalar(@$additional),
6783 'setup_fee' => $amount,
6786 my $error = $part_pkg->insert( options => \%options,
6787 tax_overrides => $override,
6790 $dbh->rollback if $oldAutoCommit;
6794 my $pkgpart = $part_pkg->pkgpart;
6795 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
6796 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
6797 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
6798 $error = $type_pkgs->insert;
6800 $dbh->rollback if $oldAutoCommit;
6805 my $cust_pkg = new FS::cust_pkg ( {
6806 'custnum' => $self->custnum,
6807 'pkgpart' => $pkgpart,
6808 'quantity' => $quantity,
6809 'start_date' => $start_date,
6810 'no_auto' => $no_auto,
6813 $error = $cust_pkg->insert;
6815 $dbh->rollback if $oldAutoCommit;
6817 } elsif ( $cust_pkg_ref ) {
6818 ${$cust_pkg_ref} = $cust_pkg;
6822 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
6823 'pkg_list' => [ $cust_pkg ],
6826 $dbh->rollback if $oldAutoCommit;
6831 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6836 #=item charge_postal_fee
6838 #Applies a one time charge this customer. If there is an error,
6839 #returns the error, returns the cust_pkg charge object or false
6840 #if there was no charge.
6844 # This should be a customer event. For that to work requires that bill
6845 # also be a customer event.
6847 sub charge_postal_fee {
6850 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
6851 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
6853 my $cust_pkg = new FS::cust_pkg ( {
6854 'custnum' => $self->custnum,
6855 'pkgpart' => $pkgpart,
6859 my $error = $cust_pkg->insert;
6860 $error ? $error : $cust_pkg;
6865 Returns all the invoices (see L<FS::cust_bill>) for this customer.
6871 map { $_ } #return $self->num_cust_bill unless wantarray;
6872 sort { $a->_date <=> $b->_date }
6873 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6876 =item open_cust_bill
6878 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
6883 sub open_cust_bill {
6887 'table' => 'cust_bill',
6888 'hashref' => { 'custnum' => $self->custnum, },
6889 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
6890 'order_by' => 'ORDER BY _date ASC',
6895 =item cust_statements
6897 Returns all the statements (see L<FS::cust_statement>) for this customer.
6901 sub cust_statement {
6903 map { $_ } #return $self->num_cust_statement unless wantarray;
6904 sort { $a->_date <=> $b->_date }
6905 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
6910 Returns all the credits (see L<FS::cust_credit>) for this customer.
6916 map { $_ } #return $self->num_cust_credit unless wantarray;
6917 sort { $a->_date <=> $b->_date }
6918 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
6921 =item cust_credit_pkgnum
6923 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
6924 package when using experimental package balances.
6928 sub cust_credit_pkgnum {
6929 my( $self, $pkgnum ) = @_;
6930 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
6931 sort { $a->_date <=> $b->_date }
6932 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
6933 'pkgnum' => $pkgnum,
6940 Returns all the payments (see L<FS::cust_pay>) for this customer.
6946 return $self->num_cust_pay unless wantarray;
6947 sort { $a->_date <=> $b->_date }
6948 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
6953 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
6954 called automatically when the cust_pay method is used in a scalar context.
6960 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
6961 my $sth = dbh->prepare($sql) or die dbh->errstr;
6962 $sth->execute($self->custnum) or die $sth->errstr;
6963 $sth->fetchrow_arrayref->[0];
6966 =item cust_pay_pkgnum
6968 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
6969 package when using experimental package balances.
6973 sub cust_pay_pkgnum {
6974 my( $self, $pkgnum ) = @_;
6975 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
6976 sort { $a->_date <=> $b->_date }
6977 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
6978 'pkgnum' => $pkgnum,
6985 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
6991 map { $_ } #return $self->num_cust_pay_void unless wantarray;
6992 sort { $a->_date <=> $b->_date }
6993 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
6996 =item cust_pay_batch
6998 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
7002 sub cust_pay_batch {
7004 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
7005 sort { $a->paybatchnum <=> $b->paybatchnum }
7006 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
7009 =item cust_pay_pending
7011 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
7012 (without status "done").
7016 sub cust_pay_pending {
7018 return $self->num_cust_pay_pending unless wantarray;
7019 sort { $a->_date <=> $b->_date }
7020 qsearch( 'cust_pay_pending', {
7021 'custnum' => $self->custnum,
7022 'status' => { op=>'!=', value=>'done' },
7027 =item num_cust_pay_pending
7029 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7030 customer (without status "done"). Also called automatically when the
7031 cust_pay_pending method is used in a scalar context.
7035 sub num_cust_pay_pending {
7037 my $sql = " SELECT COUNT(*) FROM cust_pay_pending ".
7038 " WHERE custnum = ? AND status != 'done' ";
7039 my $sth = dbh->prepare($sql) or die dbh->errstr;
7040 $sth->execute($self->custnum) or die $sth->errstr;
7041 $sth->fetchrow_arrayref->[0];
7046 Returns all the refunds (see L<FS::cust_refund>) for this customer.
7052 map { $_ } #return $self->num_cust_refund unless wantarray;
7053 sort { $a->_date <=> $b->_date }
7054 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
7057 =item display_custnum
7059 Returns the displayed customer number for this customer: agent_custid if
7060 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
7064 sub display_custnum {
7066 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
7067 return $self->agent_custid;
7069 return $self->custnum;
7075 Returns a name string for this customer, either "Company (Last, First)" or
7082 my $name = $self->contact;
7083 $name = $self->company. " ($name)" if $self->company;
7089 Returns a name string for this (service/shipping) contact, either
7090 "Company (Last, First)" or "Last, First".
7096 if ( $self->get('ship_last') ) {
7097 my $name = $self->ship_contact;
7098 $name = $self->ship_company. " ($name)" if $self->ship_company;
7107 Returns a name string for this customer, either "Company" or "First Last".
7113 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
7116 =item ship_name_short
7118 Returns a name string for this (service/shipping) contact, either "Company"
7123 sub ship_name_short {
7125 if ( $self->get('ship_last') ) {
7126 $self->ship_company !~ /^\s*$/
7127 ? $self->ship_company
7128 : $self->ship_contact_firstlast;
7130 $self->name_company_or_firstlast;
7136 Returns this customer's full (billing) contact name only, "Last, First"
7142 $self->get('last'). ', '. $self->first;
7147 Returns this customer's full (shipping) contact name only, "Last, First"
7153 $self->get('ship_last')
7154 ? $self->get('ship_last'). ', '. $self->ship_first
7158 =item contact_firstlast
7160 Returns this customers full (billing) contact name only, "First Last".
7164 sub contact_firstlast {
7166 $self->first. ' '. $self->get('last');
7169 =item ship_contact_firstlast
7171 Returns this customer's full (shipping) contact name only, "First Last".
7175 sub ship_contact_firstlast {
7177 $self->get('ship_last')
7178 ? $self->first. ' '. $self->get('ship_last')
7179 : $self->contact_firstlast;
7184 Returns this customer's full country name
7190 code2country($self->country);
7193 =item geocode DATA_VENDOR
7195 Returns a value for the customer location as encoded by DATA_VENDOR.
7196 Currently this only makes sense for "CCH" as DATA_VENDOR.
7201 my ($self, $data_vendor) = (shift, shift); #always cch for now
7203 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
7204 return $geocode if $geocode;
7206 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7210 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7211 if $self->country eq 'US';
7215 #CCH specific location stuff
7216 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7218 my @cust_tax_location =
7220 'table' => 'cust_tax_location',
7221 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7222 'extra_sql' => $extra_sql,
7223 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
7226 $geocode = $cust_tax_location[0]->geocode
7227 if scalar(@cust_tax_location);
7236 Returns a status string for this customer, currently:
7240 =item prospect - No packages have ever been ordered
7242 =item ordered - Recurring packages all are new (not yet billed).
7244 =item active - One or more recurring packages is active
7246 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7248 =item suspended - All non-cancelled recurring packages are suspended
7250 =item cancelled - All recurring packages are cancelled
7256 sub status { shift->cust_status(@_); }
7260 # prospect ordered active inactive suspended cancelled
7261 for my $status ( FS::cust_main->statuses() ) {
7262 my $method = $status.'_sql';
7263 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7264 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7265 $sth->execute( ($self->custnum) x $numnum )
7266 or die "Error executing 'SELECT $sql': ". $sth->errstr;
7267 return $status if $sth->fetchrow_arrayref->[0];
7271 =item ucfirst_cust_status
7273 =item ucfirst_status
7275 Returns the status with the first character capitalized.
7279 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7281 sub ucfirst_cust_status {
7283 ucfirst($self->cust_status);
7288 Returns a hex triplet color string for this customer's status.
7292 use vars qw(%statuscolor);
7293 tie %statuscolor, 'Tie::IxHash',
7294 'prospect' => '7e0079', #'000000', #black? naw, purple
7295 'active' => '00CC00', #green
7296 'ordered' => '009999', #teal? cyan?
7297 'inactive' => '0000CC', #blue
7298 'suspended' => 'FF9900', #yellow
7299 'cancelled' => 'FF0000', #red
7302 sub statuscolor { shift->cust_statuscolor(@_); }
7304 sub cust_statuscolor {
7306 $statuscolor{$self->cust_status};
7311 Returns an array of hashes representing the customer's RT tickets.
7318 my $num = $conf->config('cust_main-max_tickets') || 10;
7321 if ( $conf->config('ticket_system') ) {
7322 unless ( $conf->config('ticket_system-custom_priority_field') ) {
7324 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7328 foreach my $priority (
7329 $conf->config('ticket_system-custom_priority_field-values'), ''
7331 last if scalar(@tickets) >= $num;
7333 @{ FS::TicketSystem->customer_tickets( $self->custnum,
7334 $num - scalar(@tickets),
7344 # Return services representing svc_accts in customer support packages
7345 sub support_services {
7347 my %packages = map { $_ => 1 } $conf->config('support_packages');
7349 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7350 grep { $_->part_svc->svcdb eq 'svc_acct' }
7351 map { $_->cust_svc }
7352 grep { exists $packages{ $_->pkgpart } }
7353 $self->ncancelled_pkgs;
7357 # Return a list of latitude/longitude for one of the services (if any)
7358 sub service_coordinates {
7362 grep { $_->latitude && $_->longitude }
7364 map { $_->cust_svc }
7365 $self->ncancelled_pkgs;
7367 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7372 =head1 CLASS METHODS
7378 Class method that returns the list of possible status strings for customers
7379 (see L<the status method|/status>). For example:
7381 @statuses = FS::cust_main->statuses();
7386 #my $self = shift; #could be class...
7392 Returns an SQL expression identifying prospective cust_main records (customers
7393 with no packages ever ordered)
7397 use vars qw($select_count_pkgs);
7398 $select_count_pkgs =
7399 "SELECT COUNT(*) FROM cust_pkg
7400 WHERE cust_pkg.custnum = cust_main.custnum";
7402 sub select_count_pkgs_sql {
7407 " 0 = ( $select_count_pkgs ) ";
7412 Returns an SQL expression identifying ordered cust_main records (customers with
7413 recurring packages not yet setup).
7418 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
7423 Returns an SQL expression identifying active cust_main records (customers with
7424 active recurring packages).
7429 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7434 Returns an SQL expression identifying inactive cust_main records (customers with
7435 no active recurring packages, but otherwise unsuspended/uncancelled).
7439 sub inactive_sql { "
7440 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7442 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7448 Returns an SQL expression identifying suspended cust_main records.
7453 sub suspended_sql { susp_sql(@_); }
7455 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
7457 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7463 Returns an SQL expression identifying cancelled cust_main records.
7467 sub cancelled_sql { cancel_sql(@_); }
7470 my $recurring_sql = FS::cust_pkg->recurring_sql;
7471 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7474 0 < ( $select_count_pkgs )
7475 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
7476 AND 0 = ( $select_count_pkgs AND $recurring_sql
7477 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7479 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7485 =item uncancelled_sql
7487 Returns an SQL expression identifying un-cancelled cust_main records.
7491 sub uncancelled_sql { uncancel_sql(@_); }
7492 sub uncancel_sql { "
7493 ( 0 < ( $select_count_pkgs
7494 AND ( cust_pkg.cancel IS NULL
7495 OR cust_pkg.cancel = 0
7498 OR 0 = ( $select_count_pkgs )
7504 Returns an SQL fragment to retreive the balance.
7509 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7510 WHERE cust_bill.custnum = cust_main.custnum )
7511 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
7512 WHERE cust_pay.custnum = cust_main.custnum )
7513 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
7514 WHERE cust_credit.custnum = cust_main.custnum )
7515 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
7516 WHERE cust_refund.custnum = cust_main.custnum )
7519 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
7521 Returns an SQL fragment to retreive the balance for this customer, optionally
7522 considering invoices with date earlier than START_TIME, and not
7523 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7524 total_unapplied_payments).
7526 Times are specified as SQL fragments or numeric
7527 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7528 L<Date::Parse> for conversion functions. The empty string can be passed
7529 to disable that time constraint completely.
7531 Available options are:
7535 =item unapplied_date
7537 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)
7542 set to true to remove all customer comparison clauses, for totals
7547 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
7552 JOIN clause (typically used with the total option)
7556 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
7557 time will be ignored. Note that START_TIME and END_TIME only limit the date
7558 range for invoices and I<unapplied> payments, credits, and refunds.
7564 sub balance_date_sql {
7565 my( $class, $start, $end, %opt ) = @_;
7567 my $cutoff = $opt{'cutoff'};
7569 my $owed = FS::cust_bill->owed_sql($cutoff);
7570 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
7571 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
7572 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7574 my $j = $opt{'join'} || '';
7576 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
7577 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
7578 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
7579 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
7581 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
7582 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
7583 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
7584 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
7589 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
7591 Returns an SQL fragment to retreive the total unapplied payments for this
7592 customer, only considering invoices with date earlier than START_TIME, and
7593 optionally not later than END_TIME.
7595 Times are specified as SQL fragments or numeric
7596 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7597 L<Date::Parse> for conversion functions. The empty string can be passed
7598 to disable that time constraint completely.
7600 Available options are:
7604 sub unapplied_payments_date_sql {
7605 my( $class, $start, $end, %opt ) = @_;
7607 my $cutoff = $opt{'cutoff'};
7609 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7611 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
7612 'unapplied_date'=>1 );
7614 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
7617 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7619 Helper method for balance_date_sql; name (and usage) subject to change
7620 (suggestions welcome).
7622 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
7623 cust_refund, cust_credit or cust_pay).
7625 If TABLE is "cust_bill" or the unapplied_date option is true, only
7626 considers records with date earlier than START_TIME, and optionally not
7627 later than END_TIME .
7631 sub _money_table_where {
7632 my( $class, $table, $start, $end, %opt ) = @_;
7635 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
7636 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
7637 push @where, "$table._date <= $start" if defined($start) && length($start);
7638 push @where, "$table._date > $end" if defined($end) && length($end);
7640 push @where, @{$opt{'where'}} if $opt{'where'};
7641 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
7647 =item search HASHREF
7651 Returns a qsearch hash expression to search for parameters specified in
7652 HASHREF. Valid parameters are
7660 =item cancelled_pkgs
7666 listref of start date, end date
7676 =item current_balance
7678 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
7682 =item flattened_pkgs
7691 my ($class, $params) = @_;
7702 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
7704 "cust_main.agentnum = $1";
7708 # do the same for user
7711 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
7713 "cust_main.usernum = $1";
7720 #prospect ordered active inactive suspended cancelled
7721 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
7722 my $method = $params->{'status'}. '_sql';
7723 #push @where, $class->$method();
7724 push @where, FS::cust_main->$method();
7728 # parse cancelled package checkbox
7733 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
7734 unless $params->{'cancelled_pkgs'};
7737 # parse without census tract checkbox
7740 push @where, "(censustract = '' or censustract is null)"
7741 if $params->{'no_censustract'};
7747 foreach my $field (qw( signupdate )) {
7749 next unless exists($params->{$field});
7751 my($beginning, $ending, $hour) = @{$params->{$field}};
7754 "cust_main.$field IS NOT NULL",
7755 "cust_main.$field >= $beginning",
7756 "cust_main.$field <= $ending";
7758 # XXX: do this for mysql and/or pull it out of here
7760 if ($dbh->{Driver}->{Name} eq 'Pg') {
7761 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
7764 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
7768 $orderby ||= "ORDER BY cust_main.$field";
7776 if ( $params->{'classnum'} ) {
7778 my @classnum = ref( $params->{'classnum'} )
7779 ? @{ $params->{'classnum'} }
7780 : ( $params->{'classnum'} );
7782 @classnum = grep /^(\d*)$/, @classnum;
7785 push @where, '( '. join(' OR ', map {
7786 $_ ? "cust_main.classnum = $_"
7787 : "cust_main.classnum IS NULL"
7800 if ( $params->{'payby'} ) {
7802 my @payby = ref( $params->{'payby'} )
7803 ? @{ $params->{'payby'} }
7804 : ( $params->{'payby'} );
7806 @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
7808 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
7814 # paydate_year / paydate_month
7817 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
7819 $params->{'paydate_month'} =~ /^(\d\d?)$/
7820 or die "paydate_year without paydate_month?";
7824 'paydate IS NOT NULL',
7826 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
7834 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
7836 if ( $1 eq 'NULL' ) {
7838 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
7841 "cust_main.invoice_terms IS NOT NULL",
7842 "cust_main.invoice_terms = '$1'";
7850 if ( $params->{'current_balance'} ) {
7852 #my $balance_sql = $class->balance_sql();
7853 my $balance_sql = FS::cust_main->balance_sql();
7855 my @current_balance =
7856 ref( $params->{'current_balance'} )
7857 ? @{ $params->{'current_balance'} }
7858 : ( $params->{'current_balance'} );
7860 push @where, map { s/current_balance/$balance_sql/; $_ }
7869 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
7871 "cust_main.custbatch = '$1'";
7875 # setup queries, subs, etc. for the search
7878 $orderby ||= 'ORDER BY custnum';
7880 # here is the agent virtualization
7881 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
7883 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
7885 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
7887 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
7889 my $select = join(', ',
7890 'cust_main.custnum',
7891 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
7894 my(@extra_headers) = ();
7895 my(@extra_fields) = ();
7897 if ($params->{'flattened_pkgs'}) {
7899 if ($dbh->{Driver}->{Name} eq 'Pg') {
7901 $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";
7903 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
7904 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
7905 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
7907 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
7908 "omitting packing information from report.";
7911 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";
7913 my $sth = dbh->prepare($header_query) or die dbh->errstr;
7914 $sth->execute() or die $sth->errstr;
7915 my $headerrow = $sth->fetchrow_arrayref;
7916 my $headercount = $headerrow ? $headerrow->[0] : 0;
7917 while($headercount) {
7918 unshift @extra_headers, "Package ". $headercount;
7919 unshift @extra_fields, eval q!sub {my $c = shift;
7920 my @a = split '\|', $c->magic;
7921 my $p = $a[!.--$headercount. q!];
7929 'table' => 'cust_main',
7930 'select' => $select,
7932 'extra_sql' => $extra_sql,
7933 'order_by' => $orderby,
7934 'count_query' => $count_query,
7935 'extra_headers' => \@extra_headers,
7936 'extra_fields' => \@extra_fields,
7941 =item email_search_result HASHREF
7945 Emails a notice to the specified customers.
7947 Valid parameters are those of the L<search> method, plus the following:
7969 Optional job queue job for status updates.
7973 Returns an error message, or false for success.
7975 If an error occurs during any email, stops the enture send and returns that
7976 error. Presumably if you're getting SMTP errors aborting is better than
7977 retrying everything.
7981 sub email_search_result {
7982 my($class, $params) = @_;
7984 my $from = delete $params->{from};
7985 my $subject = delete $params->{subject};
7986 my $html_body = delete $params->{html_body};
7987 my $text_body = delete $params->{text_body};
7990 my $job = delete $params->{'job'}
7991 or die "email_search_result must run from the job queue.\n";
7993 $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
7994 unless ref($params->{'payby'});
7996 my $sql_query = $class->search($params);
7998 my $count_query = delete($sql_query->{'count_query'});
7999 my $count_sth = dbh->prepare($count_query)
8000 or die "Error preparing $count_query: ". dbh->errstr;
8002 or die "Error executing $count_query: ". $count_sth->errstr;
8003 my $count_arrayref = $count_sth->fetchrow_arrayref;
8004 my $num_cust = $count_arrayref->[0];
8006 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
8007 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
8010 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
8011 my @retry_jobs = ();
8014 #eventually order+limit magic to reduce memory use?
8015 foreach my $cust_main ( qsearch($sql_query) ) {
8017 #progressbar first, so that the count is right
8019 if ( time - $min_sec > $last ) {
8020 my $error = $job->update_statustext(
8021 int( 100 * $num / $num_cust )
8023 die $error if $error;
8027 my $to = $cust_main->invoicing_list_emailonly_scalar;
8033 'subject' => $subject,
8034 'html_body' => $html_body,
8035 'text_body' => $text_body,
8038 $error = send_email( generate_email( @message ) );
8041 # queue the sending of this message so that the user can see what we
8042 # tried to do, and retry if desired
8043 my $queue = new FS::queue {
8044 'job' => 'FS::Misc::process_send_email',
8045 'custnum' => $cust_main->custnum,
8046 'status' => 'failed',
8047 'statustext' => $error,
8049 $queue->insert(@message);
8050 push @retry_jobs, $queue;
8057 if($success == 0 and
8058 (scalar(@retry_jobs) > 10 or $num == $num_cust)
8060 # 10 is arbitrary, but if we have enough failures, that's
8061 # probably a configuration or network problem, and we
8062 # abort the batch and run away screaming.
8063 # We NEVER do this if anything was successfully sent.
8064 $_->delete foreach (@retry_jobs);
8065 return "multiple failures: '$error'\n";
8070 # fail the job, but with a status message that makes it clear
8071 # something was sent.
8072 return "Sent $success, failed ".scalar(@retry_jobs).". Failed attempts placed in job queue.\n";
8078 sub process_email_search_result {
8080 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
8082 my $param = thaw(decode_base64(shift));
8083 warn Dumper($param) if $DEBUG;
8085 $param->{'job'} = $job;
8087 $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
8088 unless ref($param->{'payby'});
8090 my $error = FS::cust_main->email_search_result( $param );
8091 die $error if $error;
8095 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
8097 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
8098 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
8099 specified (the appropriate ship_ field is also searched).
8101 Additional options are the same as FS::Record::qsearch
8106 my( $self, $fuzzy, $hash, @opt) = @_;
8111 check_and_rebuild_fuzzyfiles();
8112 foreach my $field ( keys %$fuzzy ) {
8114 my $all = $self->all_X($field);
8115 next unless scalar(@$all);
8118 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
8121 foreach ( keys %match ) {
8122 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
8123 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
8126 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
8129 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
8131 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
8139 Returns a masked version of the named field
8144 my ($self,$field) = @_;
8148 'x'x(length($self->getfield($field))-4).
8149 substr($self->getfield($field), (length($self->getfield($field))-4));
8159 =item smart_search OPTION => VALUE ...
8161 Accepts the following options: I<search>, the string to search for. The string
8162 will be searched for as a customer number, phone number, name or company name,
8163 as an exact, or, in some cases, a substring or fuzzy match (see the source code
8164 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
8165 skip fuzzy matching when an exact match is found.
8167 Any additional options are treated as an additional qualifier on the search
8170 Returns a (possibly empty) array of FS::cust_main objects.
8177 #here is the agent virtualization
8178 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8182 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
8183 my $search = delete $options{'search'};
8184 ( my $alphanum_search = $search ) =~ s/\W//g;
8186 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8188 #false laziness w/Record::ut_phone
8189 my $phonen = "$1-$2-$3";
8190 $phonen .= " x$4" if $4;
8192 push @cust_main, qsearch( {
8193 'table' => 'cust_main',
8194 'hashref' => { %options },
8195 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8197 join(' OR ', map "$_ = '$phonen'",
8198 qw( daytime night fax
8199 ship_daytime ship_night ship_fax )
8202 " AND $agentnums_sql", #agent virtualization
8205 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8206 #try looking for matches with extensions unless one was specified
8208 push @cust_main, qsearch( {
8209 'table' => 'cust_main',
8210 'hashref' => { %options },
8211 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8213 join(' OR ', map "$_ LIKE '$phonen\%'",
8215 ship_daytime ship_night )
8218 " AND $agentnums_sql", #agent virtualization
8223 # custnum search (also try agent_custid), with some tweaking options if your
8224 # legacy cust "numbers" have letters
8227 if ( $search =~ /^\s*(\d+)\s*$/
8228 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8229 && $search =~ /^\s*(\w\w?\d+)\s*$/
8231 || ( $conf->exists('address1-search' )
8232 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
8239 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
8240 push @cust_main, qsearch( {
8241 'table' => 'cust_main',
8242 'hashref' => { 'custnum' => $num, %options },
8243 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8247 push @cust_main, qsearch( {
8248 'table' => 'cust_main',
8249 'hashref' => { 'agent_custid' => $num, %options },
8250 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8253 if ( $conf->exists('address1-search') ) {
8254 my $len = length($num);
8256 foreach my $prefix ( '', 'ship_' ) {
8257 push @cust_main, qsearch( {
8258 'table' => 'cust_main',
8259 'hashref' => { %options, },
8261 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8262 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
8263 " AND $agentnums_sql",
8268 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8270 my($company, $last, $first) = ( $1, $2, $3 );
8272 # "Company (Last, First)"
8273 #this is probably something a browser remembered,
8274 #so just do an exact search (but case-insensitive, so USPS standardization
8275 #doesn't throw a wrench in the works)
8277 foreach my $prefix ( '', 'ship_' ) {
8278 push @cust_main, qsearch( {
8279 'table' => 'cust_main',
8280 'hashref' => { %options },
8282 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8284 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
8285 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
8286 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
8292 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8293 # try (ship_){last,company}
8297 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8298 # # full strings the browser remembers won't work
8299 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8301 use Lingua::EN::NameParse;
8302 my $NameParse = new Lingua::EN::NameParse(
8304 allow_reversed => 1,
8307 my($last, $first) = ( '', '' );
8308 #maybe disable this too and just rely on NameParse?
8309 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8311 ($last, $first) = ( $1, $2 );
8313 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
8314 } elsif ( ! $NameParse->parse($value) ) {
8316 my %name = $NameParse->components;
8317 $first = $name{'given_name_1'};
8318 $last = $name{'surname_1'};
8322 if ( $first && $last ) {
8324 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8327 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8329 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8330 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8333 push @cust_main, qsearch( {
8334 'table' => 'cust_main',
8335 'hashref' => \%options,
8336 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8339 # or it just be something that was typed in... (try that in a sec)
8343 my $q_value = dbh->quote($value);
8346 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8347 $sql .= " ( LOWER(last) = $q_value
8348 OR LOWER(company) = $q_value
8349 OR LOWER(ship_last) = $q_value
8350 OR LOWER(ship_company) = $q_value
8352 $sql .= " OR LOWER(address1) = $q_value
8353 OR LOWER(ship_address1) = $q_value
8355 if $conf->exists('address1-search');
8358 push @cust_main, qsearch( {
8359 'table' => 'cust_main',
8360 'hashref' => \%options,
8361 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8364 #no exact match, trying substring/fuzzy
8365 #always do substring & fuzzy (unless they're explicity config'ed off)
8366 #getting complaints searches are not returning enough
8367 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8369 #still some false laziness w/search (was search/cust_main.cgi)
8374 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
8375 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8378 if ( $first && $last ) {
8381 { 'first' => { op=>'ILIKE', value=>"%$first%" },
8382 'last' => { op=>'ILIKE', value=>"%$last%" },
8384 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
8385 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
8392 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
8393 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
8397 if ( $conf->exists('address1-search') ) {
8399 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
8400 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
8404 foreach my $hashref ( @hashrefs ) {
8406 push @cust_main, qsearch( {
8407 'table' => 'cust_main',
8408 'hashref' => { %$hashref,
8411 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8420 " AND $agentnums_sql", #extra_sql #agent virtualization
8423 if ( $first && $last ) {
8424 push @cust_main, FS::cust_main->fuzzy_search(
8425 { 'last' => $last, #fuzzy hashref
8426 'first' => $first }, #
8430 foreach my $field ( 'last', 'company' ) {
8432 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8434 if ( $conf->exists('address1-search') ) {
8436 FS::cust_main->fuzzy_search( { 'address1' => $value }, @fuzopts );
8443 #eliminate duplicates
8445 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8453 Accepts the following options: I<email>, the email address to search for. The
8454 email address will be searched for as an email invoice destination and as an
8457 #Any additional options are treated as an additional qualifier on the search
8458 #(i.e. I<agentnum>).
8460 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8470 my $email = delete $options{'email'};
8472 #we're only being used by RT at the moment... no agent virtualization yet
8473 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8477 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8479 my ( $user, $domain ) = ( $1, $2 );
8481 warn "$me smart_search: searching for $user in domain $domain"
8487 'table' => 'cust_main_invoice',
8488 'hashref' => { 'dest' => $email },
8495 map $_->cust_svc->cust_pkg,
8497 'table' => 'svc_acct',
8498 'hashref' => { 'username' => $user, },
8500 'AND ( SELECT domain FROM svc_domain
8501 WHERE svc_acct.domsvc = svc_domain.svcnum
8502 ) = '. dbh->quote($domain),
8508 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8510 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8517 =item check_and_rebuild_fuzzyfiles
8521 sub check_and_rebuild_fuzzyfiles {
8522 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8523 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8526 =item rebuild_fuzzyfiles
8530 sub rebuild_fuzzyfiles {
8532 use Fcntl qw(:flock);
8534 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8535 mkdir $dir, 0700 unless -d $dir;
8537 foreach my $fuzzy ( @fuzzyfields ) {
8539 open(LOCK,">>$dir/cust_main.$fuzzy")
8540 or die "can't open $dir/cust_main.$fuzzy: $!";
8542 or die "can't lock $dir/cust_main.$fuzzy: $!";
8544 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8545 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8547 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8548 my $sth = dbh->prepare("SELECT $field FROM cust_main".
8549 " WHERE $field != '' AND $field IS NOT NULL");
8550 $sth->execute or die $sth->errstr;
8552 while ( my $row = $sth->fetchrow_arrayref ) {
8553 print CACHE $row->[0]. "\n";
8558 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8560 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8571 my( $self, $field ) = @_;
8572 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8573 open(CACHE,"<$dir/cust_main.$field")
8574 or die "can't open $dir/cust_main.$field: $!";
8575 my @array = map { chomp; $_; } <CACHE>;
8580 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
8584 sub append_fuzzyfiles {
8585 #my( $first, $last, $company ) = @_;
8587 &check_and_rebuild_fuzzyfiles;
8589 use Fcntl qw(:flock);
8591 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8593 foreach my $field (@fuzzyfields) {
8598 open(CACHE,">>$dir/cust_main.$field")
8599 or die "can't open $dir/cust_main.$field: $!";
8600 flock(CACHE,LOCK_EX)
8601 or die "can't lock $dir/cust_main.$field: $!";
8603 print CACHE "$value\n";
8605 flock(CACHE,LOCK_UN)
8606 or die "can't unlock $dir/cust_main.$field: $!";
8621 #warn join('-',keys %$param);
8622 my $fh = $param->{filehandle};
8623 my @fields = @{$param->{fields}};
8625 eval "use Text::CSV_XS;";
8628 my $csv = new Text::CSV_XS;
8635 local $SIG{HUP} = 'IGNORE';
8636 local $SIG{INT} = 'IGNORE';
8637 local $SIG{QUIT} = 'IGNORE';
8638 local $SIG{TERM} = 'IGNORE';
8639 local $SIG{TSTP} = 'IGNORE';
8640 local $SIG{PIPE} = 'IGNORE';
8642 my $oldAutoCommit = $FS::UID::AutoCommit;
8643 local $FS::UID::AutoCommit = 0;
8646 #while ( $columns = $csv->getline($fh) ) {
8648 while ( defined($line=<$fh>) ) {
8650 $csv->parse($line) or do {
8651 $dbh->rollback if $oldAutoCommit;
8652 return "can't parse: ". $csv->error_input();
8655 my @columns = $csv->fields();
8656 #warn join('-',@columns);
8659 foreach my $field ( @fields ) {
8660 $row{$field} = shift @columns;
8663 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
8664 unless ( $cust_main ) {
8665 $dbh->rollback if $oldAutoCommit;
8666 return "unknown custnum $row{'custnum'}";
8669 if ( $row{'amount'} > 0 ) {
8670 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8672 $dbh->rollback if $oldAutoCommit;
8676 } elsif ( $row{'amount'} < 0 ) {
8677 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8680 $dbh->rollback if $oldAutoCommit;
8690 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8692 return "Empty file!" unless $imported;
8698 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8700 Sends a templated email notification to the customer (see L<Text::Template>).
8702 OPTIONS is a hash and may include
8704 I<from> - the email sender (default is invoice_from)
8706 I<to> - comma-separated scalar or arrayref of recipients
8707 (default is invoicing_list)
8709 I<subject> - The subject line of the sent email notification
8710 (default is "Notice from company_name")
8712 I<extra_fields> - a hashref of name/value pairs which will be substituted
8715 The following variables are vavailable in the template.
8717 I<$first> - the customer first name
8718 I<$last> - the customer last name
8719 I<$company> - the customer company
8720 I<$payby> - a description of the method of payment for the customer
8721 # would be nice to use FS::payby::shortname
8722 I<$payinfo> - the account information used to collect for this customer
8723 I<$expdate> - the expiration of the customer payment in seconds from epoch
8728 my ($self, $template, %options) = @_;
8730 return unless $conf->exists($template);
8732 my $from = $conf->config('invoice_from', $self->agentnum)
8733 if $conf->exists('invoice_from', $self->agentnum);
8734 $from = $options{from} if exists($options{from});
8736 my $to = join(',', $self->invoicing_list_emailonly);
8737 $to = $options{to} if exists($options{to});
8739 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
8740 if $conf->exists('company_name', $self->agentnum);
8741 $subject = $options{subject} if exists($options{subject});
8743 my $notify_template = new Text::Template (TYPE => 'ARRAY',
8744 SOURCE => [ map "$_\n",
8745 $conf->config($template)]
8747 or die "can't create new Text::Template object: Text::Template::ERROR";
8748 $notify_template->compile()
8749 or die "can't compile template: Text::Template::ERROR";
8751 $FS::notify_template::_template::company_name =
8752 $conf->config('company_name', $self->agentnum);
8753 $FS::notify_template::_template::company_address =
8754 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
8756 my $paydate = $self->paydate || '2037-12-31';
8757 $FS::notify_template::_template::first = $self->first;
8758 $FS::notify_template::_template::last = $self->last;
8759 $FS::notify_template::_template::company = $self->company;
8760 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
8761 my $payby = $self->payby;
8762 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8763 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8765 #credit cards expire at the end of the month/year of their exp date
8766 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8767 $FS::notify_template::_template::payby = 'credit card';
8768 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8769 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8771 }elsif ($payby eq 'COMP') {
8772 $FS::notify_template::_template::payby = 'complimentary account';
8774 $FS::notify_template::_template::payby = 'current method';
8776 $FS::notify_template::_template::expdate = $expire_time;
8778 for (keys %{$options{extra_fields}}){
8780 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
8783 send_email(from => $from,
8785 subject => $subject,
8786 body => $notify_template->fill_in( PACKAGE =>
8787 'FS::notify_template::_template' ),
8792 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8794 Generates a templated notification to the customer (see L<Text::Template>).
8796 OPTIONS is a hash and may include
8798 I<extra_fields> - a hashref of name/value pairs which will be substituted
8799 into the template. These values may override values mentioned below
8800 and those from the customer record.
8802 The following variables are available in the template instead of or in addition
8803 to the fields of the customer record.
8805 I<$payby> - a description of the method of payment for the customer
8806 # would be nice to use FS::payby::shortname
8807 I<$payinfo> - the masked account information used to collect for this customer
8808 I<$expdate> - the expiration of the customer payment method in seconds from epoch
8809 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
8813 sub generate_letter {
8814 my ($self, $template, %options) = @_;
8816 return unless $conf->exists($template);
8818 my $letter_template = new Text::Template
8820 SOURCE => [ map "$_\n", $conf->config($template)],
8821 DELIMITERS => [ '[@--', '--@]' ],
8823 or die "can't create new Text::Template object: Text::Template::ERROR";
8825 $letter_template->compile()
8826 or die "can't compile template: Text::Template::ERROR";
8828 my %letter_data = map { $_ => $self->$_ } $self->fields;
8829 $letter_data{payinfo} = $self->mask_payinfo;
8831 #my $paydate = $self->paydate || '2037-12-31';
8832 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
8834 my $payby = $self->payby;
8835 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8836 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8838 #credit cards expire at the end of the month/year of their exp date
8839 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8840 $letter_data{payby} = 'credit card';
8841 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8842 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8844 }elsif ($payby eq 'COMP') {
8845 $letter_data{payby} = 'complimentary account';
8847 $letter_data{payby} = 'current method';
8849 $letter_data{expdate} = $expire_time;
8851 for (keys %{$options{extra_fields}}){
8852 $letter_data{$_} = $options{extra_fields}->{$_};
8855 unless(exists($letter_data{returnaddress})){
8856 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
8857 $self->agent_template)
8859 if ( length($retadd) ) {
8860 $letter_data{returnaddress} = $retadd;
8861 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
8862 $letter_data{returnaddress} =
8863 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
8864 $conf->config('company_address', $self->agentnum)
8867 $letter_data{returnaddress} = '~';
8871 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
8873 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
8875 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
8876 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
8880 ) or die "can't open temp file: $!\n";
8882 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
8884 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
8888 =item print_ps TEMPLATE
8890 Returns an postscript letter filled in from TEMPLATE, as a scalar.
8896 my $file = $self->generate_letter(@_);
8897 FS::Misc::generate_ps($file);
8900 =item print TEMPLATE
8902 Prints the filled in template.
8904 TEMPLATE is the name of a L<Text::Template> to fill in and print.
8908 sub queueable_print {
8911 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
8912 or die "invalid customer number: " . $opt{custvnum};
8914 my $error = $self->print( $opt{template} );
8915 die $error if $error;
8919 my ($self, $template) = (shift, shift);
8920 do_print [ $self->print_ps($template) ];
8923 #these three subs should just go away once agent stuff is all config overrides
8925 sub agent_template {
8927 $self->_agent_plandata('agent_templatename');
8930 sub agent_invoice_from {
8932 $self->_agent_plandata('agent_invoice_from');
8935 sub _agent_plandata {
8936 my( $self, $option ) = @_;
8938 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
8939 #agent-specific Conf
8941 use FS::part_event::Condition;
8943 my $agentnum = $self->agentnum;
8945 my $regexp = regexp_sql();
8947 my $part_event_option =
8949 'select' => 'part_event_option.*',
8950 'table' => 'part_event_option',
8952 LEFT JOIN part_event USING ( eventpart )
8953 LEFT JOIN part_event_option AS peo_agentnum
8954 ON ( part_event.eventpart = peo_agentnum.eventpart
8955 AND peo_agentnum.optionname = 'agentnum'
8956 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
8958 LEFT JOIN part_event_condition
8959 ON ( part_event.eventpart = part_event_condition.eventpart
8960 AND part_event_condition.conditionname = 'cust_bill_age'
8962 LEFT JOIN part_event_condition_option
8963 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
8964 AND part_event_condition_option.optionname = 'age'
8967 #'hashref' => { 'optionname' => $option },
8968 #'hashref' => { 'part_event_option.optionname' => $option },
8970 " WHERE part_event_option.optionname = ". dbh->quote($option).
8971 " AND action = 'cust_bill_send_agent' ".
8972 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
8973 " AND peo_agentnum.optionname = 'agentnum' ".
8974 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
8976 CASE WHEN part_event_condition_option.optionname IS NULL
8978 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
8980 , part_event.weight".
8984 unless ( $part_event_option ) {
8985 return $self->agent->invoice_template || ''
8986 if $option eq 'agent_templatename';
8990 $part_event_option->optionvalue;
8994 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
8996 Subroutine (not a method), designed to be called from the queue.
8998 Takes a list of options and values.
9000 Pulls up the customer record via the custnum option and calls bill_and_collect.
9005 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
9007 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
9008 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
9010 $cust_main->bill_and_collect( %args );
9013 sub process_bill_and_collect {
9015 my $param = thaw(decode_base64(shift));
9016 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
9017 or die "custnum '$param->{custnum}' not found!\n";
9018 $param->{'job'} = $job;
9019 $param->{'fatal'} = 1; # runs from job queue, will be caught
9020 $param->{'retry'} = 1;
9022 $cust_main->bill_and_collect( %$param );
9025 sub _upgrade_data { #class method
9026 my ($class, %opts) = @_;
9028 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
9029 my $sth = dbh->prepare($sql) or die dbh->errstr;
9030 $sth->execute or die $sth->errstr;
9032 local($ignore_expired_card) = 1;
9033 $class->_upgrade_otaker(%opts);
9043 The delete method should possibly take an FS::cust_main object reference
9044 instead of a scalar customer number.
9046 Bill and collect options should probably be passed as references instead of a
9049 There should probably be a configuration file with a list of allowed credit
9052 No multiple currency support (probably a larger project than just this module).
9054 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
9056 Birthdates rely on negative epoch values.
9058 The payby for card/check batches is broken. With mixed batching, bad
9061 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
9065 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
9066 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
9067 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.