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);
21 use Digest::MD5 qw(md5_base64);
24 use File::Temp qw( tempfile );
25 use String::Approx qw(amatch);
26 use Business::CreditCard 0.28;
28 use FS::UID qw( getotaker dbh driver_name );
29 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
30 use FS::Misc qw( generate_email send_email generate_ps do_print );
31 use FS::Msgcat qw(gettext);
36 use FS::cust_bill_pkg;
37 use FS::cust_bill_pkg_display;
38 use FS::cust_bill_pkg_tax_location;
39 use FS::cust_bill_pkg_tax_rate_location;
41 use FS::cust_pay_pending;
42 use FS::cust_pay_void;
43 use FS::cust_pay_batch;
46 use FS::part_referral;
47 use FS::cust_main_county;
48 use FS::cust_location;
50 use FS::cust_main_exemption;
51 use FS::cust_tax_adjustment;
53 use FS::tax_rate_location;
54 use FS::cust_tax_location;
55 use FS::part_pkg_taxrate;
57 use FS::cust_main_invoice;
58 use FS::cust_credit_bill;
59 use FS::cust_bill_pay;
60 use FS::prepay_credit;
64 use FS::part_event_condition;
68 use FS::payment_gateway;
69 use FS::agent_payment_gateway;
73 @EXPORT_OK = qw( smart_search );
75 $realtime_bop_decline_quiet = 0;
77 # 1 is mostly method/subroutine entry and options
78 # 2 traces progress of some operations
79 # 3 is even more information including possibly sensitive data
81 $me = '[FS::cust_main]';
84 $ignore_expired_card = 0;
87 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
89 @encrypted_fields = ('payinfo', 'paycvv');
90 sub nohistory_fields { ('payinfo', 'paycvv'); }
92 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
94 #ask FS::UID to run this stuff for us later
95 #$FS::UID::callback{'FS::cust_main'} = sub {
96 install_callback FS::UID sub {
98 #yes, need it for stuff below (prolly should be cached)
103 my ( $hashref, $cache ) = @_;
104 if ( exists $hashref->{'pkgnum'} ) {
105 #@{ $self->{'_pkgnum'} } = ();
106 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
107 $self->{'_pkgnum'} = $subcache;
108 #push @{ $self->{'_pkgnum'} },
109 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
115 FS::cust_main - Object methods for cust_main records
121 $record = new FS::cust_main \%hash;
122 $record = new FS::cust_main { 'column' => 'value' };
124 $error = $record->insert;
126 $error = $new_record->replace($old_record);
128 $error = $record->delete;
130 $error = $record->check;
132 @cust_pkg = $record->all_pkgs;
134 @cust_pkg = $record->ncancelled_pkgs;
136 @cust_pkg = $record->suspended_pkgs;
138 $error = $record->bill;
139 $error = $record->bill %options;
140 $error = $record->bill 'time' => $time;
142 $error = $record->collect;
143 $error = $record->collect %options;
144 $error = $record->collect 'invoice_time' => $time,
149 An FS::cust_main object represents a customer. FS::cust_main inherits from
150 FS::Record. The following fields are currently supported:
156 Primary key (assigned automatically for new customers)
160 Agent (see L<FS::agent>)
164 Advertising source (see L<FS::part_referral>)
176 Cocial security number (optional)
192 (optional, see L<FS::cust_main_county>)
196 (see L<FS::cust_main_county>)
202 (see L<FS::cust_main_county>)
238 (optional, see L<FS::cust_main_county>)
242 (see L<FS::cust_main_county>)
248 (see L<FS::cust_main_county>)
264 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
268 Payment Information (See L<FS::payinfo_Mixin> for data format)
272 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
276 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
280 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
284 Start date month (maestro/solo cards only)
288 Start date year (maestro/solo cards only)
292 Issue number (maestro/solo cards only)
296 Name on card or billing name
300 IP address from which payment information was received
304 Tax exempt, empty or `Y'
308 Order taker (see L<FS::access_user>)
314 =item referral_custnum
316 Referring customer number
320 Enable individual CDR spooling, empty or `Y'
324 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
328 Discourage individual CDR printing, empty or `Y'
338 Creates a new customer. To add the customer to the database, see L<"insert">.
340 Note that this stores the hash reference, not a distinct copy of the hash it
341 points to. You can ask the object for a copy with the I<hash> method.
345 sub table { 'cust_main'; }
347 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
349 Adds this customer to the database. If there is an error, returns the error,
350 otherwise returns false.
352 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
353 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
354 are inserted atomicly, or the transaction is rolled back. Passing an empty
355 hash reference is equivalent to not supplying this parameter. There should be
356 a better explanation of this, but until then, here's an example:
359 tie %hash, 'Tie::RefHash'; #this part is important
361 $cust_pkg => [ $svc_acct ],
364 $cust_main->insert( \%hash );
366 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
367 be set as the invoicing list (see L<"invoicing_list">). Errors return as
368 expected and rollback the entire transaction; it is not necessary to call
369 check_invoicing_list first. The invoicing_list is set after the records in the
370 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
371 invoicing_list destination to the newly-created svc_acct. Here's an example:
373 $cust_main->insert( {}, [ $email, 'POST' ] );
375 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
377 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
378 on the supplied jobnum (they will not run until the specific job completes).
379 This can be used to defer provisioning until some action completes (such
380 as running the customer's credit card successfully).
382 The I<noexport> option is deprecated. If I<noexport> is set true, no
383 provisioning jobs (exports) are scheduled. (You can schedule them later with
384 the B<reexport> method.)
386 The I<tax_exemption> option can be set to an arrayref of tax names.
387 FS::cust_main_exemption records will be created and inserted.
393 my $cust_pkgs = @_ ? shift : {};
394 my $invoicing_list = @_ ? shift : '';
396 warn "$me insert called with options ".
397 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
400 local $SIG{HUP} = 'IGNORE';
401 local $SIG{INT} = 'IGNORE';
402 local $SIG{QUIT} = 'IGNORE';
403 local $SIG{TERM} = 'IGNORE';
404 local $SIG{TSTP} = 'IGNORE';
405 local $SIG{PIPE} = 'IGNORE';
407 my $oldAutoCommit = $FS::UID::AutoCommit;
408 local $FS::UID::AutoCommit = 0;
411 my $prepay_identifier = '';
412 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
414 if ( $self->payby eq 'PREPAY' ) {
416 $self->payby('BILL');
417 $prepay_identifier = $self->payinfo;
420 warn " looking up prepaid card $prepay_identifier\n"
423 my $error = $self->get_prepay( $prepay_identifier,
424 'amount_ref' => \$amount,
425 'seconds_ref' => \$seconds,
426 'upbytes_ref' => \$upbytes,
427 'downbytes_ref' => \$downbytes,
428 'totalbytes_ref' => \$totalbytes,
431 $dbh->rollback if $oldAutoCommit;
432 #return "error applying prepaid card (transaction rolled back): $error";
436 $payby = 'PREP' if $amount;
438 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
441 $self->payby('BILL');
442 $amount = $self->paid;
446 warn " inserting $self\n"
449 $self->signupdate(time) unless $self->signupdate;
451 $self->auto_agent_custid()
452 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
454 my $error = $self->SUPER::insert;
456 $dbh->rollback if $oldAutoCommit;
457 #return "inserting cust_main record (transaction rolled back): $error";
461 warn " setting invoicing list\n"
464 if ( $invoicing_list ) {
465 $error = $self->check_invoicing_list( $invoicing_list );
467 $dbh->rollback if $oldAutoCommit;
468 #return "checking invoicing_list (transaction rolled back): $error";
471 $self->invoicing_list( $invoicing_list );
474 warn " setting cust_main_exemption\n"
477 my $tax_exemption = delete $options{'tax_exemption'};
478 if ( $tax_exemption ) {
479 foreach my $taxname ( @$tax_exemption ) {
480 my $cust_main_exemption = new FS::cust_main_exemption {
481 'custnum' => $self->custnum,
482 'taxname' => $taxname,
484 my $error = $cust_main_exemption->insert;
486 $dbh->rollback if $oldAutoCommit;
487 return "inserting cust_main_exemption (transaction rolled back): $error";
492 if ( $conf->config('cust_main-skeleton_tables')
493 && $conf->config('cust_main-skeleton_custnum') ) {
495 warn " inserting skeleton records\n"
498 my $error = $self->start_copy_skel;
500 $dbh->rollback if $oldAutoCommit;
506 warn " ordering packages\n"
509 $error = $self->order_pkgs( $cust_pkgs,
511 'seconds_ref' => \$seconds,
512 'upbytes_ref' => \$upbytes,
513 'downbytes_ref' => \$downbytes,
514 'totalbytes_ref' => \$totalbytes,
517 $dbh->rollback if $oldAutoCommit;
522 $dbh->rollback if $oldAutoCommit;
523 return "No svc_acct record to apply pre-paid time";
525 if ( $upbytes || $downbytes || $totalbytes ) {
526 $dbh->rollback if $oldAutoCommit;
527 return "No svc_acct record to apply pre-paid data";
531 warn " inserting initial $payby payment of $amount\n"
533 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
535 $dbh->rollback if $oldAutoCommit;
536 return "inserting payment (transaction rolled back): $error";
540 unless ( $import || $skip_fuzzyfiles ) {
541 warn " queueing fuzzyfiles update\n"
543 $error = $self->queue_fuzzyfiles_update;
545 $dbh->rollback if $oldAutoCommit;
546 return "updating fuzzy search cache: $error";
551 warn " exporting\n" if $DEBUG > 1;
553 my $export_args = $options{'export_args'} || [];
556 map qsearch( 'part_export', {exportnum=>$_} ),
557 $conf->config('cust_main-exports'); #, $agentnum
559 foreach my $part_export ( @part_export ) {
560 my $error = $part_export->export_insert($self, @$export_args);
562 $dbh->rollback if $oldAutoCommit;
563 return "exporting to ". $part_export->exporttype.
564 " (transaction rolled back): $error";
568 #foreach my $depend_jobnum ( @$depend_jobnums ) {
569 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
571 # foreach my $jobnum ( @jobnums ) {
572 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
573 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
575 # my $error = $queue->depend_insert($depend_jobnum);
577 # $dbh->rollback if $oldAutoCommit;
578 # return "error queuing job dependancy: $error";
585 #if ( exists $options{'jobnums'} ) {
586 # push @{ $options{'jobnums'} }, @jobnums;
589 warn " insert complete; committing transaction\n"
592 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
597 use File::CounterFile;
598 sub auto_agent_custid {
601 my $format = $conf->config('cust_main-auto_agent_custid');
603 if ( $format eq '1YMMXXXXXXXX' ) {
605 my $counter = new File::CounterFile 'cust_main.agent_custid';
608 my $ym = 100000000000 + time2str('%y%m00000000', time);
609 if ( $ym > $counter->value ) {
610 $counter->{'value'} = $agent_custid = $ym;
611 $counter->{'updated'} = 1;
613 $agent_custid = $counter->inc;
619 die "Unknown cust_main-auto_agent_custid format: $format";
622 $self->agent_custid($agent_custid);
626 sub start_copy_skel {
629 #'mg_user_preference' => {},
630 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
631 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
632 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
633 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
634 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
637 _copy_skel( 'cust_main', #tablename
638 $conf->config('cust_main-skeleton_custnum'), #sourceid
639 $self->custnum, #destid
640 @tables, #child tables
644 #recursive subroutine, not a method
646 my( $table, $sourceid, $destid, %child_tables ) = @_;
649 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
650 ( $table, $primary_key ) = ( $1, $2 );
652 my $dbdef_table = dbdef->table($table);
653 $primary_key = $dbdef_table->primary_key
654 or return "$table has no primary key".
655 " (or do you need to run dbdef-create?)";
658 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
659 join (', ', keys %child_tables). "\n"
662 foreach my $child_table_def ( keys %child_tables ) {
666 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
667 ( $child_table, $child_pkey ) = ( $1, $2 );
669 $child_table = $child_table_def;
671 $child_pkey = dbdef->table($child_table)->primary_key;
672 # or return "$table has no primary key".
673 # " (or do you need to run dbdef-create?)\n";
677 if ( keys %{ $child_tables{$child_table_def} } ) {
679 return "$child_table has no primary key".
680 " (run dbdef-create or try specifying it?)\n"
683 #false laziness w/Record::insert and only works on Pg
684 #refactor the proper last-inserted-id stuff out of Record::insert if this
685 # ever gets use for anything besides a quick kludge for one customer
686 my $default = dbdef->table($child_table)->column($child_pkey)->default;
687 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
688 or return "can't parse $child_table.$child_pkey default value ".
689 " for sequence name: $default";
694 my @sel_columns = grep { $_ ne $primary_key }
695 dbdef->table($child_table)->columns;
696 my $sel_columns = join(', ', @sel_columns );
698 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
699 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
700 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
702 my $sel_st = "SELECT $sel_columns FROM $child_table".
703 " WHERE $primary_key = $sourceid";
706 my $sel_sth = dbh->prepare( $sel_st )
707 or return dbh->errstr;
709 $sel_sth->execute or return $sel_sth->errstr;
711 while ( my $row = $sel_sth->fetchrow_hashref ) {
713 warn " selected row: ".
714 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
718 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
719 my $ins_sth =dbh->prepare($statement)
720 or return dbh->errstr;
721 my @param = ( $destid, map $row->{$_}, @ins_columns );
722 warn " $statement: [ ". join(', ', @param). " ]\n"
724 $ins_sth->execute( @param )
725 or return $ins_sth->errstr;
727 #next unless keys %{ $child_tables{$child_table} };
728 next unless $sequence;
730 #another section of that laziness
731 my $seq_sql = "SELECT currval('$sequence')";
732 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
733 $seq_sth->execute or return $seq_sth->errstr;
734 my $insertid = $seq_sth->fetchrow_arrayref->[0];
736 # don't drink soap! recurse! recurse! okay!
738 _copy_skel( $child_table_def,
739 $row->{$child_pkey}, #sourceid
741 %{ $child_tables{$child_table_def} },
743 return $error if $error;
753 =item order_pkg HASHREF | OPTION => VALUE ...
755 Orders a single package.
757 Options may be passed as a list of key/value pairs or as a hash reference.
768 Optional FS::cust_location object
772 Optional arryaref of FS::svc_* service objects.
776 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
777 jobs will have a dependancy on the supplied job (they will not run until the
778 specific job completes). This can be used to defer provisioning until some
779 action completes (such as running the customer's credit card successfully).
783 Optional subject for a ticket created and attached to this customer
787 Optional queue name for ticket additions
795 my $opt = ref($_[0]) ? shift : { @_ };
797 warn "$me order_pkg called with options ".
798 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
801 my $cust_pkg = $opt->{'cust_pkg'};
802 my $svcs = $opt->{'svcs'} || [];
804 my %svc_options = ();
805 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
806 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
808 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
809 qw( ticket_subject ticket_queue );
811 local $SIG{HUP} = 'IGNORE';
812 local $SIG{INT} = 'IGNORE';
813 local $SIG{QUIT} = 'IGNORE';
814 local $SIG{TERM} = 'IGNORE';
815 local $SIG{TSTP} = 'IGNORE';
816 local $SIG{PIPE} = 'IGNORE';
818 my $oldAutoCommit = $FS::UID::AutoCommit;
819 local $FS::UID::AutoCommit = 0;
822 if ( $opt->{'cust_location'} &&
823 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
824 my $error = $opt->{'cust_location'}->insert;
826 $dbh->rollback if $oldAutoCommit;
827 return "inserting cust_location (transaction rolled back): $error";
829 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
832 $cust_pkg->custnum( $self->custnum );
834 my $error = $cust_pkg->insert( %insert_params );
836 $dbh->rollback if $oldAutoCommit;
837 return "inserting cust_pkg (transaction rolled back): $error";
840 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
841 if ( $svc_something->svcnum ) {
842 my $old_cust_svc = $svc_something->cust_svc;
843 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
844 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
845 $error = $new_cust_svc->replace($old_cust_svc);
847 $svc_something->pkgnum( $cust_pkg->pkgnum );
848 if ( $svc_something->isa('FS::svc_acct') ) {
849 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
850 qw( seconds upbytes downbytes totalbytes ) ) {
851 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
852 ${ $opt->{$_.'_ref'} } = 0;
855 $error = $svc_something->insert(%svc_options);
858 $dbh->rollback if $oldAutoCommit;
859 return "inserting svc_ (transaction rolled back): $error";
863 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
868 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
869 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
871 Like the insert method on an existing record, this method orders multiple
872 packages and included services atomicaly. Pass a Tie::RefHash data structure
873 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
874 There should be a better explanation of this, but until then, here's an
878 tie %hash, 'Tie::RefHash'; #this part is important
880 $cust_pkg => [ $svc_acct ],
883 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
885 Services can be new, in which case they are inserted, or existing unaudited
886 services, in which case they are linked to the newly-created package.
888 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
889 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
891 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
892 on the supplied jobnum (they will not run until the specific job completes).
893 This can be used to defer provisioning until some action completes (such
894 as running the customer's credit card successfully).
896 The I<noexport> option is deprecated. If I<noexport> is set true, no
897 provisioning jobs (exports) are scheduled. (You can schedule them later with
898 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
899 on the cust_main object is not recommended, as existing services will also be
902 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
903 provided, the scalars (provided by references) will be incremented by the
904 values of the prepaid card.`
910 my $cust_pkgs = shift;
911 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
913 $seconds_ref ||= $options{'seconds_ref'};
915 warn "$me order_pkgs called with options ".
916 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
919 local $SIG{HUP} = 'IGNORE';
920 local $SIG{INT} = 'IGNORE';
921 local $SIG{QUIT} = 'IGNORE';
922 local $SIG{TERM} = 'IGNORE';
923 local $SIG{TSTP} = 'IGNORE';
924 local $SIG{PIPE} = 'IGNORE';
926 my $oldAutoCommit = $FS::UID::AutoCommit;
927 local $FS::UID::AutoCommit = 0;
930 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
932 foreach my $cust_pkg ( keys %$cust_pkgs ) {
934 my $error = $self->order_pkg(
935 'cust_pkg' => $cust_pkg,
936 'svcs' => $cust_pkgs->{$cust_pkg},
937 'seconds_ref' => $seconds_ref,
938 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
943 $dbh->rollback if $oldAutoCommit;
949 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
953 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
955 Recharges this (existing) customer with the specified prepaid card (see
956 L<FS::prepay_credit>), specified either by I<identifier> or as an
957 FS::prepay_credit object. If there is an error, returns the error, otherwise
960 Optionally, five scalar references can be passed as well. They will have their
961 values filled in with the amount, number of seconds, and number of upload,
962 download, and total bytes applied by this prepaid card.
966 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
967 #the only place that uses these args
968 sub recharge_prepay {
969 my( $self, $prepay_credit, $amountref, $secondsref,
970 $upbytesref, $downbytesref, $totalbytesref ) = @_;
972 local $SIG{HUP} = 'IGNORE';
973 local $SIG{INT} = 'IGNORE';
974 local $SIG{QUIT} = 'IGNORE';
975 local $SIG{TERM} = 'IGNORE';
976 local $SIG{TSTP} = 'IGNORE';
977 local $SIG{PIPE} = 'IGNORE';
979 my $oldAutoCommit = $FS::UID::AutoCommit;
980 local $FS::UID::AutoCommit = 0;
983 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
985 my $error = $self->get_prepay( $prepay_credit,
986 'amount_ref' => \$amount,
987 'seconds_ref' => \$seconds,
988 'upbytes_ref' => \$upbytes,
989 'downbytes_ref' => \$downbytes,
990 'totalbytes_ref' => \$totalbytes,
992 || $self->increment_seconds($seconds)
993 || $self->increment_upbytes($upbytes)
994 || $self->increment_downbytes($downbytes)
995 || $self->increment_totalbytes($totalbytes)
996 || $self->insert_cust_pay_prepay( $amount,
998 ? $prepay_credit->identifier
1003 $dbh->rollback if $oldAutoCommit;
1007 if ( defined($amountref) ) { $$amountref = $amount; }
1008 if ( defined($secondsref) ) { $$secondsref = $seconds; }
1009 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1010 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1011 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1013 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1018 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1020 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1021 specified either by I<identifier> or as an FS::prepay_credit object.
1023 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
1024 incremented by the values of the prepaid card.
1026 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1027 check or set this customer's I<agentnum>.
1029 If there is an error, returns the error, otherwise returns false.
1035 my( $self, $prepay_credit, %opt ) = @_;
1037 local $SIG{HUP} = 'IGNORE';
1038 local $SIG{INT} = 'IGNORE';
1039 local $SIG{QUIT} = 'IGNORE';
1040 local $SIG{TERM} = 'IGNORE';
1041 local $SIG{TSTP} = 'IGNORE';
1042 local $SIG{PIPE} = 'IGNORE';
1044 my $oldAutoCommit = $FS::UID::AutoCommit;
1045 local $FS::UID::AutoCommit = 0;
1048 unless ( ref($prepay_credit) ) {
1050 my $identifier = $prepay_credit;
1052 $prepay_credit = qsearchs(
1054 { 'identifier' => $prepay_credit },
1059 unless ( $prepay_credit ) {
1060 $dbh->rollback if $oldAutoCommit;
1061 return "Invalid prepaid card: ". $identifier;
1066 if ( $prepay_credit->agentnum ) {
1067 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1068 $dbh->rollback if $oldAutoCommit;
1069 return "prepaid card not valid for agent ". $self->agentnum;
1071 $self->agentnum($prepay_credit->agentnum);
1074 my $error = $prepay_credit->delete;
1076 $dbh->rollback if $oldAutoCommit;
1077 return "removing prepay_credit (transaction rolled back): $error";
1080 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1081 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1083 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1088 =item increment_upbytes SECONDS
1090 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1091 the specified number of upbytes. If there is an error, returns the error,
1092 otherwise returns false.
1096 sub increment_upbytes {
1097 _increment_column( shift, 'upbytes', @_);
1100 =item increment_downbytes SECONDS
1102 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1103 the specified number of downbytes. If there is an error, returns the error,
1104 otherwise returns false.
1108 sub increment_downbytes {
1109 _increment_column( shift, 'downbytes', @_);
1112 =item increment_totalbytes SECONDS
1114 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1115 the specified number of totalbytes. If there is an error, returns the error,
1116 otherwise returns false.
1120 sub increment_totalbytes {
1121 _increment_column( shift, 'totalbytes', @_);
1124 =item increment_seconds SECONDS
1126 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1127 the specified number of seconds. If there is an error, returns the error,
1128 otherwise returns false.
1132 sub increment_seconds {
1133 _increment_column( shift, 'seconds', @_);
1136 =item _increment_column AMOUNT
1138 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1139 the specified number of seconds or bytes. If there is an error, returns
1140 the error, otherwise returns false.
1144 sub _increment_column {
1145 my( $self, $column, $amount ) = @_;
1146 warn "$me increment_column called: $column, $amount\n"
1149 return '' unless $amount;
1151 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1152 $self->ncancelled_pkgs;
1154 if ( ! @cust_pkg ) {
1155 return 'No packages with primary or single services found'.
1156 ' to apply pre-paid time';
1157 } elsif ( scalar(@cust_pkg) > 1 ) {
1158 #maybe have a way to specify the package/account?
1159 return 'Multiple packages found to apply pre-paid time';
1162 my $cust_pkg = $cust_pkg[0];
1163 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1167 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1169 if ( ! @cust_svc ) {
1170 return 'No account found to apply pre-paid time';
1171 } elsif ( scalar(@cust_svc) > 1 ) {
1172 return 'Multiple accounts found to apply pre-paid time';
1175 my $svc_acct = $cust_svc[0]->svc_x;
1176 warn " found service svcnum ". $svc_acct->pkgnum.
1177 ' ('. $svc_acct->email. ")\n"
1180 $column = "increment_$column";
1181 $svc_acct->$column($amount);
1185 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1187 Inserts a prepayment in the specified amount for this customer. An optional
1188 second argument can specify the prepayment identifier for tracking purposes.
1189 If there is an error, returns the error, otherwise returns false.
1193 sub insert_cust_pay_prepay {
1194 shift->insert_cust_pay('PREP', @_);
1197 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1199 Inserts a cash payment in the specified amount for this customer. An optional
1200 second argument can specify the payment identifier for tracking purposes.
1201 If there is an error, returns the error, otherwise returns false.
1205 sub insert_cust_pay_cash {
1206 shift->insert_cust_pay('CASH', @_);
1209 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1211 Inserts a Western Union payment in the specified amount for this customer. An
1212 optional second argument can specify the prepayment identifier for tracking
1213 purposes. If there is an error, returns the error, otherwise returns false.
1217 sub insert_cust_pay_west {
1218 shift->insert_cust_pay('WEST', @_);
1221 sub insert_cust_pay {
1222 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1223 my $payinfo = scalar(@_) ? shift : '';
1225 my $cust_pay = new FS::cust_pay {
1226 'custnum' => $self->custnum,
1227 'paid' => sprintf('%.2f', $amount),
1228 #'_date' => #date the prepaid card was purchased???
1230 'payinfo' => $payinfo,
1238 This method is deprecated. See the I<depend_jobnum> option to the insert and
1239 order_pkgs methods for a better way to defer provisioning.
1241 Re-schedules all exports by calling the B<reexport> method of all associated
1242 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1243 otherwise returns false.
1250 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1251 "use the depend_jobnum option to insert or order_pkgs to delay export";
1253 local $SIG{HUP} = 'IGNORE';
1254 local $SIG{INT} = 'IGNORE';
1255 local $SIG{QUIT} = 'IGNORE';
1256 local $SIG{TERM} = 'IGNORE';
1257 local $SIG{TSTP} = 'IGNORE';
1258 local $SIG{PIPE} = 'IGNORE';
1260 my $oldAutoCommit = $FS::UID::AutoCommit;
1261 local $FS::UID::AutoCommit = 0;
1264 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1265 my $error = $cust_pkg->reexport;
1267 $dbh->rollback if $oldAutoCommit;
1272 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1277 =item delete NEW_CUSTNUM
1279 This deletes the customer. If there is an error, returns the error, otherwise
1282 This will completely remove all traces of the customer record. This is not
1283 what you want when a customer cancels service; for that, cancel all of the
1284 customer's packages (see L</cancel>).
1286 If the customer has any uncancelled packages, you need to pass a new (valid)
1287 customer number for those packages to be transferred to. Cancelled packages
1288 will be deleted. Did I mention that this is NOT what you want when a customer
1289 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1291 You can't delete a customer with invoices (see L<FS::cust_bill>),
1292 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1293 refunds (see L<FS::cust_refund>).
1300 local $SIG{HUP} = 'IGNORE';
1301 local $SIG{INT} = 'IGNORE';
1302 local $SIG{QUIT} = 'IGNORE';
1303 local $SIG{TERM} = 'IGNORE';
1304 local $SIG{TSTP} = 'IGNORE';
1305 local $SIG{PIPE} = 'IGNORE';
1307 my $oldAutoCommit = $FS::UID::AutoCommit;
1308 local $FS::UID::AutoCommit = 0;
1311 if ( $self->cust_bill ) {
1312 $dbh->rollback if $oldAutoCommit;
1313 return "Can't delete a customer with invoices";
1315 if ( $self->cust_credit ) {
1316 $dbh->rollback if $oldAutoCommit;
1317 return "Can't delete a customer with credits";
1319 if ( $self->cust_pay ) {
1320 $dbh->rollback if $oldAutoCommit;
1321 return "Can't delete a customer with payments";
1323 if ( $self->cust_refund ) {
1324 $dbh->rollback if $oldAutoCommit;
1325 return "Can't delete a customer with refunds";
1328 my @cust_pkg = $self->ncancelled_pkgs;
1330 my $new_custnum = shift;
1331 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1332 $dbh->rollback if $oldAutoCommit;
1333 return "Invalid new customer number: $new_custnum";
1335 foreach my $cust_pkg ( @cust_pkg ) {
1336 my %hash = $cust_pkg->hash;
1337 $hash{'custnum'} = $new_custnum;
1338 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1339 my $error = $new_cust_pkg->replace($cust_pkg,
1340 options => { $cust_pkg->options },
1343 $dbh->rollback if $oldAutoCommit;
1348 my @cancelled_cust_pkg = $self->all_pkgs;
1349 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1350 my $error = $cust_pkg->delete;
1352 $dbh->rollback if $oldAutoCommit;
1357 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1358 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1360 my $error = $cust_main_invoice->delete;
1362 $dbh->rollback if $oldAutoCommit;
1367 foreach my $cust_main_exemption (
1368 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } )
1370 my $error = $cust_main_exemption->delete;
1372 $dbh->rollback if $oldAutoCommit;
1377 my $error = $self->SUPER::delete;
1379 $dbh->rollback if $oldAutoCommit;
1383 # cust_main exports!
1385 #my $export_args = $options{'export_args'} || [];
1388 map qsearch( 'part_export', {exportnum=>$_} ),
1389 $conf->config('cust_main-exports'); #, $agentnum
1391 foreach my $part_export ( @part_export ) {
1392 my $error = $part_export->export_delete( $self ); #, @$export_args);
1394 $dbh->rollback if $oldAutoCommit;
1395 return "exporting to ". $part_export->exporttype.
1396 " (transaction rolled back): $error";
1400 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1405 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1408 Replaces the OLD_RECORD with this one in the database. If there is an error,
1409 returns the error, otherwise returns false.
1411 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1412 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1413 expected and rollback the entire transaction; it is not necessary to call
1414 check_invoicing_list first. Here's an example:
1416 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1418 Currently available options are: I<tax_exemption>.
1420 The I<tax_exemption> option can be set to an arrayref of tax names.
1421 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1428 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1430 : $self->replace_old;
1434 warn "$me replace called\n"
1437 my $curuser = $FS::CurrentUser::CurrentUser;
1438 if ( $self->payby eq 'COMP'
1439 && $self->payby ne $old->payby
1440 && ! $curuser->access_right('Complimentary customer')
1443 return "You are not permitted to create complimentary accounts.";
1446 local($ignore_expired_card) = 1
1447 if $old->payby =~ /^(CARD|DCRD)$/
1448 && $self->payby =~ /^(CARD|DCRD)$/
1449 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1451 local $SIG{HUP} = 'IGNORE';
1452 local $SIG{INT} = 'IGNORE';
1453 local $SIG{QUIT} = 'IGNORE';
1454 local $SIG{TERM} = 'IGNORE';
1455 local $SIG{TSTP} = 'IGNORE';
1456 local $SIG{PIPE} = 'IGNORE';
1458 my $oldAutoCommit = $FS::UID::AutoCommit;
1459 local $FS::UID::AutoCommit = 0;
1462 my $error = $self->SUPER::replace($old);
1465 $dbh->rollback if $oldAutoCommit;
1469 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1470 my $invoicing_list = shift @param;
1471 $error = $self->check_invoicing_list( $invoicing_list );
1473 $dbh->rollback if $oldAutoCommit;
1476 $self->invoicing_list( $invoicing_list );
1479 my %options = @param;
1481 my $tax_exemption = delete $options{'tax_exemption'};
1482 if ( $tax_exemption ) {
1484 my %cust_main_exemption =
1485 map { $_->taxname => $_ }
1486 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1488 foreach my $taxname ( @$tax_exemption ) {
1490 next if delete $cust_main_exemption{$taxname};
1492 my $cust_main_exemption = new FS::cust_main_exemption {
1493 'custnum' => $self->custnum,
1494 'taxname' => $taxname,
1496 my $error = $cust_main_exemption->insert;
1498 $dbh->rollback if $oldAutoCommit;
1499 return "inserting cust_main_exemption (transaction rolled back): $error";
1503 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1504 my $error = $cust_main_exemption->delete;
1506 $dbh->rollback if $oldAutoCommit;
1507 return "deleting cust_main_exemption (transaction rolled back): $error";
1513 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1514 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1515 && $self->get('payinfo') !~ /^99\d{14}$/
1517 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1522 # card/check/lec info has changed, want to retry realtime_ invoice events
1523 my $error = $self->retry_realtime;
1525 $dbh->rollback if $oldAutoCommit;
1530 unless ( $import || $skip_fuzzyfiles ) {
1531 $error = $self->queue_fuzzyfiles_update;
1533 $dbh->rollback if $oldAutoCommit;
1534 return "updating fuzzy search cache: $error";
1538 # cust_main exports!
1540 my $export_args = $options{'export_args'} || [];
1543 map qsearch( 'part_export', {exportnum=>$_} ),
1544 $conf->config('cust_main-exports'); #, $agentnum
1546 foreach my $part_export ( @part_export ) {
1547 my $error = $part_export->export_replace( $self, $old, @$export_args);
1549 $dbh->rollback if $oldAutoCommit;
1550 return "exporting to ". $part_export->exporttype.
1551 " (transaction rolled back): $error";
1555 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1560 =item queue_fuzzyfiles_update
1562 Used by insert & replace to update the fuzzy search cache
1566 sub queue_fuzzyfiles_update {
1569 local $SIG{HUP} = 'IGNORE';
1570 local $SIG{INT} = 'IGNORE';
1571 local $SIG{QUIT} = 'IGNORE';
1572 local $SIG{TERM} = 'IGNORE';
1573 local $SIG{TSTP} = 'IGNORE';
1574 local $SIG{PIPE} = 'IGNORE';
1576 my $oldAutoCommit = $FS::UID::AutoCommit;
1577 local $FS::UID::AutoCommit = 0;
1580 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1581 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1583 $dbh->rollback if $oldAutoCommit;
1584 return "queueing job (transaction rolled back): $error";
1587 if ( $self->ship_last ) {
1588 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1589 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1591 $dbh->rollback if $oldAutoCommit;
1592 return "queueing job (transaction rolled back): $error";
1596 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1603 Checks all fields to make sure this is a valid customer record. If there is
1604 an error, returns the error, otherwise returns false. Called by the insert
1605 and replace methods.
1612 warn "$me check BEFORE: \n". $self->_dump
1616 $self->ut_numbern('custnum')
1617 || $self->ut_number('agentnum')
1618 || $self->ut_textn('agent_custid')
1619 || $self->ut_number('refnum')
1620 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1621 || $self->ut_textn('custbatch')
1622 || $self->ut_name('last')
1623 || $self->ut_name('first')
1624 || $self->ut_snumbern('birthdate')
1625 || $self->ut_snumbern('signupdate')
1626 || $self->ut_textn('company')
1627 || $self->ut_text('address1')
1628 || $self->ut_textn('address2')
1629 || $self->ut_text('city')
1630 || $self->ut_textn('county')
1631 || $self->ut_textn('state')
1632 || $self->ut_country('country')
1633 || $self->ut_anything('comments')
1634 || $self->ut_numbern('referral_custnum')
1635 || $self->ut_textn('stateid')
1636 || $self->ut_textn('stateid_state')
1637 || $self->ut_textn('invoice_terms')
1638 || $self->ut_alphan('geocode')
1639 || $self->ut_floatn('cdr_termination_percentage')
1642 #barf. need message catalogs. i18n. etc.
1643 $error .= "Please select an advertising source."
1644 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1645 return $error if $error;
1647 return "Unknown agent"
1648 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1650 return "Unknown refnum"
1651 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1653 return "Unknown referring custnum: ". $self->referral_custnum
1654 unless ! $self->referral_custnum
1655 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1657 if ( $self->censustract ne '' ) {
1658 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1659 or return "Illegal census tract: ". $self->censustract;
1661 $self->censustract("$1.$2");
1664 if ( $self->ss eq '' ) {
1669 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1670 or return "Illegal social security number: ". $self->ss;
1671 $self->ss("$1-$2-$3");
1675 # bad idea to disable, causes billing to fail because of no tax rates later
1676 # unless ( $import ) {
1677 unless ( qsearch('cust_main_county', {
1678 'country' => $self->country,
1681 return "Unknown state/county/country: ".
1682 $self->state. "/". $self->county. "/". $self->country
1683 unless qsearch('cust_main_county',{
1684 'state' => $self->state,
1685 'county' => $self->county,
1686 'country' => $self->country,
1692 $self->ut_phonen('daytime', $self->country)
1693 || $self->ut_phonen('night', $self->country)
1694 || $self->ut_phonen('fax', $self->country)
1695 || $self->ut_zip('zip', $self->country)
1697 return $error if $error;
1699 if ( $conf->exists('cust_main-require_phone')
1700 && ! length($self->daytime) && ! length($self->night)
1703 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1705 : FS::Msgcat::_gettext('daytime');
1706 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1708 : FS::Msgcat::_gettext('night');
1710 return "$daytime_label or $night_label is required"
1714 if ( $self->has_ship_address
1715 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1716 $self->addr_fields )
1720 $self->ut_name('ship_last')
1721 || $self->ut_name('ship_first')
1722 || $self->ut_textn('ship_company')
1723 || $self->ut_text('ship_address1')
1724 || $self->ut_textn('ship_address2')
1725 || $self->ut_text('ship_city')
1726 || $self->ut_textn('ship_county')
1727 || $self->ut_textn('ship_state')
1728 || $self->ut_country('ship_country')
1730 return $error if $error;
1732 #false laziness with above
1733 unless ( qsearchs('cust_main_county', {
1734 'country' => $self->ship_country,
1737 return "Unknown ship_state/ship_county/ship_country: ".
1738 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1739 unless qsearch('cust_main_county',{
1740 'state' => $self->ship_state,
1741 'county' => $self->ship_county,
1742 'country' => $self->ship_country,
1748 $self->ut_phonen('ship_daytime', $self->ship_country)
1749 || $self->ut_phonen('ship_night', $self->ship_country)
1750 || $self->ut_phonen('ship_fax', $self->ship_country)
1751 || $self->ut_zip('ship_zip', $self->ship_country)
1753 return $error if $error;
1755 return "Unit # is required."
1756 if $self->ship_address2 =~ /^\s*$/
1757 && $conf->exists('cust_main-require_address2');
1759 } else { # ship_ info eq billing info, so don't store dup info in database
1761 $self->setfield("ship_$_", '')
1762 foreach $self->addr_fields;
1764 return "Unit # is required."
1765 if $self->address2 =~ /^\s*$/
1766 && $conf->exists('cust_main-require_address2');
1770 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1771 # or return "Illegal payby: ". $self->payby;
1773 FS::payby->can_payby($self->table, $self->payby)
1774 or return "Illegal payby: ". $self->payby;
1776 $error = $self->ut_numbern('paystart_month')
1777 || $self->ut_numbern('paystart_year')
1778 || $self->ut_numbern('payissue')
1779 || $self->ut_textn('paytype')
1781 return $error if $error;
1783 if ( $self->payip eq '' ) {
1786 $error = $self->ut_ip('payip');
1787 return $error if $error;
1790 # If it is encrypted and the private key is not availaible then we can't
1791 # check the credit card.
1792 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1794 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1796 my $payinfo = $self->payinfo;
1797 $payinfo =~ s/\D//g;
1798 $payinfo =~ /^(\d{13,16})$/
1799 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1801 $self->payinfo($payinfo);
1803 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1805 return gettext('unknown_card_type')
1806 if $self->payinfo !~ /^99\d{14}$/ #token
1807 && cardtype($self->payinfo) eq "Unknown";
1809 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1811 return 'Banned credit card: banned on '.
1812 time2str('%a %h %o at %r', $ban->_date).
1813 ' by '. $ban->otaker.
1814 ' (ban# '. $ban->bannum. ')';
1817 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1818 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1819 $self->paycvv =~ /^(\d{4})$/
1820 or return "CVV2 (CID) for American Express cards is four digits.";
1823 $self->paycvv =~ /^(\d{3})$/
1824 or return "CVV2 (CVC2/CID) is three digits.";
1831 my $cardtype = cardtype($payinfo);
1832 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1834 return "Start date or issue number is required for $cardtype cards"
1835 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1837 return "Start month must be between 1 and 12"
1838 if $self->paystart_month
1839 and $self->paystart_month < 1 || $self->paystart_month > 12;
1841 return "Start year must be 1990 or later"
1842 if $self->paystart_year
1843 and $self->paystart_year < 1990;
1845 return "Issue number must be beween 1 and 99"
1847 and $self->payissue < 1 || $self->payissue > 99;
1850 $self->paystart_month('');
1851 $self->paystart_year('');
1852 $self->payissue('');
1855 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1857 my $payinfo = $self->payinfo;
1858 $payinfo =~ s/[^\d\@]//g;
1859 if ( $conf->exists('echeck-nonus') ) {
1860 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1861 $payinfo = "$1\@$2";
1863 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1864 $payinfo = "$1\@$2";
1866 $self->payinfo($payinfo);
1869 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1871 return 'Banned ACH account: banned on '.
1872 time2str('%a %h %o at %r', $ban->_date).
1873 ' by '. $ban->otaker.
1874 ' (ban# '. $ban->bannum. ')';
1877 } elsif ( $self->payby eq 'LECB' ) {
1879 my $payinfo = $self->payinfo;
1880 $payinfo =~ s/\D//g;
1881 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1883 $self->payinfo($payinfo);
1886 } elsif ( $self->payby eq 'BILL' ) {
1888 $error = $self->ut_textn('payinfo');
1889 return "Illegal P.O. number: ". $self->payinfo if $error;
1892 } elsif ( $self->payby eq 'COMP' ) {
1894 my $curuser = $FS::CurrentUser::CurrentUser;
1895 if ( ! $self->custnum
1896 && ! $curuser->access_right('Complimentary customer')
1899 return "You are not permitted to create complimentary accounts."
1902 $error = $self->ut_textn('payinfo');
1903 return "Illegal comp account issuer: ". $self->payinfo if $error;
1906 } elsif ( $self->payby eq 'PREPAY' ) {
1908 my $payinfo = $self->payinfo;
1909 $payinfo =~ s/\W//g; #anything else would just confuse things
1910 $self->payinfo($payinfo);
1911 $error = $self->ut_alpha('payinfo');
1912 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1913 return "Unknown prepayment identifier"
1914 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1919 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1920 return "Expiration date required"
1921 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1925 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1926 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1927 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1928 ( $m, $y ) = ( $2, "19$1" );
1929 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1930 ( $m, $y ) = ( $3, "20$2" );
1932 return "Illegal expiration date: ". $self->paydate;
1934 $self->paydate("$y-$m-01");
1935 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1936 return gettext('expired_card')
1938 && !$ignore_expired_card
1939 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1942 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1943 ( ! $conf->exists('require_cardname')
1944 || $self->payby !~ /^(CARD|DCRD)$/ )
1946 $self->payname( $self->first. " ". $self->getfield('last') );
1948 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1949 or return gettext('illegal_name'). " payname: ". $self->payname;
1953 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1954 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1958 $self->otaker(getotaker) unless $self->otaker;
1960 warn "$me check AFTER: \n". $self->_dump
1963 $self->SUPER::check;
1968 Returns a list of fields which have ship_ duplicates.
1973 qw( last first company
1974 address1 address2 city county state zip country
1979 =item has_ship_address
1981 Returns true if this customer record has a separate shipping address.
1985 sub has_ship_address {
1987 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1992 Returns a list of key/value pairs, with the following keys: address1, adddress2,
1993 city, county, state, zip, country. The shipping address is used if present.
1997 #geocode? dependent on tax-ship_address config, not available in cust_location
1998 #mostly. not yet then.
2002 my $prefix = $self->has_ship_address ? 'ship_' : '';
2004 map { $_ => $self->get($prefix.$_) }
2005 qw( address1 address2 city county state zip country geocode );
2006 #fields that cust_location has
2009 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2011 Returns all packages (see L<FS::cust_pkg>) for this customer.
2017 my $extra_qsearch = ref($_[0]) ? shift : {};
2019 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
2022 if ( $self->{'_pkgnum'} ) {
2023 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2025 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2028 sort sort_packages @cust_pkg;
2033 Synonym for B<all_pkgs>.
2038 shift->all_pkgs(@_);
2043 Returns all locations (see L<FS::cust_location>) for this customer.
2049 qsearch('cust_location', { 'custnum' => $self->custnum } );
2052 =item location_label [ OPTION => VALUE ... ]
2054 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2062 used to separate the address elements (defaults to ', ')
2064 =item escape_function
2066 a callback used for escaping the text of the address elements
2072 # false laziness with FS::cust_location::line
2074 sub location_label {
2078 my $separator = $opt{join_string} || ', ';
2079 my $escape = $opt{escape_function} || sub{ shift };
2081 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2082 my $prefix = length($self->ship_last) ? 'ship_' : '';
2085 foreach (qw ( address1 address2 ) ) {
2086 my $method = "$prefix$_";
2087 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2092 foreach (qw ( city county state zip ) ) {
2093 my $method = "$prefix$_";
2094 if ( $self->$method ) {
2095 $line .= ' (' if $method eq 'county';
2096 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2097 $line .= ' )' if $method eq 'county';
2101 $line .= $separator. &$escape(code2country($self->country))
2102 if $self->country ne $cydefault;
2107 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2109 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2113 sub ncancelled_pkgs {
2115 my $extra_qsearch = ref($_[0]) ? shift : {};
2117 return $self->num_ncancelled_pkgs unless wantarray;
2120 if ( $self->{'_pkgnum'} ) {
2122 warn "$me ncancelled_pkgs: returning cached objects"
2125 @cust_pkg = grep { ! $_->getfield('cancel') }
2126 values %{ $self->{'_pkgnum'}->cache };
2130 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2131 $self->custnum. "\n"
2134 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2136 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2140 sort sort_packages @cust_pkg;
2146 my $extra_qsearch = ref($_[0]) ? shift : {};
2148 $extra_qsearch->{'select'} ||= '*';
2149 $extra_qsearch->{'select'} .=
2150 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2154 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2159 'table' => 'cust_pkg',
2160 'hashref' => { 'custnum' => $self->custnum },
2165 # This should be generalized to use config options to determine order.
2168 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2169 return $locationsort if $locationsort;
2171 if ( $a->get('cancel') xor $b->get('cancel') ) {
2172 return -1 if $b->get('cancel');
2173 return 1 if $a->get('cancel');
2174 #shouldn't get here...
2177 my $a_num_cust_svc = $a->num_cust_svc;
2178 my $b_num_cust_svc = $b->num_cust_svc;
2179 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2180 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2181 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2182 my @a_cust_svc = $a->cust_svc;
2183 my @b_cust_svc = $b->cust_svc;
2184 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2189 =item suspended_pkgs
2191 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2195 sub suspended_pkgs {
2197 grep { $_->susp } $self->ncancelled_pkgs;
2200 =item unflagged_suspended_pkgs
2202 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2203 customer (thouse packages without the `manual_flag' set).
2207 sub unflagged_suspended_pkgs {
2209 return $self->suspended_pkgs
2210 unless dbdef->table('cust_pkg')->column('manual_flag');
2211 grep { ! $_->manual_flag } $self->suspended_pkgs;
2214 =item unsuspended_pkgs
2216 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2221 sub unsuspended_pkgs {
2223 grep { ! $_->susp } $self->ncancelled_pkgs;
2226 =item next_bill_date
2228 Returns the next date this customer will be billed, as a UNIX timestamp, or
2229 undef if no active package has a next bill date.
2233 sub next_bill_date {
2235 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2238 =item num_cancelled_pkgs
2240 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2245 sub num_cancelled_pkgs {
2246 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2249 sub num_ncancelled_pkgs {
2250 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2254 my( $self ) = shift;
2255 my $sql = scalar(@_) ? shift : '';
2256 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2257 my $sth = dbh->prepare(
2258 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2259 ) or die dbh->errstr;
2260 $sth->execute($self->custnum) or die $sth->errstr;
2261 $sth->fetchrow_arrayref->[0];
2266 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2267 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2268 on success or a list of errors.
2274 grep { $_->unsuspend } $self->suspended_pkgs;
2279 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2281 Returns a list: an empty list on success or a list of errors.
2287 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2290 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2292 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2293 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2294 of a list of pkgparts; the hashref has the following keys:
2298 =item pkgparts - listref of pkgparts
2300 =item (other options are passed to the suspend method)
2305 Returns a list: an empty list on success or a list of errors.
2309 sub suspend_if_pkgpart {
2311 my (@pkgparts, %opt);
2312 if (ref($_[0]) eq 'HASH'){
2313 @pkgparts = @{$_[0]{pkgparts}};
2318 grep { $_->suspend(%opt) }
2319 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2320 $self->unsuspended_pkgs;
2323 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2325 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2326 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2327 instead of a list of pkgparts; the hashref has the following keys:
2331 =item pkgparts - listref of pkgparts
2333 =item (other options are passed to the suspend method)
2337 Returns a list: an empty list on success or a list of errors.
2341 sub suspend_unless_pkgpart {
2343 my (@pkgparts, %opt);
2344 if (ref($_[0]) eq 'HASH'){
2345 @pkgparts = @{$_[0]{pkgparts}};
2350 grep { $_->suspend(%opt) }
2351 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2352 $self->unsuspended_pkgs;
2355 =item cancel [ OPTION => VALUE ... ]
2357 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2359 Available options are:
2363 =item quiet - can be set true to supress email cancellation notices.
2365 =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.
2367 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2369 =item nobill - can be set true to skip billing if it might otherwise be done.
2373 Always returns a list: an empty list on success or a list of errors.
2377 # nb that dates are not specified as valid options to this method
2380 my( $self, %opt ) = @_;
2382 warn "$me cancel called on customer ". $self->custnum. " with options ".
2383 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2386 return ( 'access denied' )
2387 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2389 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2391 #should try decryption (we might have the private key)
2392 # and if not maybe queue a job for the server that does?
2393 return ( "Can't (yet) ban encrypted credit cards" )
2394 if $self->is_encrypted($self->payinfo);
2396 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2397 my $error = $ban->insert;
2398 return ( $error ) if $error;
2402 my @pkgs = $self->ncancelled_pkgs;
2404 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2406 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2407 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2411 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2412 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2415 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2418 sub _banned_pay_hashref {
2429 'payby' => $payby2ban{$self->payby},
2430 'payinfo' => md5_base64($self->payinfo),
2431 #don't ever *search* on reason! #'reason' =>
2437 Returns all notes (see L<FS::cust_main_note>) for this customer.
2444 qsearch( 'cust_main_note',
2445 { 'custnum' => $self->custnum },
2447 'ORDER BY _DATE DESC'
2453 Returns the agent (see L<FS::agent>) for this customer.
2459 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2464 Returns the customer class, as an FS::cust_class object, or the empty string
2465 if there is no customer class.
2471 if ( $self->classnum ) {
2472 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2480 Returns the customer category name, or the empty string if there is no customer
2487 my $cust_class = $self->cust_class;
2489 ? $cust_class->categoryname
2495 Returns the customer class name, or the empty string if there is no customer
2502 my $cust_class = $self->cust_class;
2504 ? $cust_class->classname
2509 =item bill_and_collect
2511 Cancels and suspends any packages due, generates bills, applies payments and
2512 credits, and applies collection events to run cards, send bills and notices,
2515 By default, warns on errors and continues with the next operation (but see the
2516 "fatal" flag below).
2518 Options are passed as name-value pairs. Currently available options are:
2524 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:
2528 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2532 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.
2536 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2540 If set true, re-charges setup fees.
2544 If set any errors prevent subsequent operations from continusing. If set
2545 specifically to "return", returns the error (or false, if there is no error).
2546 Any other true value causes errors to die.
2550 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)
2554 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2555 options of those methods are also available.
2559 sub bill_and_collect {
2560 my( $self, %options ) = @_;
2564 #$options{actual_time} not $options{time} because freeside-daily -d is for
2565 #pre-printing invoices
2567 $options{'actual_time'} ||= time;
2569 $error = $self->cancel_expired_pkgs( $options{actual_time} );
2571 $error = "Error expiring custnum ". $self->custnum. ": $error";
2572 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2573 elsif ( $options{fatal} ) { die $error; }
2574 else { warn $error; }
2577 $error = $self->suspend_adjourned_pkgs( $options{actual_time} );
2579 $error = "Error adjourning custnum ". $self->custnum. ": $error";
2580 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2581 elsif ( $options{fatal} ) { die $error; }
2582 else { warn $error; }
2585 $error = $self->bill( %options );
2587 $error = "Error billing custnum ". $self->custnum. ": $error";
2588 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2589 elsif ( $options{fatal} ) { die $error; }
2590 else { warn $error; }
2593 $error = $self->apply_payments_and_credits;
2595 $error = "Error applying custnum ". $self->custnum. ": $error";
2596 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2597 elsif ( $options{fatal} ) { die $error; }
2598 else { warn $error; }
2601 unless ( $conf->exists('cancelled_cust-noevents')
2602 && ! $self->num_ncancelled_pkgs
2604 $error = $self->collect( %options );
2606 $error = "Error collecting custnum ". $self->custnum. ": $error";
2607 if ($options{fatal} && $options{fatal} eq 'return') { return $error; }
2608 elsif ($options{fatal} ) { die $error; }
2609 else { warn $error; }
2617 sub cancel_expired_pkgs {
2618 my ( $self, $time, %options ) = @_;
2620 my @cancel_pkgs = $self->ncancelled_pkgs( {
2621 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2626 foreach my $cust_pkg ( @cancel_pkgs ) {
2627 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2628 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2629 'reason_otaker' => $cpr->otaker
2633 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2636 scalar(@errors) ? join(' / ', @errors) : '';
2640 sub suspend_adjourned_pkgs {
2641 my ( $self, $time, %options ) = @_;
2643 my @susp_pkgs = $self->ncancelled_pkgs( {
2645 " AND ( susp IS NULL OR susp = 0 )
2646 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
2647 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2652 #only because there's no SQL test for is_prepaid :/
2654 grep { ( $_->part_pkg->is_prepaid
2659 && $_->adjourn <= $time
2667 foreach my $cust_pkg ( @susp_pkgs ) {
2668 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2669 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2670 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2671 'reason_otaker' => $cpr->otaker
2675 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2678 scalar(@errors) ? join(' / ', @errors) : '';
2684 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2685 conjunction with the collect method by calling B<bill_and_collect>.
2687 If there is an error, returns the error, otherwise returns false.
2689 Options are passed as name-value pairs. Currently available options are:
2695 If set true, re-charges setup fees.
2699 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:
2703 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2707 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2709 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2713 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2717 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.
2721 This boolean value informs the us that the package is being cancelled. This
2722 typically might mean not charging the normal recurring fee but only usage
2723 fees since the last billing. Setup charges may be charged. Not all package
2724 plans support this feature (they tend to charge 0).
2728 Optional terms to be printed on this invoice. Otherwise, customer-specific
2729 terms or the default terms are used.
2736 my( $self, %options ) = @_;
2737 return '' if $self->payby eq 'COMP';
2738 warn "$me bill customer ". $self->custnum. "\n"
2741 my $time = $options{'time'} || time;
2742 my $invoice_time = $options{'invoice_time'} || $time;
2744 $options{'not_pkgpart'} ||= {};
2745 $options{'not_pkgpart'} = { map { $_ => 1 }
2746 split(/\s*,\s*/, $options{'not_pkgpart'})
2748 unless ref($options{'not_pkgpart'});
2750 local $SIG{HUP} = 'IGNORE';
2751 local $SIG{INT} = 'IGNORE';
2752 local $SIG{QUIT} = 'IGNORE';
2753 local $SIG{TERM} = 'IGNORE';
2754 local $SIG{TSTP} = 'IGNORE';
2755 local $SIG{PIPE} = 'IGNORE';
2757 my $oldAutoCommit = $FS::UID::AutoCommit;
2758 local $FS::UID::AutoCommit = 0;
2761 $self->select_for_update; #mutex
2763 my $error = $self->do_cust_event(
2764 'debug' => ( $options{'debug'} || 0 ),
2765 'time' => $invoice_time,
2766 'check_freq' => $options{'check_freq'},
2767 'stage' => 'pre-bill',
2770 $dbh->rollback if $oldAutoCommit;
2774 #keep auto-charge and non-auto-charge line items separate
2775 my @passes = ( '', 'no_auto' );
2777 my %cust_bill_pkg = map { $_ => [] } @passes;
2780 # find the packages which are due for billing, find out how much they are
2781 # & generate invoice database.
2784 my %total_setup = map { my $z = 0; $_ => \$z; } @passes;
2785 my %total_recur = map { my $z = 0; $_ => \$z; } @passes;
2787 my %taxlisthash = map { $_ => {} } @passes;
2789 my @precommit_hooks = ();
2791 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
2792 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2794 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2796 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2798 #? to avoid use of uninitialized value errors... ?
2799 $cust_pkg->setfield('bill', '')
2800 unless defined($cust_pkg->bill);
2802 #my $part_pkg = $cust_pkg->part_pkg;
2804 my $real_pkgpart = $cust_pkg->pkgpart;
2805 my %hash = $cust_pkg->hash;
2807 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2809 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2811 my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
2814 $self->_make_lines( 'part_pkg' => $part_pkg,
2815 'cust_pkg' => $cust_pkg,
2816 'precommit_hooks' => \@precommit_hooks,
2817 'line_items' => $cust_bill_pkg{$pass},
2818 'setup' => $total_setup{$pass},
2819 'recur' => $total_recur{$pass},
2820 'tax_matrix' => $taxlisthash{$pass},
2822 'real_pkgpart' => $real_pkgpart,
2823 'options' => \%options,
2826 $dbh->rollback if $oldAutoCommit;
2830 } #foreach my $part_pkg
2832 } #foreach my $cust_pkg
2834 #if the customer isn't on an automatic payby, everything can go on a single
2836 #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
2837 #merge everything into one list
2840 foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
2842 my @cust_bill_pkg = @{ $cust_bill_pkg{$pass} };
2844 next unless @cust_bill_pkg; #don't create an invoice w/o line items
2846 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2847 !$conf->exists('postal_invoice-recurring_only')
2851 my $postal_pkg = $self->charge_postal_fee();
2852 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2854 $dbh->rollback if $oldAutoCommit;
2855 return "can't charge postal invoice fee for customer ".
2856 $self->custnum. ": $postal_pkg";
2858 } elsif ( $postal_pkg ) {
2860 my $real_pkgpart = $postal_pkg->pkgpart;
2861 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2862 my %postal_options = %options;
2863 delete $postal_options{cancel};
2865 $self->_make_lines( 'part_pkg' => $part_pkg,
2866 'cust_pkg' => $postal_pkg,
2867 'precommit_hooks' => \@precommit_hooks,
2868 'line_items' => \@cust_bill_pkg,
2869 'setup' => $total_setup{$pass},
2870 'recur' => $total_recur{$pass},
2871 'tax_matrix' => $taxlisthash{$pass},
2873 'real_pkgpart' => $real_pkgpart,
2874 'options' => \%postal_options,
2877 $dbh->rollback if $oldAutoCommit;
2886 my $listref_or_error =
2887 $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
2889 unless ( ref( $listref_or_error ) ) {
2890 $dbh->rollback if $oldAutoCommit;
2891 return $listref_or_error;
2894 foreach my $taxline ( @$listref_or_error ) {
2895 ${ $total_setup{$pass} } =
2896 sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
2897 push @cust_bill_pkg, $taxline;
2900 #add tax adjustments
2901 warn "adding tax adjustments...\n" if $DEBUG > 2;
2902 foreach my $cust_tax_adjustment (
2903 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
2909 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
2911 my $itemdesc = $cust_tax_adjustment->taxname;
2912 $itemdesc = '' if $itemdesc eq 'Tax';
2914 push @cust_bill_pkg, new FS::cust_bill_pkg {
2920 'itemdesc' => $itemdesc,
2921 'itemcomment' => $cust_tax_adjustment->comment,
2922 'cust_tax_adjustment' => $cust_tax_adjustment,
2923 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
2928 my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
2930 my @cust_bill = $self->cust_bill;
2931 my $balance = $self->balance;
2932 my $previous_balance = scalar(@cust_bill)
2933 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
2936 $previous_balance += $cust_bill[$#cust_bill]->charged
2937 if scalar(@cust_bill);
2938 #my $balance_adjustments =
2939 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
2941 #create the new invoice
2942 my $cust_bill = new FS::cust_bill ( {
2943 'custnum' => $self->custnum,
2944 '_date' => ( $invoice_time ),
2945 'charged' => $charged,
2946 'billing_balance' => $balance,
2947 'previous_balance' => $previous_balance,
2948 'invoice_terms' => $options{'invoice_terms'},
2950 $error = $cust_bill->insert;
2952 $dbh->rollback if $oldAutoCommit;
2953 return "can't create invoice for customer #". $self->custnum. ": $error";
2956 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2957 $cust_bill_pkg->invnum($cust_bill->invnum);
2958 my $error = $cust_bill_pkg->insert;
2960 $dbh->rollback if $oldAutoCommit;
2961 return "can't create invoice line item: $error";
2965 } #foreach my $pass ( keys %cust_bill_pkg )
2967 foreach my $hook ( @precommit_hooks ) {
2969 &{$hook}; #($self) ?
2972 $dbh->rollback if $oldAutoCommit;
2973 return "$@ running precommit hook $hook\n";
2977 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2981 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
2983 This is a weird one. Perhaps it should not even be exposed.
2985 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
2986 Usually used internally by bill method B<bill>.
2988 If there is an error, returns the error, otherwise returns reference to a
2989 list of line items suitable for insertion.
2995 An array ref of the line items being billed.
2999 A strange beast. The keys to this hash are internal identifiers consisting
3000 of the name of the tax object type, a space, and its unique identifier ( e.g.
3001 'cust_main_county 23' ). The values of the hash are listrefs. The first
3002 item in the list is the tax object. The remaining items are either line
3003 items or floating point values (currency amounts).
3005 The taxes are calculated on this entity. Calculated exemption records are
3006 transferred to the LINEITEMREF items on the assumption that they are related.
3012 This specifies the date appearing on the associated invoice. Some
3013 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
3018 sub calculate_taxes {
3019 my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
3021 my @tax_line_items = ();
3023 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
3025 # keys are tax names (as printed on invoices / itemdesc )
3026 # values are listrefs of taxlisthash keys (internal identifiers)
3029 # keys are taxlisthash keys (internal identifiers)
3030 # values are (cumulative) amounts
3033 # keys are taxlisthash keys (internal identifiers)
3034 # values are listrefs of cust_bill_pkg_tax_location hashrefs
3035 my %tax_location = ();
3037 # keys are taxlisthash keys (internal identifiers)
3038 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
3039 my %tax_rate_location = ();
3041 foreach my $tax ( keys %$taxlisthash ) {
3042 my $tax_object = shift @{ $taxlisthash->{$tax} };
3043 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
3044 warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
3045 my $hashref_or_error =
3046 $tax_object->taxline( $taxlisthash->{$tax},
3047 'custnum' => $self->custnum,
3048 'invoice_time' => $invoice_time
3050 return $hashref_or_error unless ref($hashref_or_error);
3052 unshift @{ $taxlisthash->{$tax} }, $tax_object;
3054 my $name = $hashref_or_error->{'name'};
3055 my $amount = $hashref_or_error->{'amount'};
3057 #warn "adding $amount as $name\n";
3058 $taxname{ $name } ||= [];
3059 push @{ $taxname{ $name } }, $tax;
3061 $tax{ $tax } += $amount;
3063 $tax_location{ $tax } ||= [];
3064 if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
3065 push @{ $tax_location{ $tax } },
3067 'taxnum' => $tax_object->taxnum,
3068 'taxtype' => ref($tax_object),
3069 'pkgnum' => $tax_object->get('pkgnum'),
3070 'locationnum' => $tax_object->get('locationnum'),
3071 'amount' => sprintf('%.2f', $amount ),
3075 $tax_rate_location{ $tax } ||= [];
3076 if ( ref($tax_object) eq 'FS::tax_rate' ) {
3077 my $taxratelocationnum =
3078 $tax_object->tax_rate_location->taxratelocationnum;
3079 push @{ $tax_rate_location{ $tax } },
3081 'taxnum' => $tax_object->taxnum,
3082 'taxtype' => ref($tax_object),
3083 'amount' => sprintf('%.2f', $amount ),
3084 'locationtaxid' => $tax_object->location,
3085 'taxratelocationnum' => $taxratelocationnum,
3091 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
3092 my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
3093 foreach my $tax ( keys %$taxlisthash ) {
3094 foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
3095 next unless ref($_) eq 'FS::cust_bill_pkg';
3097 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
3098 splice( @{ $_->_cust_tax_exempt_pkg } );
3102 #consolidate and create tax line items
3103 warn "consolidating and generating...\n" if $DEBUG > 2;
3104 foreach my $taxname ( keys %taxname ) {
3107 my @cust_bill_pkg_tax_location = ();
3108 my @cust_bill_pkg_tax_rate_location = ();
3109 warn "adding $taxname\n" if $DEBUG > 1;
3110 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
3111 next if $seen{$taxitem}++;
3112 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
3113 $tax += $tax{$taxitem};
3114 push @cust_bill_pkg_tax_location,
3115 map { new FS::cust_bill_pkg_tax_location $_ }
3116 @{ $tax_location{ $taxitem } };
3117 push @cust_bill_pkg_tax_rate_location,
3118 map { new FS::cust_bill_pkg_tax_rate_location $_ }
3119 @{ $tax_rate_location{ $taxitem } };
3123 $tax = sprintf('%.2f', $tax );
3125 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
3131 if ( $pkg_category and
3132 $conf->config('invoice_latexsummary') ||
3133 $conf->config('invoice_htmlsummary')
3137 my %hash = ( 'section' => $pkg_category->categoryname );
3138 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3142 push @tax_line_items, new FS::cust_bill_pkg {
3148 'itemdesc' => $taxname,
3149 'display' => \@display,
3150 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3151 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
3160 my ($self, %params) = @_;
3162 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
3163 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
3164 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
3165 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
3166 my $total_setup = $params{setup} or die "no setup accumulator specified";
3167 my $total_recur = $params{recur} or die "no recur accumulator specified";
3168 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
3169 my $time = $params{'time'} or die "no time specified";
3170 my (%options) = %{$params{options}};
3173 my $real_pkgpart = $params{real_pkgpart};
3174 my %hash = $cust_pkg->hash;
3175 my $old_cust_pkg = new FS::cust_pkg \%hash;
3181 $cust_pkg->pkgpart($part_pkg->pkgpart);
3189 if ( $options{'resetup'}
3190 || ( ! $cust_pkg->setup
3191 && ( ! $cust_pkg->start_date
3192 || $cust_pkg->start_date <= $time
3194 && ( ! $conf->exists('disable_setup_suspended_pkgs')
3195 || ( $conf->exists('disable_setup_suspended_pkgs') &&
3196 ! $cust_pkg->getfield('susp')
3203 warn " bill setup\n" if $DEBUG > 1;
3206 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
3207 return "$@ running calc_setup for $cust_pkg\n"
3210 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
3212 $cust_pkg->setfield('setup', $time)
3213 unless $cust_pkg->setup;
3214 #do need it, but it won't get written to the db
3215 #|| $cust_pkg->pkgpart != $real_pkgpart;
3217 $cust_pkg->setfield('start_date', '')
3218 if $cust_pkg->start_date;
3223 # bill recurring fee
3226 #XXX unit stuff here too
3230 if ( ! $cust_pkg->get('susp')
3231 and ! $cust_pkg->get('start_date')
3232 and ( $part_pkg->getfield('freq') ne '0'
3233 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3235 || ( $part_pkg->plan eq 'voip_cdr'
3236 && $part_pkg->option('bill_every_call')
3238 || ( $options{cancel} )
3241 # XXX should this be a package event? probably. events are called
3242 # at collection time at the moment, though...
3243 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
3244 if $part_pkg->can('reset_usage');
3245 #don't want to reset usage just cause we want a line item??
3246 #&& $part_pkg->pkgpart == $real_pkgpart;
3248 warn " bill recur\n" if $DEBUG > 1;
3251 # XXX shared with $recur_prog
3252 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
3256 #over two params! lets at least switch to a hashref for the rest...
3257 my $increment_next_bill = ( $part_pkg->freq ne '0'
3258 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3259 && !$options{cancel}
3261 my %param = ( 'precommit_hooks' => $precommit_hooks,
3262 'increment_next_bill' => $increment_next_bill,
3263 'discounts' => \@discounts,
3266 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
3267 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
3268 return "$@ running $method for $cust_pkg\n"
3271 if ( $increment_next_bill ) {
3273 my $next_bill = $part_pkg->add_freq($sdate);
3274 return "unparsable frequency: ". $part_pkg->freq
3275 if $next_bill == -1;
3277 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
3278 # only for figuring next bill date, nothing else, so, reset $sdate again
3280 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
3281 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
3282 $cust_pkg->last_bill($sdate);
3284 $cust_pkg->setfield('bill', $next_bill );
3290 warn "\$setup is undefined" unless defined($setup);
3291 warn "\$recur is undefined" unless defined($recur);
3292 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
3295 # If there's line items, create em cust_bill_pkg records
3296 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
3301 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
3302 # hmm.. and if just the options are modified in some weird price plan?
3304 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
3307 my $error = $cust_pkg->replace( $old_cust_pkg,
3308 'options' => { $cust_pkg->options },
3310 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
3311 if $error; #just in case
3314 $setup = sprintf( "%.2f", $setup );
3315 $recur = sprintf( "%.2f", $recur );
3316 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
3317 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3319 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3320 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3323 if ( $setup != 0 || $recur != 0 ) {
3325 warn " charges (setup=$setup, recur=$recur); adding line items\n"
3328 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3330 warn " adding customer package invoice detail: $_\n"
3331 foreach @cust_pkg_detail;
3333 push @details, @cust_pkg_detail;
3335 my $cust_bill_pkg = new FS::cust_bill_pkg {
3336 'pkgnum' => $cust_pkg->pkgnum,
3338 'unitsetup' => $unitsetup,
3340 'unitrecur' => $unitrecur,
3341 'quantity' => $cust_pkg->quantity,
3342 'details' => \@details,
3343 'discounts' => \@discounts,
3344 'hidden' => $part_pkg->hidden,
3347 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3348 $cust_bill_pkg->sdate( $hash{last_bill} );
3349 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
3350 $cust_bill_pkg->edate( $time ) if $options{cancel};
3351 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3352 $cust_bill_pkg->sdate( $sdate );
3353 $cust_bill_pkg->edate( $cust_pkg->bill );
3354 #$cust_bill_pkg->edate( $time ) if $options{cancel};
3357 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3358 unless $part_pkg->pkgpart == $real_pkgpart;
3360 $$total_setup += $setup;
3361 $$total_recur += $recur;
3368 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3369 return $error if $error;
3371 push @$cust_bill_pkgs, $cust_bill_pkg;
3373 } #if $setup != 0 || $recur != 0
3383 my $part_pkg = shift;
3384 my $taxlisthash = shift;
3385 my $cust_bill_pkg = shift;
3386 my $cust_pkg = shift;
3387 my $invoice_time = shift;
3388 my $real_pkgpart = shift;
3389 my $options = shift;
3391 my %cust_bill_pkg = ();
3395 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3396 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3397 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3398 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3400 if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3402 if ( $conf->exists('enable_taxproducts')
3403 && ( scalar($part_pkg->part_pkg_taxoverride)
3404 || $part_pkg->has_taxproduct
3409 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3410 return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3413 foreach my $class (@classes) {
3414 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3415 return $err_or_ref unless ref($err_or_ref);
3416 $taxes{$class} = $err_or_ref;
3419 unless (exists $taxes{''}) {
3420 my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3421 return $err_or_ref unless ref($err_or_ref);
3422 $taxes{''} = $err_or_ref;
3427 my @loc_keys = qw( city county state country );
3429 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3430 my $cust_location = $cust_pkg->cust_location;
3431 %taxhash = map { $_ => $cust_location->$_() } @loc_keys;
3434 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3437 %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3440 $taxhash{'taxclass'} = $part_pkg->taxclass;
3443 my %taxhash_elim = %taxhash;
3444 my @elim = qw( city county state );
3447 #first try a match with taxclass
3448 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3450 if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
3451 #then try a match without taxclass
3452 my %no_taxclass = %taxhash_elim;
3453 $no_taxclass{ 'taxclass' } = '';
3454 @taxes = qsearch( 'cust_main_county', \%no_taxclass );
3457 $taxhash_elim{ shift(@elim) } = '';
3459 } while ( !scalar(@taxes) && scalar(@elim) );
3461 @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3463 if $self->cust_main_exemption; #just to be safe
3465 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3467 $_->set('pkgnum', $cust_pkg->pkgnum );
3468 $_->set('locationnum', $cust_pkg->locationnum );
3472 $taxes{''} = [ @taxes ];
3473 $taxes{'setup'} = [ @taxes ];
3474 $taxes{'recur'} = [ @taxes ];
3475 $taxes{$_} = [ @taxes ] foreach (@classes);
3477 # # maybe eliminate this entirely, along with all the 0% records
3478 # unless ( @taxes ) {
3480 # "fatal: can't find tax rate for state/county/country/taxclass ".
3481 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
3484 } #if $conf->exists('enable_taxproducts') ...
3489 my $separate = $conf->exists('separate_usage');
3490 my $usage_mandate = $cust_pkg->part_pkg->option('usage_mandate', 'Hush!');
3491 if ( $separate || $cust_bill_pkg->hidden || $usage_mandate ) {
3493 my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3494 my %hash = $cust_bill_pkg->hidden # maybe for all bill linked?
3495 ? ( 'section' => $temp_pkg->part_pkg->categoryname )
3498 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
3499 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
3501 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3502 push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3504 push @display, new FS::cust_bill_pkg_display
3507 ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3511 if ($separate && $section && $summary) {
3512 push @display, new FS::cust_bill_pkg_display { type => 'U',
3517 if ($usage_mandate || $section && $summary) {
3518 $hash{post_total} = 'Y';
3521 $hash{section} = $section if ($separate || $usage_mandate);
3522 push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3525 $cust_bill_pkg->set('display', \@display);
3527 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3528 foreach my $key (keys %tax_cust_bill_pkg) {
3529 my @taxes = @{ $taxes{$key} || [] };
3530 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3532 my %localtaxlisthash = ();
3533 foreach my $tax ( @taxes ) {
3535 my $taxname = ref( $tax ). ' '. $tax->taxnum;
3536 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3537 # ' locationnum'. $cust_pkg->locationnum
3538 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3540 $taxlisthash->{ $taxname } ||= [ $tax ];
3541 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
3543 $localtaxlisthash{ $taxname } ||= [ $tax ];
3544 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
3548 warn "finding taxed taxes...\n" if $DEBUG > 2;
3549 foreach my $tax ( keys %localtaxlisthash ) {
3550 my $tax_object = shift @{ $localtaxlisthash{$tax} };
3551 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3553 next unless $tax_object->can('tax_on_tax');
3555 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3556 my $totname = ref( $tot ). ' '. $tot->taxnum;
3558 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3560 next unless exists( $localtaxlisthash{ $totname } ); # only increase
3562 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3563 my $hashref_or_error =
3564 $tax_object->taxline( $localtaxlisthash{$tax},
3565 'custnum' => $self->custnum,
3566 'invoice_time' => $invoice_time,
3568 return $hashref_or_error
3569 unless ref($hashref_or_error);
3571 $taxlisthash->{ $totname } ||= [ $tot ];
3572 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
3584 my $part_pkg = shift;
3588 my $geocode = $self->geocode('cch');
3590 my @taxclassnums = map { $_->taxclassnum }
3591 $part_pkg->part_pkg_taxoverride($class);
3593 unless (@taxclassnums) {
3594 @taxclassnums = map { $_->taxclassnum }
3595 grep { $_->taxable eq 'Y' }
3596 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3598 warn "Found taxclassnum values of ". join(',', @taxclassnums)
3603 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3605 @taxes = qsearch({ 'table' => 'tax_rate',
3606 'hashref' => { 'geocode' => $geocode, },
3607 'extra_sql' => $extra_sql,
3609 if scalar(@taxclassnums);
3611 warn "Found taxes ".
3612 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
3619 =item collect [ HASHREF | OPTION => VALUE ... ]
3621 (Attempt to) collect money for this customer's outstanding invoices (see
3622 L<FS::cust_bill>). Usually used after the bill method.
3624 Actions are now triggered by billing events; see L<FS::part_event> and the
3625 billing events web interface. Old-style invoice events (see
3626 L<FS::part_bill_event>) have been deprecated.
3628 If there is an error, returns the error, otherwise returns false.
3630 Options are passed as name-value pairs.
3632 Currently available options are:
3638 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.
3642 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3646 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3650 set true to surpress email card/ACH decline notices.
3654 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)
3660 # allows for one time override of normal customer billing method
3665 my( $self, %options ) = @_;
3666 my $invoice_time = $options{'invoice_time'} || time;
3669 local $SIG{HUP} = 'IGNORE';
3670 local $SIG{INT} = 'IGNORE';
3671 local $SIG{QUIT} = 'IGNORE';
3672 local $SIG{TERM} = 'IGNORE';
3673 local $SIG{TSTP} = 'IGNORE';
3674 local $SIG{PIPE} = 'IGNORE';
3676 my $oldAutoCommit = $FS::UID::AutoCommit;
3677 local $FS::UID::AutoCommit = 0;
3680 $self->select_for_update; #mutex
3683 my $balance = $self->balance;
3684 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3687 if ( exists($options{'retry_card'}) ) {
3688 carp 'retry_card option passed to collect is deprecated; use retry';
3689 $options{'retry'} ||= $options{'retry_card'};
3691 if ( exists($options{'retry'}) && $options{'retry'} ) {
3692 my $error = $self->retry_realtime;
3694 $dbh->rollback if $oldAutoCommit;
3699 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3701 #never want to roll back an event just because it returned an error
3702 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3704 $self->do_cust_event(
3705 'debug' => ( $options{'debug'} || 0 ),
3706 'time' => $invoice_time,
3707 'check_freq' => $options{'check_freq'},
3708 'stage' => 'collect',
3713 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3715 Runs billing events; see L<FS::part_event> and the billing events web
3718 If there is an error, returns the error, otherwise returns false.
3720 Options are passed as name-value pairs.
3722 Currently available options are:
3728 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.
3732 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3736 "collect" (the default) or "pre-bill"
3740 set true to surpress email card/ACH decline notices.
3744 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)
3750 # allows for one time override of normal customer billing method
3754 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3757 my( $self, %options ) = @_;
3758 my $time = $options{'time'} || time;
3761 local $SIG{HUP} = 'IGNORE';
3762 local $SIG{INT} = 'IGNORE';
3763 local $SIG{QUIT} = 'IGNORE';
3764 local $SIG{TERM} = 'IGNORE';
3765 local $SIG{TSTP} = 'IGNORE';
3766 local $SIG{PIPE} = 'IGNORE';
3768 my $oldAutoCommit = $FS::UID::AutoCommit;
3769 local $FS::UID::AutoCommit = 0;
3772 $self->select_for_update; #mutex
3775 my $balance = $self->balance;
3776 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
3779 # if ( exists($options{'retry_card'}) ) {
3780 # carp 'retry_card option passed to collect is deprecated; use retry';
3781 # $options{'retry'} ||= $options{'retry_card'};
3783 # if ( exists($options{'retry'}) && $options{'retry'} ) {
3784 # my $error = $self->retry_realtime;
3786 # $dbh->rollback if $oldAutoCommit;
3791 # false laziness w/pay_batch::import_results
3793 my $due_cust_event = $self->due_cust_event(
3794 'debug' => ( $options{'debug'} || 0 ),
3796 'check_freq' => $options{'check_freq'},
3797 'stage' => ( $options{'stage'} || 'collect' ),
3799 unless( ref($due_cust_event) ) {
3800 $dbh->rollback if $oldAutoCommit;
3801 return $due_cust_event;
3804 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3805 #never want to roll back an event just because it or a different one
3807 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3809 foreach my $cust_event ( @$due_cust_event ) {
3813 #re-eval event conditions (a previous event could have changed things)
3814 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
3815 #don't leave stray "new/locked" records around
3816 my $error = $cust_event->delete;
3817 return $error if $error;
3822 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
3823 warn " running cust_event ". $cust_event->eventnum. "\n"
3826 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
3827 if ( my $error = $cust_event->do_event() ) {
3828 #XXX wtf is this? figure out a proper dealio with return value
3840 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
3842 Inserts database records for and returns an ordered listref of new events due
3843 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
3844 events are due, an empty listref is returned. If there is an error, returns a
3845 scalar error message.
3847 To actually run the events, call each event's test_condition method, and if
3848 still true, call the event's do_event method.
3850 Options are passed as a hashref or as a list of name-value pairs. Available
3857 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.
3861 "collect" (the default) or "pre-bill"
3865 "Current time" for the events.
3869 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)
3873 Only return events for the specified eventtable (by default, events of all eventtables are returned)
3877 Explicitly pass the objects to be tested (typically used with eventtable).
3881 Set to true to return the objects, but not actually insert them into the
3888 sub due_cust_event {
3890 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
3893 #my $DEBUG = $opt{'debug'}
3894 local($DEBUG) = $opt{'debug'}
3895 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
3897 warn "$me due_cust_event called with options ".
3898 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
3901 $opt{'time'} ||= time;
3903 local $SIG{HUP} = 'IGNORE';
3904 local $SIG{INT} = 'IGNORE';
3905 local $SIG{QUIT} = 'IGNORE';
3906 local $SIG{TERM} = 'IGNORE';
3907 local $SIG{TSTP} = 'IGNORE';
3908 local $SIG{PIPE} = 'IGNORE';
3910 my $oldAutoCommit = $FS::UID::AutoCommit;
3911 local $FS::UID::AutoCommit = 0;
3914 $self->select_for_update #mutex
3915 unless $opt{testonly};
3918 # find possible events (initial search)
3921 my @cust_event = ();
3923 my @eventtable = $opt{'eventtable'}
3924 ? ( $opt{'eventtable'} )
3925 : FS::part_event->eventtables_runorder;
3927 foreach my $eventtable ( @eventtable ) {
3930 if ( $opt{'objects'} ) {
3932 @objects = @{ $opt{'objects'} };
3936 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
3937 @objects = ( $eventtable eq 'cust_main' )
3939 : ( $self->$eventtable() );
3943 my @e_cust_event = ();
3945 my $cross = "CROSS JOIN $eventtable";
3946 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
3947 unless $eventtable eq 'cust_main';
3949 foreach my $object ( @objects ) {
3951 #this first search uses the condition_sql magic for optimization.
3952 #the more possible events we can eliminate in this step the better
3954 my $cross_where = '';
3955 my $pkey = $object->primary_key;
3956 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
3958 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
3960 FS::part_event_condition->where_conditions_sql( $eventtable,
3961 'time'=>$opt{'time'}
3963 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
3965 $extra_sql = "AND $extra_sql" if $extra_sql;
3967 #here is the agent virtualization
3968 $extra_sql .= " AND ( part_event.agentnum IS NULL
3969 OR part_event.agentnum = ". $self->agentnum. ' )';
3971 $extra_sql .= " $order";
3973 warn "searching for events for $eventtable ". $object->$pkey. "\n"
3974 if $opt{'debug'} > 2;
3975 my @part_event = qsearch( {
3976 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
3977 'select' => 'part_event.*',
3978 'table' => 'part_event',
3979 'addl_from' => "$cross $join",
3980 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
3981 'eventtable' => $eventtable,
3984 'extra_sql' => "AND $cross_where $extra_sql",
3988 my $pkey = $object->primary_key;
3989 warn " ". scalar(@part_event).
3990 " possible events found for $eventtable ". $object->$pkey(). "\n";
3993 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
3997 warn " ". scalar(@e_cust_event).
3998 " subtotal possible cust events found for $eventtable\n"
4001 push @cust_event, @e_cust_event;
4005 warn " ". scalar(@cust_event).
4006 " total possible cust events found in initial search\n"
4014 $opt{stage} ||= 'collect';
4016 grep { my $stage = $_->part_event->event_stage;
4017 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
4027 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
4028 'stats_hashref' => \%unsat ),
4031 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
4034 warn " invalid conditions not eliminated with condition_sql:\n".
4035 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
4036 if keys %unsat && $DEBUG; # > 1;
4042 unless( $opt{testonly} ) {
4043 foreach my $cust_event ( @cust_event ) {
4045 my $error = $cust_event->insert();
4047 $dbh->rollback if $oldAutoCommit;
4054 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4060 warn " returning events: ". Dumper(@cust_event). "\n"
4067 =item retry_realtime
4069 Schedules realtime / batch credit card / electronic check / LEC billing
4070 events for for retry. Useful if card information has changed or manual
4071 retry is desired. The 'collect' method must be called to actually retry
4074 Implementation details: For either this customer, or for each of this
4075 customer's open invoices, changes the status of the first "done" (with
4076 statustext error) realtime processing event to "failed".
4080 sub retry_realtime {
4083 local $SIG{HUP} = 'IGNORE';
4084 local $SIG{INT} = 'IGNORE';
4085 local $SIG{QUIT} = 'IGNORE';
4086 local $SIG{TERM} = 'IGNORE';
4087 local $SIG{TSTP} = 'IGNORE';
4088 local $SIG{PIPE} = 'IGNORE';
4090 my $oldAutoCommit = $FS::UID::AutoCommit;
4091 local $FS::UID::AutoCommit = 0;
4094 #a little false laziness w/due_cust_event (not too bad, really)
4096 my $join = FS::part_event_condition->join_conditions_sql;
4097 my $order = FS::part_event_condition->order_conditions_sql;
4100 . join ( ' OR ' , map {
4101 "( part_event.eventtable = " . dbh->quote($_)
4102 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
4103 } FS::part_event->eventtables)
4106 #here is the agent virtualization
4107 my $agent_virt = " ( part_event.agentnum IS NULL
4108 OR part_event.agentnum = ". $self->agentnum. ' )';
4110 #XXX this shouldn't be hardcoded, actions should declare it...
4111 my @realtime_events = qw(
4112 cust_bill_realtime_card
4113 cust_bill_realtime_check
4114 cust_bill_realtime_lec
4118 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
4123 my @cust_event = qsearchs({
4124 'table' => 'cust_event',
4125 'select' => 'cust_event.*',
4126 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
4127 'hashref' => { 'status' => 'done' },
4128 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
4129 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
4132 my %seen_invnum = ();
4133 foreach my $cust_event (@cust_event) {
4135 #max one for the customer, one for each open invoice
4136 my $cust_X = $cust_event->cust_X;
4137 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
4141 or $cust_event->part_event->eventtable eq 'cust_bill'
4144 my $error = $cust_event->retry;
4146 $dbh->rollback if $oldAutoCommit;
4147 return "error scheduling event for retry: $error";
4152 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4160 =item realtime_collect [ OPTION => VALUE ... ]
4162 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4163 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4164 gateway. See L<http://420.am/business-onlinepayment> and
4165 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4167 On failure returns an error message.
4169 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.
4171 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4173 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
4174 then it is deduced from the customer record.
4176 If no I<amount> is specified, then the customer balance is used.
4178 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4179 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4180 if set, will override the value from the customer record.
4182 I<description> is a free-text field passed to the gateway. It defaults to
4183 the value defined by the business-onlinepayment-description configuration
4184 option, or "Internet services" if that is unset.
4186 If an I<invnum> is specified, this payment (if successful) is applied to the
4187 specified invoice. If you don't specify an I<invnum> you might want to
4188 call the B<apply_payments> method or set the I<apply> option.
4190 I<apply> can be set to true to apply a resulting payment.
4192 I<quiet> can be set true to surpress email decline notices.
4194 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4195 resulting paynum, if any.
4197 I<payunique> is a unique identifier for this payment.
4199 I<session_id> is a session identifier associated with this payment.
4201 I<depend_jobnum> allows payment capture to unlock export jobs
4205 sub realtime_collect {
4206 my( $self, %options ) = @_;
4209 warn "$me realtime_collect:\n";
4210 warn " $_ => $options{$_}\n" foreach keys %options;
4213 $options{amount} = $self->balance unless exists( $options{amount} );
4214 $options{method} = FS::payby->payby2bop($self->payby)
4215 unless exists( $options{method} );
4217 return $self->realtime_bop({%options});
4221 =item realtime_bop { [ ARG => VALUE ... ] }
4223 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4224 via a Business::OnlinePayment realtime gateway. See
4225 L<http://420.am/business-onlinepayment> for supported gateways.
4227 Required arguments in the hashref are I<method>, and I<amount>
4229 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4231 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4233 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4234 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4235 if set, will override the value from the customer record.
4237 I<description> is a free-text field passed to the gateway. It defaults to
4238 the value defined by the business-onlinepayment-description configuration
4239 option, or "Internet services" if that is unset.
4241 If an I<invnum> is specified, this payment (if successful) is applied to the
4242 specified invoice. If you don't specify an I<invnum> you might want to
4243 call the B<apply_payments> method or set the I<apply> option.
4245 I<apply> can be set to true to apply a resulting payment.
4247 I<quiet> can be set true to surpress email decline notices.
4249 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4250 resulting paynum, if any.
4252 I<payunique> is a unique identifier for this payment.
4254 I<session_id> is a session identifier associated with this payment.
4256 I<depend_jobnum> allows payment capture to unlock export jobs
4258 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4262 # some helper routines
4263 sub _bop_recurring_billing {
4264 my( $self, %opt ) = @_;
4266 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
4268 if ( defined($method) && $method eq 'transaction_is_recur' ) {
4270 return 1 if $opt{'trans_is_recur'};
4274 my %hash = ( 'custnum' => $self->custnum,
4279 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4280 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4290 sub _payment_gateway {
4291 my ($self, $options) = @_;
4293 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4294 unless exists($options->{payment_gateway});
4296 $options->{payment_gateway};
4300 my ($self, $options) = @_;
4303 'login' => $options->{payment_gateway}->gateway_username,
4304 'password' => $options->{payment_gateway}->gateway_password,
4309 my ($self, $options) = @_;
4311 $options->{payment_gateway}->gatewaynum
4312 ? $options->{payment_gateway}->options
4313 : @{ $options->{payment_gateway}->get('options') };
4318 my ($self, $options) = @_;
4320 unless ( $options->{'description'} ) {
4321 if ( $conf->exists('business-onlinepayment-description') ) {
4322 my $dtempl = $conf->config('business-onlinepayment-description');
4324 my $agent = $self->agent->agent;
4326 $options->{'description'} = eval qq("$dtempl");
4328 $options->{'description'} = 'Internet services';
4332 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4333 $options->{invnum} ||= '';
4334 $options->{payname} = $self->payname unless exists( $options->{payname} );
4338 my ($self, $options) = @_;
4341 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4342 $content{customer_ip} = $payip if length($payip);
4344 $content{invoice_number} = $options->{'invnum'}
4345 if exists($options->{'invnum'}) && length($options->{'invnum'});
4347 $content{email_customer} =
4348 ( $conf->exists('business-onlinepayment-email_customer')
4349 || $conf->exists('business-onlinepayment-email-override') );
4351 my ($payname, $payfirst, $paylast);
4352 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
4353 ($payname = $options->{payname}) =~
4354 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4355 or return "Illegal payname $payname";
4356 ($payfirst, $paylast) = ($1, $2);
4358 $payfirst = $self->getfield('first');
4359 $paylast = $self->getfield('last');
4360 $payname = "$payfirst $paylast";
4363 $content{last_name} = $paylast;
4364 $content{first_name} = $payfirst;
4366 $content{name} = $payname;
4368 $content{address} = exists($options->{'address1'})
4369 ? $options->{'address1'}
4371 my $address2 = exists($options->{'address2'})
4372 ? $options->{'address2'}
4374 $content{address} .= ", ". $address2 if length($address2);
4376 $content{city} = exists($options->{city})
4379 $content{state} = exists($options->{state})
4382 $content{zip} = exists($options->{zip})
4385 $content{country} = exists($options->{country})
4386 ? $options->{country}
4389 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4390 $content{phone} = $self->daytime || $self->night;
4395 my %bop_method2payby = (
4405 if (ref($_[0]) eq 'HASH') {
4406 %options = %{$_[0]};
4408 my ( $method, $amount ) = ( shift, shift );
4410 $options{method} = $method;
4411 $options{amount} = $amount;
4415 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
4416 warn " $_ => $options{$_}\n" foreach keys %options;
4419 return $self->fake_bop(%options) if $options{'fake'};
4421 $self->_bop_defaults(\%options);
4424 # set trans_is_recur based on invnum if there is one
4427 my $trans_is_recur = 0;
4428 if ( $options{'invnum'} ) {
4430 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
4431 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
4434 map { $_->part_pkg }
4436 map { $_->cust_pkg }
4437 $cust_bill->cust_bill_pkg;
4440 if grep { $_->freq ne '0' } @part_pkg;
4448 my $payment_gateway = $self->_payment_gateway( \%options );
4449 my $namespace = $payment_gateway->gateway_namespace;
4451 eval "use $namespace";
4455 # check for banned credit card/ACH
4458 my $ban = qsearchs('banned_pay', {
4459 'payby' => $bop_method2payby{$options{method}},
4460 'payinfo' => md5_base64($options{payinfo}),
4462 return "Banned credit card" if $ban;
4468 my $bop_content = $self->_bop_content(\%options);
4469 return $bop_content unless ref($bop_content);
4471 my @invoicing_list = $self->invoicing_list_emailonly;
4472 if ( $conf->exists('emailinvoiceautoalways')
4473 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4474 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4475 push @invoicing_list, $self->all_emails;
4478 my $email = ($conf->exists('business-onlinepayment-email-override'))
4479 ? $conf->config('business-onlinepayment-email-override')
4480 : $invoicing_list[0];
4484 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
4486 $content{card_number} = $options{payinfo};
4487 $paydate = exists($options{'paydate'})
4488 ? $options{'paydate'}
4490 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4491 $content{expiration} = "$2/$1";
4493 my $paycvv = exists($options{'paycvv'})
4494 ? $options{'paycvv'}
4496 $content{cvv2} = $paycvv
4499 my $paystart_month = exists($options{'paystart_month'})
4500 ? $options{'paystart_month'}
4501 : $self->paystart_month;
4503 my $paystart_year = exists($options{'paystart_year'})
4504 ? $options{'paystart_year'}
4505 : $self->paystart_year;
4507 $content{card_start} = "$paystart_month/$paystart_year"
4508 if $paystart_month && $paystart_year;
4510 my $payissue = exists($options{'payissue'})
4511 ? $options{'payissue'}
4513 $content{issue_number} = $payissue if $payissue;
4515 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
4516 'trans_is_recur' => $trans_is_recur,
4520 $content{recurring_billing} = 'YES';
4521 $content{acct_code} = 'rebill'
4522 if $conf->exists('credit_card-recurring_billing_acct_code');
4525 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
4526 ( $content{account_number}, $content{routing_code} ) =
4527 split('@', $options{payinfo});
4528 $content{bank_name} = $options{payname};
4529 $content{bank_state} = exists($options{'paystate'})
4530 ? $options{'paystate'}
4531 : $self->getfield('paystate');
4532 $content{account_type} = exists($options{'paytype'})
4533 ? uc($options{'paytype'}) || 'CHECKING'
4534 : uc($self->getfield('paytype')) || 'CHECKING';
4535 $content{account_name} = $self->getfield('first'). ' '.
4536 $self->getfield('last');
4538 $content{customer_org} = $self->company ? 'B' : 'I';
4539 $content{state_id} = exists($options{'stateid'})
4540 ? $options{'stateid'}
4541 : $self->getfield('stateid');
4542 $content{state_id_state} = exists($options{'stateid_state'})
4543 ? $options{'stateid_state'}
4544 : $self->getfield('stateid_state');
4545 $content{customer_ssn} = exists($options{'ss'})
4548 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
4549 $content{phone} = $options{payinfo};
4550 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4557 # run transaction(s)
4560 my $balance = exists( $options{'balance'} )
4561 ? $options{'balance'}
4564 $self->select_for_update; #mutex ... just until we get our pending record in
4566 #the checks here are intended to catch concurrent payments
4567 #double-form-submission prevention is taken care of in cust_pay_pending::check
4570 return "The customer's balance has changed; $options{method} transaction aborted."
4571 if $self->balance < $balance;
4572 #&& $self->balance < $options{amount}; #might as well anyway?
4574 #also check and make sure there aren't *other* pending payments for this cust
4576 my @pending = qsearch('cust_pay_pending', {
4577 'custnum' => $self->custnum,
4578 'status' => { op=>'!=', value=>'done' }
4580 return "A payment is already being processed for this customer (".
4581 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4582 "); $options{method} transaction aborted."
4583 if scalar(@pending);
4585 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4587 my $cust_pay_pending = new FS::cust_pay_pending {
4588 'custnum' => $self->custnum,
4589 #'invnum' => $options{'invnum'},
4590 'paid' => $options{amount},
4592 'payby' => $bop_method2payby{$options{method}},
4593 'payinfo' => $options{payinfo},
4594 'paydate' => $paydate,
4595 'recurring_billing' => $content{recurring_billing},
4596 'pkgnum' => $options{'pkgnum'},
4598 'gatewaynum' => $payment_gateway->gatewaynum || '',
4599 'session_id' => $options{session_id} || '',
4600 'jobnum' => $options{depend_jobnum} || '',
4602 $cust_pay_pending->payunique( $options{payunique} )
4603 if defined($options{payunique}) && length($options{payunique});
4604 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4605 return $cpp_new_err if $cpp_new_err;
4607 my( $action1, $action2 ) =
4608 split( /\s*\,\s*/, $payment_gateway->gateway_action );
4610 my $transaction = new $namespace( $payment_gateway->gateway_module,
4611 $self->_bop_options(\%options),
4614 $transaction->content(
4615 'type' => $options{method},
4616 $self->_bop_auth(\%options),
4617 'action' => $action1,
4618 'description' => $options{'description'},
4619 'amount' => $options{amount},
4620 #'invoice_number' => $options{'invnum'},
4621 'customer_id' => $self->custnum,
4623 'reference' => $cust_pay_pending->paypendingnum, #for now
4628 $cust_pay_pending->status('pending');
4629 my $cpp_pending_err = $cust_pay_pending->replace;
4630 return $cpp_pending_err if $cpp_pending_err;
4633 my $BOP_TESTING = 0;
4634 my $BOP_TESTING_SUCCESS = 1;
4636 unless ( $BOP_TESTING ) {
4637 $transaction->test_transaction(1)
4638 if $conf->exists('business-onlinepayment-test_transaction');
4639 $transaction->submit();
4641 if ( $BOP_TESTING_SUCCESS ) {
4642 $transaction->is_success(1);
4643 $transaction->authorization('fake auth');
4645 $transaction->is_success(0);
4646 $transaction->error_message('fake failure');
4650 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4652 return { reference => $cust_pay_pending->paypendingnum,
4653 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
4655 } elsif ( $transaction->is_success() && $action2 ) {
4657 $cust_pay_pending->status('authorized');
4658 my $cpp_authorized_err = $cust_pay_pending->replace;
4659 return $cpp_authorized_err if $cpp_authorized_err;
4661 my $auth = $transaction->authorization;
4662 my $ordernum = $transaction->can('order_number')
4663 ? $transaction->order_number
4667 new Business::OnlinePayment( $payment_gateway->gateway_module,
4668 $self->_bop_options(\%options),
4673 type => $options{method},
4675 $self->_bop_auth(\%options),
4676 order_number => $ordernum,
4677 amount => $options{amount},
4678 authorization => $auth,
4679 description => $options{'description'},
4682 foreach my $field (qw( authorization_source_code returned_ACI
4683 transaction_identifier validation_code
4684 transaction_sequence_num local_transaction_date
4685 local_transaction_time AVS_result_code )) {
4686 $capture{$field} = $transaction->$field() if $transaction->can($field);
4689 $capture->content( %capture );
4691 $capture->test_transaction(1)
4692 if $conf->exists('business-onlinepayment-test_transaction');
4695 unless ( $capture->is_success ) {
4696 my $e = "Authorization successful but capture failed, custnum #".
4697 $self->custnum. ': '. $capture->result_code.
4698 ": ". $capture->error_message;
4706 # remove paycvv after initial transaction
4709 #false laziness w/misc/process/payment.cgi - check both to make sure working
4711 if ( defined $self->dbdef_table->column('paycvv')
4712 && length($self->paycvv)
4713 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
4715 my $error = $self->remove_cvv;
4717 warn "WARNING: error removing cvv: $error\n";
4726 if ( $transaction->can('card_token') && $transaction->card_token ) {
4728 $self->card_token($transaction->card_token);
4730 if ( $options{'payinfo'} eq $self->payinfo ) {
4731 $self->payinfo($transaction->card_token);
4732 my $error = $self->replace;
4734 warn "WARNING: error storing token: $error, but proceeding anyway\n";
4744 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
4756 if (ref($_[0]) eq 'HASH') {
4757 %options = %{$_[0]};
4759 my ( $method, $amount ) = ( shift, shift );
4761 $options{method} = $method;
4762 $options{amount} = $amount;
4765 if ( $options{'fake_failure'} ) {
4766 return "Error: No error; test failure requested with fake_failure";
4770 #if ( $payment_gateway->gatewaynum ) { # agent override
4771 # $paybatch = $payment_gateway->gatewaynum. '-';
4774 #$paybatch .= "$processor:". $transaction->authorization;
4776 #$paybatch .= ':'. $transaction->order_number
4777 # if $transaction->can('order_number')
4778 # && length($transaction->order_number);
4780 my $paybatch = 'FakeProcessor:54:32';
4782 my $cust_pay = new FS::cust_pay ( {
4783 'custnum' => $self->custnum,
4784 'invnum' => $options{'invnum'},
4785 'paid' => $options{amount},
4787 'payby' => $bop_method2payby{$options{method}},
4788 #'payinfo' => $payinfo,
4789 'payinfo' => '4111111111111111',
4790 'paybatch' => $paybatch,
4791 #'paydate' => $paydate,
4792 'paydate' => '2012-05-01',
4794 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
4796 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4799 $cust_pay->invnum(''); #try again with no specific invnum
4800 my $error2 = $cust_pay->insert( $options{'manual'} ?
4801 ( 'manual' => 1 ) : ()
4804 # gah, even with transactions.
4805 my $e = 'WARNING: Card/ACH debited but database not updated - '.
4806 "error inserting (fake!) payment: $error2".
4807 " (previously tried insert with invnum #$options{'invnum'}" .
4814 if ( $options{'paynum_ref'} ) {
4815 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4818 return ''; #no error
4823 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
4825 # Wraps up processing of a realtime credit card, ACH (electronic check) or
4826 # phone bill transaction.
4828 sub _realtime_bop_result {
4829 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
4831 warn "$me _realtime_bop_result: pending transaction ".
4832 $cust_pay_pending->paypendingnum. "\n";
4833 warn " $_ => $options{$_}\n" foreach keys %options;
4836 my $payment_gateway = $options{payment_gateway}
4837 or return "no payment gateway in arguments to _realtime_bop_result";
4839 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
4840 my $cpp_captured_err = $cust_pay_pending->replace;
4841 return $cpp_captured_err if $cpp_captured_err;
4843 if ( $transaction->is_success() ) {
4846 if ( $payment_gateway->gatewaynum ) { # agent override
4847 $paybatch = $payment_gateway->gatewaynum. '-';
4850 $paybatch .= $payment_gateway->gateway_module. ":".
4851 $transaction->authorization;
4853 $paybatch .= ':'. $transaction->order_number
4854 if $transaction->can('order_number')
4855 && length($transaction->order_number);
4857 my $cust_pay = new FS::cust_pay ( {
4858 'custnum' => $self->custnum,
4859 'invnum' => $options{'invnum'},
4860 'paid' => $cust_pay_pending->paid,
4862 'payby' => $cust_pay_pending->payby,
4863 'payinfo' => $options{'payinfo'},
4864 'paybatch' => $paybatch,
4865 'paydate' => $cust_pay_pending->paydate,
4866 'pkgnum' => $cust_pay_pending->pkgnum,
4868 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
4869 $cust_pay->payunique( $options{payunique} )
4870 if defined($options{payunique}) && length($options{payunique});
4872 my $oldAutoCommit = $FS::UID::AutoCommit;
4873 local $FS::UID::AutoCommit = 0;
4876 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
4878 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4881 $cust_pay->invnum(''); #try again with no specific invnum
4882 my $error2 = $cust_pay->insert( $options{'manual'} ?
4883 ( 'manual' => 1 ) : ()
4886 # gah. but at least we have a record of the state we had to abort in
4887 # from cust_pay_pending now.
4888 my $e = "WARNING: $options{method} captured but payment not recorded -".
4889 " error inserting payment (". $payment_gateway->gateway_module.
4891 " (previously tried insert with invnum #$options{'invnum'}" .
4892 ": $error ) - pending payment saved as paypendingnum ".
4893 $cust_pay_pending->paypendingnum. "\n";
4899 my $jobnum = $cust_pay_pending->jobnum;
4901 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
4903 unless ( $placeholder ) {
4904 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4905 my $e = "WARNING: $options{method} captured but job $jobnum not ".
4906 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
4911 $error = $placeholder->delete;
4914 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4915 my $e = "WARNING: $options{method} captured but could not delete ".
4916 "job $jobnum for paypendingnum ".
4917 $cust_pay_pending->paypendingnum. ": $error\n";
4924 if ( $options{'paynum_ref'} ) {
4925 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4928 $cust_pay_pending->status('done');
4929 $cust_pay_pending->statustext('captured');
4930 $cust_pay_pending->paynum($cust_pay->paynum);
4931 my $cpp_done_err = $cust_pay_pending->replace;
4933 if ( $cpp_done_err ) {
4935 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4936 my $e = "WARNING: $options{method} captured but payment not recorded - ".
4937 "error updating status for paypendingnum ".
4938 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
4944 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4946 if ( $options{'apply'} ) {
4947 my $apply_error = $self->apply_payments_and_credits;
4948 if ( $apply_error ) {
4949 warn "WARNING: error applying payment: $apply_error\n";
4950 #but we still should return no error cause the payment otherwise went
4955 return ''; #no error
4961 my $perror = $payment_gateway->gateway_module. " error: ".
4962 $transaction->error_message;
4964 my $jobnum = $cust_pay_pending->jobnum;
4966 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
4968 if ( $placeholder ) {
4969 my $error = $placeholder->depended_delete;
4970 $error ||= $placeholder->delete;
4971 warn "error removing provisioning jobs after declined paypendingnum ".
4972 $cust_pay_pending->paypendingnum. "\n";
4974 my $e = "error finding job $jobnum for declined paypendingnum ".
4975 $cust_pay_pending->paypendingnum. "\n";
4981 unless ( $transaction->error_message ) {
4984 if ( $transaction->can('response_page') ) {
4986 'page' => ( $transaction->can('response_page')
4987 ? $transaction->response_page
4990 'code' => ( $transaction->can('response_code')
4991 ? $transaction->response_code
4994 'headers' => ( $transaction->can('response_headers')
4995 ? $transaction->response_headers
5001 "No additional debugging information available for ".
5002 $payment_gateway->gateway_module;
5005 $perror .= "No error_message returned from ".
5006 $payment_gateway->gateway_module. " -- ".
5007 ( ref($t_response) ? Dumper($t_response) : $t_response );
5011 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
5012 && $conf->exists('emaildecline')
5013 && grep { $_ ne 'POST' } $self->invoicing_list
5014 && ! grep { $transaction->error_message =~ /$_/ }
5015 $conf->config('emaildecline-exclude')
5017 my @templ = $conf->config('declinetemplate');
5018 my $template = new Text::Template (
5020 SOURCE => [ map "$_\n", @templ ],
5021 ) or return "($perror) can't create template: $Text::Template::ERROR";
5022 $template->compile()
5023 or return "($perror) can't compile template: $Text::Template::ERROR";
5027 scalar( $conf->config('company_name', $self->agentnum ) ),
5028 'company_address' =>
5029 join("\n", $conf->config('company_address', $self->agentnum ) ),
5030 'error' => $transaction->error_message,
5033 my $error = send_email(
5034 'from' => $conf->config('invoice_from', $self->agentnum ),
5035 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
5036 'subject' => 'Your payment could not be processed',
5037 'body' => [ $template->fill_in(HASH => $templ_hash) ],
5040 $perror .= " (also received error sending decline notification: $error)"
5045 $cust_pay_pending->status('done');
5046 $cust_pay_pending->statustext("declined: $perror");
5047 my $cpp_done_err = $cust_pay_pending->replace;
5048 if ( $cpp_done_err ) {
5049 my $e = "WARNING: $options{method} declined but pending payment not ".
5050 "resolved - error updating status for paypendingnum ".
5051 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5053 $perror = "$e ($perror)";
5061 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
5063 Verifies successful third party processing of a realtime credit card,
5064 ACH (electronic check) or phone bill transaction via a
5065 Business::OnlineThirdPartyPayment realtime gateway. See
5066 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
5068 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
5070 The additional options I<payname>, I<city>, I<state>,
5071 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5072 if set, will override the value from the customer record.
5074 I<description> is a free-text field passed to the gateway. It defaults to
5075 "Internet services".
5077 If an I<invnum> is specified, this payment (if successful) is applied to the
5078 specified invoice. If you don't specify an I<invnum> you might want to
5079 call the B<apply_payments> method.
5081 I<quiet> can be set true to surpress email decline notices.
5083 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
5084 resulting paynum, if any.
5086 I<payunique> is a unique identifier for this payment.
5088 Returns a hashref containing elements bill_error (which will be undefined
5089 upon success) and session_id of any associated session.
5093 sub realtime_botpp_capture {
5094 my( $self, $cust_pay_pending, %options ) = @_;
5096 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5097 warn " $_ => $options{$_}\n" foreach keys %options;
5100 eval "use Business::OnlineThirdPartyPayment";
5104 # select the gateway
5107 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5109 my $payment_gateway = $cust_pay_pending->gatewaynum
5110 ? qsearchs( 'payment_gateway',
5111 { gatewaynum => $cust_pay_pending->gatewaynum }
5113 : $self->agent->payment_gateway( 'method' => $method,
5114 # 'invnum' => $cust_pay_pending->invnum,
5115 # 'payinfo' => $cust_pay_pending->payinfo,
5118 $options{payment_gateway} = $payment_gateway; # for the helper subs
5124 my @invoicing_list = $self->invoicing_list_emailonly;
5125 if ( $conf->exists('emailinvoiceautoalways')
5126 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5127 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5128 push @invoicing_list, $self->all_emails;
5131 my $email = ($conf->exists('business-onlinepayment-email-override'))
5132 ? $conf->config('business-onlinepayment-email-override')
5133 : $invoicing_list[0];
5137 $content{email_customer} =
5138 ( $conf->exists('business-onlinepayment-email_customer')
5139 || $conf->exists('business-onlinepayment-email-override') );
5142 # run transaction(s)
5146 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5147 $self->_bop_options(\%options),
5150 $transaction->reference({ %options });
5152 $transaction->content(
5154 $self->_bop_auth(\%options),
5155 'action' => 'Post Authorization',
5156 'description' => $options{'description'},
5157 'amount' => $cust_pay_pending->paid,
5158 #'invoice_number' => $options{'invnum'},
5159 'customer_id' => $self->custnum,
5160 'referer' => 'http://cleanwhisker.420.am/',
5161 'reference' => $cust_pay_pending->paypendingnum,
5163 'phone' => $self->daytime || $self->night,
5165 # plus whatever is required for bogus capture avoidance
5168 $transaction->submit();
5171 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5174 bill_error => $error,
5175 session_id => $cust_pay_pending->session_id,
5180 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5184 sub default_payment_gateway {
5185 my( $self, $method ) = @_;
5187 die "Real-time processing not enabled\n"
5188 unless $conf->exists('business-onlinepayment');
5190 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5193 my $bop_config = 'business-onlinepayment';
5194 $bop_config .= '-ach'
5195 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5196 my ( $processor, $login, $password, $action, @bop_options ) =
5197 $conf->config($bop_config);
5198 $action ||= 'normal authorization';
5199 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5200 die "No real-time processor is enabled - ".
5201 "did you set the business-onlinepayment configuration value?\n"
5204 ( $processor, $login, $password, $action, @bop_options )
5209 Removes the I<paycvv> field from the database directly.
5211 If there is an error, returns the error, otherwise returns false.
5217 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5218 or return dbh->errstr;
5219 $sth->execute($self->custnum)
5220 or return $sth->errstr;
5225 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5227 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5228 via a Business::OnlinePayment realtime gateway. See
5229 L<http://420.am/business-onlinepayment> for supported gateways.
5231 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5233 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5235 Most gateways require a reference to an original payment transaction to refund,
5236 so you probably need to specify a I<paynum>.
5238 I<amount> defaults to the original amount of the payment if not specified.
5240 I<reason> specifies a reason for the refund.
5242 I<paydate> specifies the expiration date for a credit card overriding the
5243 value from the customer record or the payment record. Specified as yyyy-mm-dd
5245 Implementation note: If I<amount> is unspecified or equal to the amount of the
5246 orignal payment, first an attempt is made to "void" the transaction via
5247 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5248 the normal attempt is made to "refund" ("credit") the transaction via the
5249 gateway is attempted.
5251 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5252 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5253 #if set, will override the value from the customer record.
5255 #If an I<invnum> is specified, this payment (if successful) is applied to the
5256 #specified invoice. If you don't specify an I<invnum> you might want to
5257 #call the B<apply_payments> method.
5261 #some false laziness w/realtime_bop, not enough to make it worth merging
5262 #but some useful small subs should be pulled out
5263 sub realtime_refund_bop {
5267 if (ref($_[0]) eq 'HASH') {
5268 %options = %{$_[0]};
5272 $options{method} = $method;
5276 warn "$me realtime_refund_bop (new): $options{method} refund\n";
5277 warn " $_ => $options{$_}\n" foreach keys %options;
5281 # look up the original payment and optionally a gateway for that payment
5285 my $amount = $options{'amount'};
5287 my( $processor, $login, $password, @bop_options, $namespace ) ;
5288 my( $auth, $order_number ) = ( '', '', '' );
5290 if ( $options{'paynum'} ) {
5292 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
5293 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5294 or return "Unknown paynum $options{'paynum'}";
5295 $amount ||= $cust_pay->paid;
5297 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5298 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5299 $cust_pay->paybatch;
5300 my $gatewaynum = '';
5301 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5303 if ( $gatewaynum ) { #gateway for the payment to be refunded
5305 my $payment_gateway =
5306 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5307 die "payment gateway $gatewaynum not found"
5308 unless $payment_gateway;
5310 $processor = $payment_gateway->gateway_module;
5311 $login = $payment_gateway->gateway_username;
5312 $password = $payment_gateway->gateway_password;
5313 $namespace = $payment_gateway->gateway_namespace;
5314 @bop_options = $payment_gateway->options;
5316 } else { #try the default gateway
5319 my $payment_gateway =
5320 $self->agent->payment_gateway('method' => $options{method});
5322 ( $conf_processor, $login, $password, $namespace ) =
5323 map { my $method = "gateway_$_"; $payment_gateway->$method }
5324 qw( module username password namespace );
5326 @bop_options = $payment_gateway->gatewaynum
5327 ? $payment_gateway->options
5328 : @{ $payment_gateway->get('options') };
5330 return "processor of payment $options{'paynum'} $processor does not".
5331 " match default processor $conf_processor"
5332 unless $processor eq $conf_processor;
5337 } else { # didn't specify a paynum, so look for agent gateway overrides
5338 # like a normal transaction
5340 my $payment_gateway =
5341 $self->agent->payment_gateway( 'method' => $options{method},
5342 #'payinfo' => $payinfo,
5344 my( $processor, $login, $password, $namespace ) =
5345 map { my $method = "gateway_$_"; $payment_gateway->$method }
5346 qw( module username password namespace );
5348 my @bop_options = $payment_gateway->gatewaynum
5349 ? $payment_gateway->options
5350 : @{ $payment_gateway->get('options') };
5353 return "neither amount nor paynum specified" unless $amount;
5355 eval "use $namespace";
5359 'type' => $options{method},
5361 'password' => $password,
5362 'order_number' => $order_number,
5363 'amount' => $amount,
5364 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5366 $content{authorization} = $auth
5367 if length($auth); #echeck/ACH transactions have an order # but no auth
5368 #(at least with authorize.net)
5370 my $disable_void_after;
5371 if ($conf->exists('disable_void_after')
5372 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5373 $disable_void_after = $1;
5376 #first try void if applicable
5377 if ( $cust_pay && $cust_pay->paid == $amount
5379 ( not defined($disable_void_after) )
5380 || ( time < ($cust_pay->_date + $disable_void_after ) )
5383 warn " attempting void\n" if $DEBUG > 1;
5384 my $void = new Business::OnlinePayment( $processor, @bop_options );
5385 if ( $void->can('info') ) {
5386 if ( $cust_pay->payby eq 'CARD'
5387 && $void->info('CC_void_requires_card') )
5389 $content{'card_number'} = $cust_pay->payinfo;
5390 } elsif ( $cust_pay->payby eq 'CHEK'
5391 && $void->info('ECHECK_void_requires_account') )
5393 ( $content{'account_number'}, $content{'routing_code'} ) =
5394 split('@', $cust_pay->payinfo);
5395 $content{'name'} = $self->get('first'). ' '. $self->get('last');
5398 $void->content( 'action' => 'void', %content );
5399 $void->test_transaction(1)
5400 if $conf->exists('business-onlinepayment-test_transaction');
5402 if ( $void->is_success ) {
5403 my $error = $cust_pay->void($options{'reason'});
5405 # gah, even with transactions.
5406 my $e = 'WARNING: Card/ACH voided but database not updated - '.
5407 "error voiding payment: $error";
5411 warn " void successful\n" if $DEBUG > 1;
5416 warn " void unsuccessful, trying refund\n"
5420 my $address = $self->address1;
5421 $address .= ", ". $self->address2 if $self->address2;
5423 my($payname, $payfirst, $paylast);
5424 if ( $self->payname && $options{method} ne 'ECHECK' ) {
5425 $payname = $self->payname;
5426 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5427 or return "Illegal payname $payname";
5428 ($payfirst, $paylast) = ($1, $2);
5430 $payfirst = $self->getfield('first');
5431 $paylast = $self->getfield('last');
5432 $payname = "$payfirst $paylast";
5435 my @invoicing_list = $self->invoicing_list_emailonly;
5436 if ( $conf->exists('emailinvoiceautoalways')
5437 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5438 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5439 push @invoicing_list, $self->all_emails;
5442 my $email = ($conf->exists('business-onlinepayment-email-override'))
5443 ? $conf->config('business-onlinepayment-email-override')
5444 : $invoicing_list[0];
5446 my $payip = exists($options{'payip'})
5449 $content{customer_ip} = $payip
5453 if ( $options{method} eq 'CC' ) {
5456 $content{card_number} = $payinfo = $cust_pay->payinfo;
5457 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
5458 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
5459 ($content{expiration} = "$2/$1"); # where available
5461 $content{card_number} = $payinfo = $self->payinfo;
5462 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
5463 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5464 $content{expiration} = "$2/$1";
5467 } elsif ( $options{method} eq 'ECHECK' ) {
5470 $payinfo = $cust_pay->payinfo;
5472 $payinfo = $self->payinfo;
5474 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
5475 $content{bank_name} = $self->payname;
5476 $content{account_type} = 'CHECKING';
5477 $content{account_name} = $payname;
5478 $content{customer_org} = $self->company ? 'B' : 'I';
5479 $content{customer_ssn} = $self->ss;
5480 } elsif ( $options{method} eq 'LEC' ) {
5481 $content{phone} = $payinfo = $self->payinfo;
5485 my $refund = new Business::OnlinePayment( $processor, @bop_options );
5486 my %sub_content = $refund->content(
5487 'action' => 'credit',
5488 'customer_id' => $self->custnum,
5489 'last_name' => $paylast,
5490 'first_name' => $payfirst,
5492 'address' => $address,
5493 'city' => $self->city,
5494 'state' => $self->state,
5495 'zip' => $self->zip,
5496 'country' => $self->country,
5498 'phone' => $self->daytime || $self->night,
5501 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
5503 $refund->test_transaction(1)
5504 if $conf->exists('business-onlinepayment-test_transaction');
5507 return "$processor error: ". $refund->error_message
5508 unless $refund->is_success();
5510 my $paybatch = "$processor:". $refund->authorization;
5511 $paybatch .= ':'. $refund->order_number
5512 if $refund->can('order_number') && $refund->order_number;
5514 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
5515 my @cust_bill_pay = $cust_pay->cust_bill_pay;
5516 last unless @cust_bill_pay;
5517 my $cust_bill_pay = pop @cust_bill_pay;
5518 my $error = $cust_bill_pay->delete;
5522 my $cust_refund = new FS::cust_refund ( {
5523 'custnum' => $self->custnum,
5524 'paynum' => $options{'paynum'},
5525 'refund' => $amount,
5527 'payby' => $bop_method2payby{$options{method}},
5528 'payinfo' => $payinfo,
5529 'paybatch' => $paybatch,
5530 'reason' => $options{'reason'} || 'card or ACH refund',
5532 my $error = $cust_refund->insert;
5534 $cust_refund->paynum(''); #try again with no specific paynum
5535 my $error2 = $cust_refund->insert;
5537 # gah, even with transactions.
5538 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
5539 "error inserting refund ($processor): $error2".
5540 " (previously tried insert with paynum #$options{'paynum'}" .
5551 =item batch_card OPTION => VALUE...
5553 Adds a payment for this invoice to the pending credit card batch (see
5554 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
5555 runs the payment using a realtime gateway.
5560 my ($self, %options) = @_;
5563 if (exists($options{amount})) {
5564 $amount = $options{amount};
5566 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
5568 return '' unless $amount > 0;
5570 my $invnum = delete $options{invnum};
5571 my $payby = $options{invnum} || $self->payby; #dubious
5573 if ($options{'realtime'}) {
5574 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
5580 my $oldAutoCommit = $FS::UID::AutoCommit;
5581 local $FS::UID::AutoCommit = 0;
5584 #this needs to handle mysql as well as Pg, like svc_acct.pm
5585 #(make it into a common function if folks need to do batching with mysql)
5586 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
5587 or return "Cannot lock pay_batch: " . $dbh->errstr;
5591 'payby' => FS::payby->payby2payment($payby),
5594 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
5596 unless ( $pay_batch ) {
5597 $pay_batch = new FS::pay_batch \%pay_batch;
5598 my $error = $pay_batch->insert;
5600 $dbh->rollback if $oldAutoCommit;
5601 die "error creating new batch: $error\n";
5605 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
5606 'batchnum' => $pay_batch->batchnum,
5607 'custnum' => $self->custnum,
5610 foreach (qw( address1 address2 city state zip country payby payinfo paydate
5612 $options{$_} = '' unless exists($options{$_});
5615 my $cust_pay_batch = new FS::cust_pay_batch ( {
5616 'batchnum' => $pay_batch->batchnum,
5617 'invnum' => $invnum || 0, # is there a better value?
5618 # this field should be
5620 # cust_bill_pay_batch now
5621 'custnum' => $self->custnum,
5622 'last' => $self->getfield('last'),
5623 'first' => $self->getfield('first'),
5624 'address1' => $options{address1} || $self->address1,
5625 'address2' => $options{address2} || $self->address2,
5626 'city' => $options{city} || $self->city,
5627 'state' => $options{state} || $self->state,
5628 'zip' => $options{zip} || $self->zip,
5629 'country' => $options{country} || $self->country,
5630 'payby' => $options{payby} || $self->payby,
5631 'payinfo' => $options{payinfo} || $self->payinfo,
5632 'exp' => $options{paydate} || $self->paydate,
5633 'payname' => $options{payname} || $self->payname,
5634 'amount' => $amount, # consolidating
5637 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
5638 if $old_cust_pay_batch;
5641 if ($old_cust_pay_batch) {
5642 $error = $cust_pay_batch->replace($old_cust_pay_batch)
5644 $error = $cust_pay_batch->insert;
5648 $dbh->rollback if $oldAutoCommit;
5652 my $unapplied = $self->total_unapplied_credits
5653 + $self->total_unapplied_payments
5654 + $self->in_transit_payments;
5655 foreach my $cust_bill ($self->open_cust_bill) {
5656 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
5657 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
5658 'invnum' => $cust_bill->invnum,
5659 'paybatchnum' => $cust_pay_batch->paybatchnum,
5660 'amount' => $cust_bill->owed,
5663 if ($unapplied >= $cust_bill_pay_batch->amount){
5664 $unapplied -= $cust_bill_pay_batch->amount;
5667 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
5668 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
5670 $error = $cust_bill_pay_batch->insert;
5672 $dbh->rollback if $oldAutoCommit;
5677 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5681 =item apply_payments_and_credits [ OPTION => VALUE ... ]
5683 Applies unapplied payments and credits.
5685 In most cases, this new method should be used in place of sequential
5686 apply_payments and apply_credits methods.
5688 A hash of optional arguments may be passed. Currently "manual" is supported.
5689 If true, a payment receipt is sent instead of a statement when
5690 'payment_receipt_email' configuration option is set.
5692 If there is an error, returns the error, otherwise returns false.
5696 sub apply_payments_and_credits {
5697 my( $self, %options ) = @_;
5699 local $SIG{HUP} = 'IGNORE';
5700 local $SIG{INT} = 'IGNORE';
5701 local $SIG{QUIT} = 'IGNORE';
5702 local $SIG{TERM} = 'IGNORE';
5703 local $SIG{TSTP} = 'IGNORE';
5704 local $SIG{PIPE} = 'IGNORE';
5706 my $oldAutoCommit = $FS::UID::AutoCommit;
5707 local $FS::UID::AutoCommit = 0;
5710 $self->select_for_update; #mutex
5712 foreach my $cust_bill ( $self->open_cust_bill ) {
5713 my $error = $cust_bill->apply_payments_and_credits(%options);
5715 $dbh->rollback if $oldAutoCommit;
5716 return "Error applying: $error";
5720 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5725 =item apply_credits OPTION => VALUE ...
5727 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
5728 to outstanding invoice balances in chronological order (or reverse
5729 chronological order if the I<order> option is set to B<newest>) and returns the
5730 value of any remaining unapplied credits available for refund (see
5731 L<FS::cust_refund>).
5733 Dies if there is an error.
5741 local $SIG{HUP} = 'IGNORE';
5742 local $SIG{INT} = 'IGNORE';
5743 local $SIG{QUIT} = 'IGNORE';
5744 local $SIG{TERM} = 'IGNORE';
5745 local $SIG{TSTP} = 'IGNORE';
5746 local $SIG{PIPE} = 'IGNORE';
5748 my $oldAutoCommit = $FS::UID::AutoCommit;
5749 local $FS::UID::AutoCommit = 0;
5752 $self->select_for_update; #mutex
5754 unless ( $self->total_unapplied_credits ) {
5755 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5759 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
5760 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
5762 my @invoices = $self->open_cust_bill;
5763 @invoices = sort { $b->_date <=> $a->_date } @invoices
5764 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
5766 if ( $conf->exists('pkg-balances') ) {
5767 # limit @credits to those w/ a pkgnum grepped from $self
5769 foreach my $i (@invoices) {
5770 foreach my $li ( $i->cust_bill_pkg ) {
5771 $pkgnums{$li->pkgnum} = 1;
5774 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
5779 foreach my $cust_bill ( @invoices ) {
5781 if ( !defined($credit) || $credit->credited == 0) {
5782 $credit = pop @credits or last;
5786 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
5787 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
5789 $owed = $cust_bill->owed;
5791 unless ( $owed > 0 ) {
5792 push @credits, $credit;
5796 my $amount = min( $credit->credited, $owed );
5798 my $cust_credit_bill = new FS::cust_credit_bill ( {
5799 'crednum' => $credit->crednum,
5800 'invnum' => $cust_bill->invnum,
5801 'amount' => $amount,
5803 $cust_credit_bill->pkgnum( $credit->pkgnum )
5804 if $conf->exists('pkg-balances') && $credit->pkgnum;
5805 my $error = $cust_credit_bill->insert;
5807 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5811 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5815 my $total_unapplied_credits = $self->total_unapplied_credits;
5817 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5819 return $total_unapplied_credits;
5822 =item apply_payments [ OPTION => VALUE ... ]
5824 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
5825 to outstanding invoice balances in chronological order.
5827 #and returns the value of any remaining unapplied payments.
5829 A hash of optional arguments may be passed. Currently "manual" is supported.
5830 If true, a payment receipt is sent instead of a statement when
5831 'payment_receipt_email' configuration option is set.
5833 Dies if there is an error.
5837 sub apply_payments {
5838 my( $self, %options ) = @_;
5840 local $SIG{HUP} = 'IGNORE';
5841 local $SIG{INT} = 'IGNORE';
5842 local $SIG{QUIT} = 'IGNORE';
5843 local $SIG{TERM} = 'IGNORE';
5844 local $SIG{TSTP} = 'IGNORE';
5845 local $SIG{PIPE} = 'IGNORE';
5847 my $oldAutoCommit = $FS::UID::AutoCommit;
5848 local $FS::UID::AutoCommit = 0;
5851 $self->select_for_update; #mutex
5855 my @payments = sort { $b->_date <=> $a->_date }
5856 grep { $_->unapplied > 0 }
5859 my @invoices = sort { $a->_date <=> $b->_date}
5860 grep { $_->owed > 0 }
5863 if ( $conf->exists('pkg-balances') ) {
5864 # limit @payments to those w/ a pkgnum grepped from $self
5866 foreach my $i (@invoices) {
5867 foreach my $li ( $i->cust_bill_pkg ) {
5868 $pkgnums{$li->pkgnum} = 1;
5871 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
5876 foreach my $cust_bill ( @invoices ) {
5878 if ( !defined($payment) || $payment->unapplied == 0 ) {
5879 $payment = pop @payments or last;
5883 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
5884 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
5886 $owed = $cust_bill->owed;
5888 unless ( $owed > 0 ) {
5889 push @payments, $payment;
5893 my $amount = min( $payment->unapplied, $owed );
5895 my $cust_bill_pay = new FS::cust_bill_pay ( {
5896 'paynum' => $payment->paynum,
5897 'invnum' => $cust_bill->invnum,
5898 'amount' => $amount,
5900 $cust_bill_pay->pkgnum( $payment->pkgnum )
5901 if $conf->exists('pkg-balances') && $payment->pkgnum;
5902 my $error = $cust_bill_pay->insert(%options);
5904 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5908 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5912 my $total_unapplied_payments = $self->total_unapplied_payments;
5914 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5916 return $total_unapplied_payments;
5921 Returns the total owed for this customer on all invoices
5922 (see L<FS::cust_bill/owed>).
5928 $self->total_owed_date(2145859200); #12/31/2037
5931 =item total_owed_date TIME
5933 Returns the total owed for this customer on all invoices with date earlier than
5934 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
5935 see L<Time::Local> and L<Date::Parse> for conversion functions.
5939 sub total_owed_date {
5943 my $custnum = $self->custnum;
5945 my $owed_sql = FS::cust_bill->owed_sql;
5948 SELECT SUM($owed_sql) FROM cust_bill
5949 WHERE custnum = $custnum
5953 sprintf( "%.2f", $self->scalar_sql($sql) );
5957 =item total_owed_pkgnum PKGNUM
5959 Returns the total owed on all invoices for this customer's specific package
5960 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
5964 sub total_owed_pkgnum {
5965 my( $self, $pkgnum ) = @_;
5966 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
5969 =item total_owed_date_pkgnum TIME PKGNUM
5971 Returns the total owed for this customer's specific package when using
5972 experimental package balances on all invoices with date earlier than
5973 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
5974 see L<Time::Local> and L<Date::Parse> for conversion functions.
5978 sub total_owed_date_pkgnum {
5979 my( $self, $time, $pkgnum ) = @_;
5982 foreach my $cust_bill (
5983 grep { $_->_date <= $time }
5984 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
5986 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
5988 sprintf( "%.2f", $total_bill );
5994 Returns the total amount of all payments.
6001 $total += $_->paid foreach $self->cust_pay;
6002 sprintf( "%.2f", $total );
6005 =item total_unapplied_credits
6007 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6008 customer. See L<FS::cust_credit/credited>.
6010 =item total_credited
6012 Old name for total_unapplied_credits. Don't use.
6016 sub total_credited {
6017 #carp "total_credited deprecated, use total_unapplied_credits";
6018 shift->total_unapplied_credits(@_);
6021 sub total_unapplied_credits {
6024 my $custnum = $self->custnum;
6026 my $unapplied_sql = FS::cust_credit->unapplied_sql;
6029 SELECT SUM($unapplied_sql) FROM cust_credit
6030 WHERE custnum = $custnum
6033 sprintf( "%.2f", $self->scalar_sql($sql) );
6037 =item total_unapplied_credits_pkgnum PKGNUM
6039 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6040 customer. See L<FS::cust_credit/credited>.
6044 sub total_unapplied_credits_pkgnum {
6045 my( $self, $pkgnum ) = @_;
6046 my $total_credit = 0;
6047 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
6048 sprintf( "%.2f", $total_credit );
6052 =item total_unapplied_payments
6054 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
6055 See L<FS::cust_pay/unapplied>.
6059 sub total_unapplied_payments {
6062 my $custnum = $self->custnum;
6064 my $unapplied_sql = FS::cust_pay->unapplied_sql;
6067 SELECT SUM($unapplied_sql) FROM cust_pay
6068 WHERE custnum = $custnum
6071 sprintf( "%.2f", $self->scalar_sql($sql) );
6075 =item total_unapplied_payments_pkgnum PKGNUM
6077 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
6078 specific package when using experimental package balances. See
6079 L<FS::cust_pay/unapplied>.
6083 sub total_unapplied_payments_pkgnum {
6084 my( $self, $pkgnum ) = @_;
6085 my $total_unapplied = 0;
6086 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
6087 sprintf( "%.2f", $total_unapplied );
6091 =item total_unapplied_refunds
6093 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
6094 customer. See L<FS::cust_refund/unapplied>.
6098 sub total_unapplied_refunds {
6100 my $custnum = $self->custnum;
6102 my $unapplied_sql = FS::cust_refund->unapplied_sql;
6105 SELECT SUM($unapplied_sql) FROM cust_refund
6106 WHERE custnum = $custnum
6109 sprintf( "%.2f", $self->scalar_sql($sql) );
6115 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6116 total_unapplied_credits minus total_unapplied_payments).
6122 $self->balance_date_range;
6125 =item balance_date TIME
6127 Returns the balance for this customer, only considering invoices with date
6128 earlier than TIME (total_owed_date minus total_credited minus
6129 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
6130 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
6137 $self->balance_date_range(shift);
6140 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
6142 Returns the balance for this customer, optionally considering invoices with
6143 date earlier than START_TIME, and not later than END_TIME
6144 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
6146 Times are specified as SQL fragments or numeric
6147 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
6148 L<Date::Parse> for conversion functions. The empty string can be passed
6149 to disable that time constraint completely.
6151 Available options are:
6155 =item unapplied_date
6157 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)
6163 sub balance_date_range {
6165 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
6166 ') FROM cust_main WHERE custnum='. $self->custnum;
6167 sprintf( "%.2f", $self->scalar_sql($sql) );
6170 =item balance_pkgnum PKGNUM
6172 Returns the balance for this customer's specific package when using
6173 experimental package balances (total_owed plus total_unrefunded, minus
6174 total_unapplied_credits minus total_unapplied_payments)
6178 sub balance_pkgnum {
6179 my( $self, $pkgnum ) = @_;
6182 $self->total_owed_pkgnum($pkgnum)
6183 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6184 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
6185 - $self->total_unapplied_credits_pkgnum($pkgnum)
6186 - $self->total_unapplied_payments_pkgnum($pkgnum)
6190 =item in_transit_payments
6192 Returns the total of requests for payments for this customer pending in
6193 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
6197 sub in_transit_payments {
6199 my $in_transit_payments = 0;
6200 foreach my $pay_batch ( qsearch('pay_batch', {
6203 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6204 'batchnum' => $pay_batch->batchnum,
6205 'custnum' => $self->custnum,
6207 $in_transit_payments += $cust_pay_batch->amount;
6210 sprintf( "%.2f", $in_transit_payments );
6215 Returns a hash of useful information for making a payment.
6225 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6226 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6227 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6231 For credit card transactions:
6243 For electronic check transactions:
6258 $return{balance} = $self->balance;
6260 $return{payname} = $self->payname
6261 || ( $self->first. ' '. $self->get('last') );
6263 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6265 $return{payby} = $self->payby;
6266 $return{stateid_state} = $self->stateid_state;
6268 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6269 $return{card_type} = cardtype($self->payinfo);
6270 $return{payinfo} = $self->paymask;
6272 @return{'month', 'year'} = $self->paydate_monthyear;
6276 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6277 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6278 $return{payinfo1} = $payinfo1;
6279 $return{payinfo2} = $payinfo2;
6280 $return{paytype} = $self->paytype;
6281 $return{paystate} = $self->paystate;
6285 #doubleclick protection
6287 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6293 =item paydate_monthyear
6295 Returns a two-element list consisting of the month and year of this customer's
6296 paydate (credit card expiration date for CARD customers)
6300 sub paydate_monthyear {
6302 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6304 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6311 =item tax_exemption TAXNAME
6316 my( $self, $taxname ) = @_;
6318 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6319 'taxname' => $taxname,
6324 =item cust_main_exemption
6328 sub cust_main_exemption {
6330 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6333 =item invoicing_list [ ARRAYREF ]
6335 If an arguement is given, sets these email addresses as invoice recipients
6336 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
6337 (except as warnings), so use check_invoicing_list first.
6339 Returns a list of email addresses (with svcnum entries expanded).
6341 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
6342 check it without disturbing anything by passing nothing.
6344 This interface may change in the future.
6348 sub invoicing_list {
6349 my( $self, $arrayref ) = @_;
6352 my @cust_main_invoice;
6353 if ( $self->custnum ) {
6354 @cust_main_invoice =
6355 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6357 @cust_main_invoice = ();
6359 foreach my $cust_main_invoice ( @cust_main_invoice ) {
6360 #warn $cust_main_invoice->destnum;
6361 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6362 #warn $cust_main_invoice->destnum;
6363 my $error = $cust_main_invoice->delete;
6364 warn $error if $error;
6367 if ( $self->custnum ) {
6368 @cust_main_invoice =
6369 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6371 @cust_main_invoice = ();
6373 my %seen = map { $_->address => 1 } @cust_main_invoice;
6374 foreach my $address ( @{$arrayref} ) {
6375 next if exists $seen{$address} && $seen{$address};
6376 $seen{$address} = 1;
6377 my $cust_main_invoice = new FS::cust_main_invoice ( {
6378 'custnum' => $self->custnum,
6381 my $error = $cust_main_invoice->insert;
6382 warn $error if $error;
6386 if ( $self->custnum ) {
6388 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6395 =item check_invoicing_list ARRAYREF
6397 Checks these arguements as valid input for the invoicing_list method. If there
6398 is an error, returns the error, otherwise returns false.
6402 sub check_invoicing_list {
6403 my( $self, $arrayref ) = @_;
6405 foreach my $address ( @$arrayref ) {
6407 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6408 return 'Can\'t add FAX invoice destination with a blank FAX number.';
6411 my $cust_main_invoice = new FS::cust_main_invoice ( {
6412 'custnum' => $self->custnum,
6415 my $error = $self->custnum
6416 ? $cust_main_invoice->check
6417 : $cust_main_invoice->checkdest
6419 return $error if $error;
6423 return "Email address required"
6424 if $conf->exists('cust_main-require_invoicing_list_email')
6425 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6430 =item set_default_invoicing_list
6432 Sets the invoicing list to all accounts associated with this customer,
6433 overwriting any previous invoicing list.
6437 sub set_default_invoicing_list {
6439 $self->invoicing_list($self->all_emails);
6444 Returns the email addresses of all accounts provisioned for this customer.
6451 foreach my $cust_pkg ( $self->all_pkgs ) {
6452 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6454 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6455 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6457 $list{$_}=1 foreach map { $_->email } @svc_acct;
6462 =item invoicing_list_addpost
6464 Adds postal invoicing to this customer. If this customer is already configured
6465 to receive postal invoices, does nothing.
6469 sub invoicing_list_addpost {
6471 return if grep { $_ eq 'POST' } $self->invoicing_list;
6472 my @invoicing_list = $self->invoicing_list;
6473 push @invoicing_list, 'POST';
6474 $self->invoicing_list(\@invoicing_list);
6477 =item invoicing_list_emailonly
6479 Returns the list of email invoice recipients (invoicing_list without non-email
6480 destinations such as POST and FAX).
6484 sub invoicing_list_emailonly {
6486 warn "$me invoicing_list_emailonly called"
6488 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
6491 =item invoicing_list_emailonly_scalar
6493 Returns the list of email invoice recipients (invoicing_list without non-email
6494 destinations such as POST and FAX) as a comma-separated scalar.
6498 sub invoicing_list_emailonly_scalar {
6500 warn "$me invoicing_list_emailonly_scalar called"
6502 join(', ', $self->invoicing_list_emailonly);
6505 =item referral_custnum_cust_main
6507 Returns the customer who referred this customer (or the empty string, if
6508 this customer was not referred).
6510 Note the difference with referral_cust_main method: This method,
6511 referral_custnum_cust_main returns the single customer (if any) who referred
6512 this customer, while referral_cust_main returns an array of customers referred
6517 sub referral_custnum_cust_main {
6519 return '' unless $self->referral_custnum;
6520 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6523 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
6525 Returns an array of customers referred by this customer (referral_custnum set
6526 to this custnum). If DEPTH is given, recurses up to the given depth, returning
6527 customers referred by customers referred by this customer and so on, inclusive.
6528 The default behavior is DEPTH 1 (no recursion).
6530 Note the difference with referral_custnum_cust_main method: This method,
6531 referral_cust_main, returns an array of customers referred BY this customer,
6532 while referral_custnum_cust_main returns the single customer (if any) who
6533 referred this customer.
6537 sub referral_cust_main {
6539 my $depth = @_ ? shift : 1;
6540 my $exclude = @_ ? shift : {};
6543 map { $exclude->{$_->custnum}++; $_; }
6544 grep { ! $exclude->{ $_->custnum } }
6545 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
6549 map { $_->referral_cust_main($depth-1, $exclude) }
6556 =item referral_cust_main_ncancelled
6558 Same as referral_cust_main, except only returns customers with uncancelled
6563 sub referral_cust_main_ncancelled {
6565 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
6568 =item referral_cust_pkg [ DEPTH ]
6570 Like referral_cust_main, except returns a flat list of all unsuspended (and
6571 uncancelled) packages for each customer. The number of items in this list may
6572 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
6576 sub referral_cust_pkg {
6578 my $depth = @_ ? shift : 1;
6580 map { $_->unsuspended_pkgs }
6581 grep { $_->unsuspended_pkgs }
6582 $self->referral_cust_main($depth);
6585 =item referring_cust_main
6587 Returns the single cust_main record for the customer who referred this customer
6588 (referral_custnum), or false.
6592 sub referring_cust_main {
6594 return '' unless $self->referral_custnum;
6595 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6598 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
6600 Applies a credit to this customer. If there is an error, returns the error,
6601 otherwise returns false.
6603 REASON can be a text string, an FS::reason object, or a scalar reference to
6604 a reasonnum. If a text string, it will be automatically inserted as a new
6605 reason, and a 'reason_type' option must be passed to indicate the
6606 FS::reason_type for the new reason.
6608 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
6610 Any other options are passed to FS::cust_credit::insert.
6615 my( $self, $amount, $reason, %options ) = @_;
6617 my $cust_credit = new FS::cust_credit {
6618 'custnum' => $self->custnum,
6619 'amount' => $amount,
6622 if ( ref($reason) ) {
6624 if ( ref($reason) eq 'SCALAR' ) {
6625 $cust_credit->reasonnum( $$reason );
6627 $cust_credit->reasonnum( $reason->reasonnum );
6631 $cust_credit->set('reason', $reason)
6634 for (qw( addlinfo eventnum )) {
6635 $cust_credit->$_( delete $options{$_} )
6636 if exists($options{$_});
6639 $cust_credit->insert(%options);
6643 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
6645 Creates a one-time charge for this customer. If there is an error, returns
6646 the error, otherwise returns false.
6648 New-style, with a hashref of options:
6650 my $error = $cust_main->charge(
6654 'start_date' => str2time('7/4/2009'),
6655 'pkg' => 'Description',
6656 'comment' => 'Comment',
6657 'additional' => [], #extra invoice detail
6658 'classnum' => 1, #pkg_class
6660 'setuptax' => '', # or 'Y' for tax exempt
6663 'taxclass' => 'Tax class',
6666 'taxproduct' => 2, #part_pkg_taxproduct
6667 'override' => {}, #XXX describe
6669 #will be filled in with the new object
6670 'cust_pkg_ref' => \$cust_pkg,
6672 #generate an invoice immediately
6674 'invoice_terms' => '', #with these terms
6680 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
6686 my ( $amount, $quantity, $start_date, $classnum );
6687 my ( $pkg, $comment, $additional );
6688 my ( $setuptax, $taxclass ); #internal taxes
6689 my ( $taxproduct, $override ); #vendor (CCH) taxes
6691 my $cust_pkg_ref = '';
6692 my ( $bill_now, $invoice_terms ) = ( 0, '' );
6693 if ( ref( $_[0] ) ) {
6694 $amount = $_[0]->{amount};
6695 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
6696 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
6697 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
6698 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
6699 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
6700 : '$'. sprintf("%.2f",$amount);
6701 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
6702 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
6703 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
6704 $additional = $_[0]->{additional} || [];
6705 $taxproduct = $_[0]->{taxproductnum};
6706 $override = { '' => $_[0]->{tax_override} };
6707 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
6708 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
6709 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
6714 $pkg = @_ ? shift : 'One-time charge';
6715 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
6717 $taxclass = @_ ? shift : '';
6721 local $SIG{HUP} = 'IGNORE';
6722 local $SIG{INT} = 'IGNORE';
6723 local $SIG{QUIT} = 'IGNORE';
6724 local $SIG{TERM} = 'IGNORE';
6725 local $SIG{TSTP} = 'IGNORE';
6726 local $SIG{PIPE} = 'IGNORE';
6728 my $oldAutoCommit = $FS::UID::AutoCommit;
6729 local $FS::UID::AutoCommit = 0;
6732 my $part_pkg = new FS::part_pkg ( {
6734 'comment' => $comment,
6738 'classnum' => ( $classnum ? $classnum : '' ),
6739 'setuptax' => $setuptax,
6740 'taxclass' => $taxclass,
6741 'taxproductnum' => $taxproduct,
6744 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
6745 ( 0 .. @$additional - 1 )
6747 'additional_count' => scalar(@$additional),
6748 'setup_fee' => $amount,
6751 my $error = $part_pkg->insert( options => \%options,
6752 tax_overrides => $override,
6755 $dbh->rollback if $oldAutoCommit;
6759 my $pkgpart = $part_pkg->pkgpart;
6760 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
6761 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
6762 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
6763 $error = $type_pkgs->insert;
6765 $dbh->rollback if $oldAutoCommit;
6770 my $cust_pkg = new FS::cust_pkg ( {
6771 'custnum' => $self->custnum,
6772 'pkgpart' => $pkgpart,
6773 'quantity' => $quantity,
6774 'start_date' => $start_date,
6775 'no_auto' => $no_auto,
6778 $error = $cust_pkg->insert;
6780 $dbh->rollback if $oldAutoCommit;
6782 } elsif ( $cust_pkg_ref ) {
6783 ${$cust_pkg_ref} = $cust_pkg;
6787 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
6788 'pkg_list' => [ $cust_pkg ],
6791 $dbh->rollback if $oldAutoCommit;
6796 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6801 #=item charge_postal_fee
6803 #Applies a one time charge this customer. If there is an error,
6804 #returns the error, returns the cust_pkg charge object or false
6805 #if there was no charge.
6809 # This should be a customer event. For that to work requires that bill
6810 # also be a customer event.
6812 sub charge_postal_fee {
6815 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
6816 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
6818 my $cust_pkg = new FS::cust_pkg ( {
6819 'custnum' => $self->custnum,
6820 'pkgpart' => $pkgpart,
6824 my $error = $cust_pkg->insert;
6825 $error ? $error : $cust_pkg;
6830 Returns all the invoices (see L<FS::cust_bill>) for this customer.
6836 map { $_ } #return $self->num_cust_bill unless wantarray;
6837 sort { $a->_date <=> $b->_date }
6838 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6841 =item open_cust_bill
6843 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
6848 sub open_cust_bill {
6852 'table' => 'cust_bill',
6853 'hashref' => { 'custnum' => $self->custnum, },
6854 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
6855 'order_by' => 'ORDER BY _date ASC',
6860 =item cust_statements
6862 Returns all the statements (see L<FS::cust_statement>) for this customer.
6866 sub cust_statement {
6868 map { $_ } #return $self->num_cust_statement unless wantarray;
6869 sort { $a->_date <=> $b->_date }
6870 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
6875 Returns all the credits (see L<FS::cust_credit>) for this customer.
6881 map { $_ } #return $self->num_cust_credit unless wantarray;
6882 sort { $a->_date <=> $b->_date }
6883 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
6886 =item cust_credit_pkgnum
6888 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
6889 package when using experimental package balances.
6893 sub cust_credit_pkgnum {
6894 my( $self, $pkgnum ) = @_;
6895 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
6896 sort { $a->_date <=> $b->_date }
6897 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
6898 'pkgnum' => $pkgnum,
6905 Returns all the payments (see L<FS::cust_pay>) for this customer.
6911 return $self->num_cust_pay unless wantarray;
6912 sort { $a->_date <=> $b->_date }
6913 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
6918 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
6919 called automatically when the cust_pay method is used in a scalar context.
6925 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
6926 my $sth = dbh->prepare($sql) or die dbh->errstr;
6927 $sth->execute($self->custnum) or die $sth->errstr;
6928 $sth->fetchrow_arrayref->[0];
6931 =item cust_pay_pkgnum
6933 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
6934 package when using experimental package balances.
6938 sub cust_pay_pkgnum {
6939 my( $self, $pkgnum ) = @_;
6940 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
6941 sort { $a->_date <=> $b->_date }
6942 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
6943 'pkgnum' => $pkgnum,
6950 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
6956 map { $_ } #return $self->num_cust_pay_void unless wantarray;
6957 sort { $a->_date <=> $b->_date }
6958 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
6961 =item cust_pay_batch
6963 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
6967 sub cust_pay_batch {
6969 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
6970 sort { $a->paybatchnum <=> $b->paybatchnum }
6971 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
6974 =item cust_pay_pending
6976 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
6977 (without status "done").
6981 sub cust_pay_pending {
6983 return $self->num_cust_pay_pending unless wantarray;
6984 sort { $a->_date <=> $b->_date }
6985 qsearch( 'cust_pay_pending', {
6986 'custnum' => $self->custnum,
6987 'status' => { op=>'!=', value=>'done' },
6992 =item num_cust_pay_pending
6994 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
6995 customer (without status "done"). Also called automatically when the
6996 cust_pay_pending method is used in a scalar context.
7000 sub num_cust_pay_pending {
7002 my $sql = " SELECT COUNT(*) FROM cust_pay_pending ".
7003 " WHERE custnum = ? AND status != 'done' ";
7004 my $sth = dbh->prepare($sql) or die dbh->errstr;
7005 $sth->execute($self->custnum) or die $sth->errstr;
7006 $sth->fetchrow_arrayref->[0];
7011 Returns all the refunds (see L<FS::cust_refund>) for this customer.
7017 map { $_ } #return $self->num_cust_refund unless wantarray;
7018 sort { $a->_date <=> $b->_date }
7019 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
7022 =item display_custnum
7024 Returns the displayed customer number for this customer: agent_custid if
7025 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
7029 sub display_custnum {
7031 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
7032 return $self->agent_custid;
7034 return $self->custnum;
7040 Returns a name string for this customer, either "Company (Last, First)" or
7047 my $name = $self->contact;
7048 $name = $self->company. " ($name)" if $self->company;
7054 Returns a name string for this (service/shipping) contact, either
7055 "Company (Last, First)" or "Last, First".
7061 if ( $self->get('ship_last') ) {
7062 my $name = $self->ship_contact;
7063 $name = $self->ship_company. " ($name)" if $self->ship_company;
7072 Returns a name string for this customer, either "Company" or "First Last".
7078 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
7081 =item ship_name_short
7083 Returns a name string for this (service/shipping) contact, either "Company"
7088 sub ship_name_short {
7090 if ( $self->get('ship_last') ) {
7091 $self->ship_company !~ /^\s*$/
7092 ? $self->ship_company
7093 : $self->ship_contact_firstlast;
7095 $self->name_company_or_firstlast;
7101 Returns this customer's full (billing) contact name only, "Last, First"
7107 $self->get('last'). ', '. $self->first;
7112 Returns this customer's full (shipping) contact name only, "Last, First"
7118 $self->get('ship_last')
7119 ? $self->get('ship_last'). ', '. $self->ship_first
7123 =item contact_firstlast
7125 Returns this customers full (billing) contact name only, "First Last".
7129 sub contact_firstlast {
7131 $self->first. ' '. $self->get('last');
7134 =item ship_contact_firstlast
7136 Returns this customer's full (shipping) contact name only, "First Last".
7140 sub ship_contact_firstlast {
7142 $self->get('ship_last')
7143 ? $self->first. ' '. $self->get('ship_last')
7144 : $self->contact_firstlast;
7149 Returns this customer's full country name
7155 code2country($self->country);
7158 =item geocode DATA_VENDOR
7160 Returns a value for the customer location as encoded by DATA_VENDOR.
7161 Currently this only makes sense for "CCH" as DATA_VENDOR.
7166 my ($self, $data_vendor) = (shift, shift); #always cch for now
7168 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
7169 return $geocode if $geocode;
7171 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7175 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7176 if $self->country eq 'US';
7180 #CCH specific location stuff
7181 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7183 my @cust_tax_location =
7185 'table' => 'cust_tax_location',
7186 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7187 'extra_sql' => $extra_sql,
7188 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
7191 $geocode = $cust_tax_location[0]->geocode
7192 if scalar(@cust_tax_location);
7201 Returns a status string for this customer, currently:
7205 =item prospect - No packages have ever been ordered
7207 =item ordered - Recurring packages all are new (not yet billed).
7209 =item active - One or more recurring packages is active
7211 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7213 =item suspended - All non-cancelled recurring packages are suspended
7215 =item cancelled - All recurring packages are cancelled
7221 sub status { shift->cust_status(@_); }
7225 # prospect ordered active inactive suspended cancelled
7226 for my $status ( FS::cust_main->statuses() ) {
7227 my $method = $status.'_sql';
7228 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7229 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7230 $sth->execute( ($self->custnum) x $numnum )
7231 or die "Error executing 'SELECT $sql': ". $sth->errstr;
7232 return $status if $sth->fetchrow_arrayref->[0];
7236 =item ucfirst_cust_status
7238 =item ucfirst_status
7240 Returns the status with the first character capitalized.
7244 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7246 sub ucfirst_cust_status {
7248 ucfirst($self->cust_status);
7253 Returns a hex triplet color string for this customer's status.
7257 use vars qw(%statuscolor);
7258 tie %statuscolor, 'Tie::IxHash',
7259 'prospect' => '7e0079', #'000000', #black? naw, purple
7260 'active' => '00CC00', #green
7261 'ordered' => '009999', #teal? cyan?
7262 'inactive' => '0000CC', #blue
7263 'suspended' => 'FF9900', #yellow
7264 'cancelled' => 'FF0000', #red
7267 sub statuscolor { shift->cust_statuscolor(@_); }
7269 sub cust_statuscolor {
7271 $statuscolor{$self->cust_status};
7276 Returns an array of hashes representing the customer's RT tickets.
7283 my $num = $conf->config('cust_main-max_tickets') || 10;
7286 if ( $conf->config('ticket_system') ) {
7287 unless ( $conf->config('ticket_system-custom_priority_field') ) {
7289 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7293 foreach my $priority (
7294 $conf->config('ticket_system-custom_priority_field-values'), ''
7296 last if scalar(@tickets) >= $num;
7298 @{ FS::TicketSystem->customer_tickets( $self->custnum,
7299 $num - scalar(@tickets),
7309 # Return services representing svc_accts in customer support packages
7310 sub support_services {
7312 my %packages = map { $_ => 1 } $conf->config('support_packages');
7314 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7315 grep { $_->part_svc->svcdb eq 'svc_acct' }
7316 map { $_->cust_svc }
7317 grep { exists $packages{ $_->pkgpart } }
7318 $self->ncancelled_pkgs;
7322 # Return a list of latitude/longitude for one of the services (if any)
7323 sub service_coordinates {
7327 grep { $_->latitude && $_->longitude }
7329 map { $_->cust_svc }
7330 $self->ncancelled_pkgs;
7332 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7337 =head1 CLASS METHODS
7343 Class method that returns the list of possible status strings for customers
7344 (see L<the status method|/status>). For example:
7346 @statuses = FS::cust_main->statuses();
7351 #my $self = shift; #could be class...
7357 Returns an SQL expression identifying prospective cust_main records (customers
7358 with no packages ever ordered)
7362 use vars qw($select_count_pkgs);
7363 $select_count_pkgs =
7364 "SELECT COUNT(*) FROM cust_pkg
7365 WHERE cust_pkg.custnum = cust_main.custnum";
7367 sub select_count_pkgs_sql {
7372 " 0 = ( $select_count_pkgs ) ";
7377 Returns an SQL expression identifying ordered cust_main records (customers with
7378 recurring packages not yet setup).
7383 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
7388 Returns an SQL expression identifying active cust_main records (customers with
7389 active recurring packages).
7394 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7399 Returns an SQL expression identifying inactive cust_main records (customers with
7400 no active recurring packages, but otherwise unsuspended/uncancelled).
7404 sub inactive_sql { "
7405 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7407 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7413 Returns an SQL expression identifying suspended cust_main records.
7418 sub suspended_sql { susp_sql(@_); }
7420 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
7422 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7428 Returns an SQL expression identifying cancelled cust_main records.
7432 sub cancelled_sql { cancel_sql(@_); }
7435 my $recurring_sql = FS::cust_pkg->recurring_sql;
7436 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7439 0 < ( $select_count_pkgs )
7440 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
7441 AND 0 = ( $select_count_pkgs AND $recurring_sql
7442 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7444 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7450 =item uncancelled_sql
7452 Returns an SQL expression identifying un-cancelled cust_main records.
7456 sub uncancelled_sql { uncancel_sql(@_); }
7457 sub uncancel_sql { "
7458 ( 0 < ( $select_count_pkgs
7459 AND ( cust_pkg.cancel IS NULL
7460 OR cust_pkg.cancel = 0
7463 OR 0 = ( $select_count_pkgs )
7469 Returns an SQL fragment to retreive the balance.
7474 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7475 WHERE cust_bill.custnum = cust_main.custnum )
7476 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
7477 WHERE cust_pay.custnum = cust_main.custnum )
7478 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
7479 WHERE cust_credit.custnum = cust_main.custnum )
7480 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
7481 WHERE cust_refund.custnum = cust_main.custnum )
7484 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
7486 Returns an SQL fragment to retreive the balance for this customer, optionally
7487 considering invoices with date earlier than START_TIME, and not
7488 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7489 total_unapplied_payments).
7491 Times are specified as SQL fragments or numeric
7492 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7493 L<Date::Parse> for conversion functions. The empty string can be passed
7494 to disable that time constraint completely.
7496 Available options are:
7500 =item unapplied_date
7502 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)
7507 set to true to remove all customer comparison clauses, for totals
7512 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
7517 JOIN clause (typically used with the total option)
7521 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
7522 time will be ignored. Note that START_TIME and END_TIME only limit the date
7523 range for invoices and I<unapplied> payments, credits, and refunds.
7529 sub balance_date_sql {
7530 my( $class, $start, $end, %opt ) = @_;
7532 my $cutoff = $opt{'cutoff'};
7534 my $owed = FS::cust_bill->owed_sql($cutoff);
7535 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
7536 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
7537 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7539 my $j = $opt{'join'} || '';
7541 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
7542 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
7543 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
7544 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
7546 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
7547 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
7548 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
7549 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
7554 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
7556 Returns an SQL fragment to retreive the total unapplied payments for this
7557 customer, only considering invoices with date earlier than START_TIME, and
7558 optionally not later than END_TIME.
7560 Times are specified as SQL fragments or numeric
7561 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7562 L<Date::Parse> for conversion functions. The empty string can be passed
7563 to disable that time constraint completely.
7565 Available options are:
7569 sub unapplied_payments_date_sql {
7570 my( $class, $start, $end, %opt ) = @_;
7572 my $cutoff = $opt{'cutoff'};
7574 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7576 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
7577 'unapplied_date'=>1 );
7579 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
7582 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7584 Helper method for balance_date_sql; name (and usage) subject to change
7585 (suggestions welcome).
7587 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
7588 cust_refund, cust_credit or cust_pay).
7590 If TABLE is "cust_bill" or the unapplied_date option is true, only
7591 considers records with date earlier than START_TIME, and optionally not
7592 later than END_TIME .
7596 sub _money_table_where {
7597 my( $class, $table, $start, $end, %opt ) = @_;
7600 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
7601 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
7602 push @where, "$table._date <= $start" if defined($start) && length($start);
7603 push @where, "$table._date > $end" if defined($end) && length($end);
7605 push @where, @{$opt{'where'}} if $opt{'where'};
7606 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
7612 =item search HASHREF
7616 Returns a qsearch hash expression to search for parameters specified in
7617 HASHREF. Valid parameters are
7625 =item cancelled_pkgs
7631 listref of start date, end date
7641 =item current_balance
7643 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
7647 =item flattened_pkgs
7656 my ($class, $params) = @_;
7667 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
7669 "cust_main.agentnum = $1";
7673 # do the same for user
7676 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
7678 "cust_main.usernum = $1";
7685 #prospect ordered active inactive suspended cancelled
7686 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
7687 my $method = $params->{'status'}. '_sql';
7688 #push @where, $class->$method();
7689 push @where, FS::cust_main->$method();
7693 # parse cancelled package checkbox
7698 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
7699 unless $params->{'cancelled_pkgs'};
7702 # parse without census tract checkbox
7705 push @where, "(censustract = '' or censustract is null)"
7706 if $params->{'no_censustract'};
7712 foreach my $field (qw( signupdate )) {
7714 next unless exists($params->{$field});
7716 my($beginning, $ending, $hour) = @{$params->{$field}};
7719 "cust_main.$field IS NOT NULL",
7720 "cust_main.$field >= $beginning",
7721 "cust_main.$field <= $ending";
7723 # XXX: do this for mysql and/or pull it out of here
7725 if ($dbh->{Driver}->{Name} eq 'Pg') {
7726 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
7729 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
7733 $orderby ||= "ORDER BY cust_main.$field";
7741 if ( $params->{'classnum'} ) {
7743 my @classnum = ref( $params->{'classnum'} )
7744 ? @{ $params->{'classnum'} }
7745 : ( $params->{'classnum'} );
7747 @classnum = grep /^(\d*)$/, @classnum;
7750 push @where, '( '. join(' OR ', map {
7751 $_ ? "cust_main.classnum = $_"
7752 : "cust_main.classnum IS NULL"
7765 if ( $params->{'payby'} ) {
7767 my @payby = ref( $params->{'payby'} )
7768 ? @{ $params->{'payby'} }
7769 : ( $params->{'payby'} );
7771 @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
7773 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
7779 # paydate_year / paydate_month
7782 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
7784 $params->{'paydate_month'} =~ /^(\d\d?)$/
7785 or die "paydate_year without paydate_month?";
7789 'paydate IS NOT NULL',
7791 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
7799 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
7801 if ( $1 eq 'NULL' ) {
7803 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
7806 "cust_main.invoice_terms IS NOT NULL",
7807 "cust_main.invoice_terms = '$1'";
7815 if ( $params->{'current_balance'} ) {
7817 #my $balance_sql = $class->balance_sql();
7818 my $balance_sql = FS::cust_main->balance_sql();
7820 my @current_balance =
7821 ref( $params->{'current_balance'} )
7822 ? @{ $params->{'current_balance'} }
7823 : ( $params->{'current_balance'} );
7825 push @where, map { s/current_balance/$balance_sql/; $_ }
7834 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
7836 "cust_main.custbatch = '$1'";
7840 # setup queries, subs, etc. for the search
7843 $orderby ||= 'ORDER BY custnum';
7845 # here is the agent virtualization
7846 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
7848 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
7850 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
7852 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
7854 my $select = join(', ',
7855 'cust_main.custnum',
7856 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
7859 my(@extra_headers) = ();
7860 my(@extra_fields) = ();
7862 if ($params->{'flattened_pkgs'}) {
7864 if ($dbh->{Driver}->{Name} eq 'Pg') {
7866 $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";
7868 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
7869 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
7870 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
7872 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
7873 "omitting packing information from report.";
7876 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";
7878 my $sth = dbh->prepare($header_query) or die dbh->errstr;
7879 $sth->execute() or die $sth->errstr;
7880 my $headerrow = $sth->fetchrow_arrayref;
7881 my $headercount = $headerrow ? $headerrow->[0] : 0;
7882 while($headercount) {
7883 unshift @extra_headers, "Package ". $headercount;
7884 unshift @extra_fields, eval q!sub {my $c = shift;
7885 my @a = split '\|', $c->magic;
7886 my $p = $a[!.--$headercount. q!];
7894 'table' => 'cust_main',
7895 'select' => $select,
7897 'extra_sql' => $extra_sql,
7898 'order_by' => $orderby,
7899 'count_query' => $count_query,
7900 'extra_headers' => \@extra_headers,
7901 'extra_fields' => \@extra_fields,
7906 =item email_search_result HASHREF
7910 Emails a notice to the specified customers.
7912 Valid parameters are those of the L<search> method, plus the following:
7934 Optional job queue job for status updates.
7938 Returns an error message, or false for success.
7940 If an error occurs during any email, stops the enture send and returns that
7941 error. Presumably if you're getting SMTP errors aborting is better than
7942 retrying everything.
7946 sub email_search_result {
7947 my($class, $params) = @_;
7949 my $from = delete $params->{from};
7950 my $subject = delete $params->{subject};
7951 my $html_body = delete $params->{html_body};
7952 my $text_body = delete $params->{text_body};
7954 my $job = delete $params->{'job'};
7956 $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
7957 unless ref($params->{'payby'});
7959 my $sql_query = $class->search($params);
7961 my $count_query = delete($sql_query->{'count_query'});
7962 my $count_sth = dbh->prepare($count_query)
7963 or die "Error preparing $count_query: ". dbh->errstr;
7965 or die "Error executing $count_query: ". $count_sth->errstr;
7966 my $count_arrayref = $count_sth->fetchrow_arrayref;
7967 my $num_cust = $count_arrayref->[0];
7969 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
7970 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
7973 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
7975 #eventually order+limit magic to reduce memory use?
7976 foreach my $cust_main ( qsearch($sql_query) ) {
7978 my $to = $cust_main->invoicing_list_emailonly_scalar;
7981 my $error = send_email(
7985 'subject' => $subject,
7986 'html_body' => $html_body,
7987 'text_body' => $text_body,
7990 return $error if $error;
7992 if ( $job ) { #progressbar foo
7994 if ( time - $min_sec > $last ) {
7995 my $error = $job->update_statustext(
7996 int( 100 * $num / $num_cust )
7998 die $error if $error;
8008 use Storable qw(thaw);
8011 sub process_email_search_result {
8013 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
8015 my $param = thaw(decode_base64(shift));
8016 warn Dumper($param) if $DEBUG;
8018 $param->{'job'} = $job;
8020 $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
8021 unless ref($param->{'payby'});
8023 my $error = FS::cust_main->email_search_result( $param );
8024 die $error if $error;
8028 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
8030 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
8031 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
8032 specified (the appropriate ship_ field is also searched).
8034 Additional options are the same as FS::Record::qsearch
8039 my( $self, $fuzzy, $hash, @opt) = @_;
8044 check_and_rebuild_fuzzyfiles();
8045 foreach my $field ( keys %$fuzzy ) {
8047 my $all = $self->all_X($field);
8048 next unless scalar(@$all);
8051 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
8054 foreach ( keys %match ) {
8055 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
8056 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
8059 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
8062 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
8064 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
8072 Returns a masked version of the named field
8077 my ($self,$field) = @_;
8081 'x'x(length($self->getfield($field))-4).
8082 substr($self->getfield($field), (length($self->getfield($field))-4));
8092 =item smart_search OPTION => VALUE ...
8094 Accepts the following options: I<search>, the string to search for. The string
8095 will be searched for as a customer number, phone number, name or company name,
8096 as an exact, or, in some cases, a substring or fuzzy match (see the source code
8097 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
8098 skip fuzzy matching when an exact match is found.
8100 Any additional options are treated as an additional qualifier on the search
8103 Returns a (possibly empty) array of FS::cust_main objects.
8110 #here is the agent virtualization
8111 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8115 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
8116 my $search = delete $options{'search'};
8117 ( my $alphanum_search = $search ) =~ s/\W//g;
8119 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8121 #false laziness w/Record::ut_phone
8122 my $phonen = "$1-$2-$3";
8123 $phonen .= " x$4" if $4;
8125 push @cust_main, qsearch( {
8126 'table' => 'cust_main',
8127 'hashref' => { %options },
8128 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8130 join(' OR ', map "$_ = '$phonen'",
8131 qw( daytime night fax
8132 ship_daytime ship_night ship_fax )
8135 " AND $agentnums_sql", #agent virtualization
8138 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8139 #try looking for matches with extensions unless one was specified
8141 push @cust_main, qsearch( {
8142 'table' => 'cust_main',
8143 'hashref' => { %options },
8144 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8146 join(' OR ', map "$_ LIKE '$phonen\%'",
8148 ship_daytime ship_night )
8151 " AND $agentnums_sql", #agent virtualization
8156 # custnum search (also try agent_custid), with some tweaking options if your
8157 # legacy cust "numbers" have letters
8160 if ( $search =~ /^\s*(\d+)\s*$/
8161 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8162 && $search =~ /^\s*(\w\w?\d+)\s*$/
8164 || ( $conf->exists('address1-search' )
8165 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
8172 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
8173 push @cust_main, qsearch( {
8174 'table' => 'cust_main',
8175 'hashref' => { 'custnum' => $num, %options },
8176 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8180 push @cust_main, qsearch( {
8181 'table' => 'cust_main',
8182 'hashref' => { 'agent_custid' => $num, %options },
8183 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8186 if ( $conf->exists('address1-search') ) {
8187 my $len = length($num);
8189 foreach my $prefix ( '', 'ship_' ) {
8190 push @cust_main, qsearch( {
8191 'table' => 'cust_main',
8192 'hashref' => { %options, },
8194 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8195 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
8196 " AND $agentnums_sql",
8201 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8203 my($company, $last, $first) = ( $1, $2, $3 );
8205 # "Company (Last, First)"
8206 #this is probably something a browser remembered,
8207 #so just do an exact search (but case-insensitive, so USPS standardization
8208 #doesn't throw a wrench in the works)
8210 foreach my $prefix ( '', 'ship_' ) {
8211 push @cust_main, qsearch( {
8212 'table' => 'cust_main',
8213 'hashref' => { %options },
8215 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8217 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
8218 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
8219 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
8225 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8226 # try (ship_){last,company}
8230 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8231 # # full strings the browser remembers won't work
8232 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8234 use Lingua::EN::NameParse;
8235 my $NameParse = new Lingua::EN::NameParse(
8237 allow_reversed => 1,
8240 my($last, $first) = ( '', '' );
8241 #maybe disable this too and just rely on NameParse?
8242 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8244 ($last, $first) = ( $1, $2 );
8246 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
8247 } elsif ( ! $NameParse->parse($value) ) {
8249 my %name = $NameParse->components;
8250 $first = $name{'given_name_1'};
8251 $last = $name{'surname_1'};
8255 if ( $first && $last ) {
8257 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8260 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8262 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8263 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8266 push @cust_main, qsearch( {
8267 'table' => 'cust_main',
8268 'hashref' => \%options,
8269 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8272 # or it just be something that was typed in... (try that in a sec)
8276 my $q_value = dbh->quote($value);
8279 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8280 $sql .= " ( LOWER(last) = $q_value
8281 OR LOWER(company) = $q_value
8282 OR LOWER(ship_last) = $q_value
8283 OR LOWER(ship_company) = $q_value
8285 $sql .= " OR LOWER(address1) = $q_value
8286 OR LOWER(ship_address1) = $q_value
8288 if $conf->exists('address1-search');
8291 push @cust_main, qsearch( {
8292 'table' => 'cust_main',
8293 'hashref' => \%options,
8294 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8297 #no exact match, trying substring/fuzzy
8298 #always do substring & fuzzy (unless they're explicity config'ed off)
8299 #getting complaints searches are not returning enough
8300 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8302 #still some false laziness w/search (was search/cust_main.cgi)
8307 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
8308 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8311 if ( $first && $last ) {
8314 { 'first' => { op=>'ILIKE', value=>"%$first%" },
8315 'last' => { op=>'ILIKE', value=>"%$last%" },
8317 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
8318 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
8325 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
8326 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
8330 if ( $conf->exists('address1-search') ) {
8332 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
8333 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
8337 foreach my $hashref ( @hashrefs ) {
8339 push @cust_main, qsearch( {
8340 'table' => 'cust_main',
8341 'hashref' => { %$hashref,
8344 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8353 " AND $agentnums_sql", #extra_sql #agent virtualization
8356 if ( $first && $last ) {
8357 push @cust_main, FS::cust_main->fuzzy_search(
8358 { 'last' => $last, #fuzzy hashref
8359 'first' => $first }, #
8363 foreach my $field ( 'last', 'company' ) {
8365 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8367 if ( $conf->exists('address1-search') ) {
8369 FS::cust_main->fuzzy_search( { 'address1' => $value }, @fuzopts );
8376 #eliminate duplicates
8378 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8386 Accepts the following options: I<email>, the email address to search for. The
8387 email address will be searched for as an email invoice destination and as an
8390 #Any additional options are treated as an additional qualifier on the search
8391 #(i.e. I<agentnum>).
8393 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8403 my $email = delete $options{'email'};
8405 #we're only being used by RT at the moment... no agent virtualization yet
8406 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8410 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8412 my ( $user, $domain ) = ( $1, $2 );
8414 warn "$me smart_search: searching for $user in domain $domain"
8420 'table' => 'cust_main_invoice',
8421 'hashref' => { 'dest' => $email },
8428 map $_->cust_svc->cust_pkg,
8430 'table' => 'svc_acct',
8431 'hashref' => { 'username' => $user, },
8433 'AND ( SELECT domain FROM svc_domain
8434 WHERE svc_acct.domsvc = svc_domain.svcnum
8435 ) = '. dbh->quote($domain),
8441 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8443 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8450 =item check_and_rebuild_fuzzyfiles
8454 sub check_and_rebuild_fuzzyfiles {
8455 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8456 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8459 =item rebuild_fuzzyfiles
8463 sub rebuild_fuzzyfiles {
8465 use Fcntl qw(:flock);
8467 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8468 mkdir $dir, 0700 unless -d $dir;
8470 foreach my $fuzzy ( @fuzzyfields ) {
8472 open(LOCK,">>$dir/cust_main.$fuzzy")
8473 or die "can't open $dir/cust_main.$fuzzy: $!";
8475 or die "can't lock $dir/cust_main.$fuzzy: $!";
8477 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8478 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8480 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8481 my $sth = dbh->prepare("SELECT $field FROM cust_main".
8482 " WHERE $field != '' AND $field IS NOT NULL");
8483 $sth->execute or die $sth->errstr;
8485 while ( my $row = $sth->fetchrow_arrayref ) {
8486 print CACHE $row->[0]. "\n";
8491 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8493 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8504 my( $self, $field ) = @_;
8505 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8506 open(CACHE,"<$dir/cust_main.$field")
8507 or die "can't open $dir/cust_main.$field: $!";
8508 my @array = map { chomp; $_; } <CACHE>;
8513 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
8517 sub append_fuzzyfiles {
8518 #my( $first, $last, $company ) = @_;
8520 &check_and_rebuild_fuzzyfiles;
8522 use Fcntl qw(:flock);
8524 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8526 foreach my $field (@fuzzyfields) {
8531 open(CACHE,">>$dir/cust_main.$field")
8532 or die "can't open $dir/cust_main.$field: $!";
8533 flock(CACHE,LOCK_EX)
8534 or die "can't lock $dir/cust_main.$field: $!";
8536 print CACHE "$value\n";
8538 flock(CACHE,LOCK_UN)
8539 or die "can't unlock $dir/cust_main.$field: $!";
8554 #warn join('-',keys %$param);
8555 my $fh = $param->{filehandle};
8556 my @fields = @{$param->{fields}};
8558 eval "use Text::CSV_XS;";
8561 my $csv = new Text::CSV_XS;
8568 local $SIG{HUP} = 'IGNORE';
8569 local $SIG{INT} = 'IGNORE';
8570 local $SIG{QUIT} = 'IGNORE';
8571 local $SIG{TERM} = 'IGNORE';
8572 local $SIG{TSTP} = 'IGNORE';
8573 local $SIG{PIPE} = 'IGNORE';
8575 my $oldAutoCommit = $FS::UID::AutoCommit;
8576 local $FS::UID::AutoCommit = 0;
8579 #while ( $columns = $csv->getline($fh) ) {
8581 while ( defined($line=<$fh>) ) {
8583 $csv->parse($line) or do {
8584 $dbh->rollback if $oldAutoCommit;
8585 return "can't parse: ". $csv->error_input();
8588 my @columns = $csv->fields();
8589 #warn join('-',@columns);
8592 foreach my $field ( @fields ) {
8593 $row{$field} = shift @columns;
8596 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
8597 unless ( $cust_main ) {
8598 $dbh->rollback if $oldAutoCommit;
8599 return "unknown custnum $row{'custnum'}";
8602 if ( $row{'amount'} > 0 ) {
8603 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8605 $dbh->rollback if $oldAutoCommit;
8609 } elsif ( $row{'amount'} < 0 ) {
8610 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8613 $dbh->rollback if $oldAutoCommit;
8623 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8625 return "Empty file!" unless $imported;
8631 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8633 Sends a templated email notification to the customer (see L<Text::Template>).
8635 OPTIONS is a hash and may include
8637 I<from> - the email sender (default is invoice_from)
8639 I<to> - comma-separated scalar or arrayref of recipients
8640 (default is invoicing_list)
8642 I<subject> - The subject line of the sent email notification
8643 (default is "Notice from company_name")
8645 I<extra_fields> - a hashref of name/value pairs which will be substituted
8648 The following variables are vavailable in the template.
8650 I<$first> - the customer first name
8651 I<$last> - the customer last name
8652 I<$company> - the customer company
8653 I<$payby> - a description of the method of payment for the customer
8654 # would be nice to use FS::payby::shortname
8655 I<$payinfo> - the account information used to collect for this customer
8656 I<$expdate> - the expiration of the customer payment in seconds from epoch
8661 my ($self, $template, %options) = @_;
8663 return unless $conf->exists($template);
8665 my $from = $conf->config('invoice_from', $self->agentnum)
8666 if $conf->exists('invoice_from', $self->agentnum);
8667 $from = $options{from} if exists($options{from});
8669 my $to = join(',', $self->invoicing_list_emailonly);
8670 $to = $options{to} if exists($options{to});
8672 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
8673 if $conf->exists('company_name', $self->agentnum);
8674 $subject = $options{subject} if exists($options{subject});
8676 my $notify_template = new Text::Template (TYPE => 'ARRAY',
8677 SOURCE => [ map "$_\n",
8678 $conf->config($template)]
8680 or die "can't create new Text::Template object: Text::Template::ERROR";
8681 $notify_template->compile()
8682 or die "can't compile template: Text::Template::ERROR";
8684 $FS::notify_template::_template::company_name =
8685 $conf->config('company_name', $self->agentnum);
8686 $FS::notify_template::_template::company_address =
8687 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
8689 my $paydate = $self->paydate || '2037-12-31';
8690 $FS::notify_template::_template::first = $self->first;
8691 $FS::notify_template::_template::last = $self->last;
8692 $FS::notify_template::_template::company = $self->company;
8693 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
8694 my $payby = $self->payby;
8695 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8696 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8698 #credit cards expire at the end of the month/year of their exp date
8699 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8700 $FS::notify_template::_template::payby = 'credit card';
8701 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8702 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8704 }elsif ($payby eq 'COMP') {
8705 $FS::notify_template::_template::payby = 'complimentary account';
8707 $FS::notify_template::_template::payby = 'current method';
8709 $FS::notify_template::_template::expdate = $expire_time;
8711 for (keys %{$options{extra_fields}}){
8713 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
8716 send_email(from => $from,
8718 subject => $subject,
8719 body => $notify_template->fill_in( PACKAGE =>
8720 'FS::notify_template::_template' ),
8725 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8727 Generates a templated notification to the customer (see L<Text::Template>).
8729 OPTIONS is a hash and may include
8731 I<extra_fields> - a hashref of name/value pairs which will be substituted
8732 into the template. These values may override values mentioned below
8733 and those from the customer record.
8735 The following variables are available in the template instead of or in addition
8736 to the fields of the customer record.
8738 I<$payby> - a description of the method of payment for the customer
8739 # would be nice to use FS::payby::shortname
8740 I<$payinfo> - the masked account information used to collect for this customer
8741 I<$expdate> - the expiration of the customer payment method in seconds from epoch
8742 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
8746 sub generate_letter {
8747 my ($self, $template, %options) = @_;
8749 return unless $conf->exists($template);
8751 my $letter_template = new Text::Template
8753 SOURCE => [ map "$_\n", $conf->config($template)],
8754 DELIMITERS => [ '[@--', '--@]' ],
8756 or die "can't create new Text::Template object: Text::Template::ERROR";
8758 $letter_template->compile()
8759 or die "can't compile template: Text::Template::ERROR";
8761 my %letter_data = map { $_ => $self->$_ } $self->fields;
8762 $letter_data{payinfo} = $self->mask_payinfo;
8764 #my $paydate = $self->paydate || '2037-12-31';
8765 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
8767 my $payby = $self->payby;
8768 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8769 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8771 #credit cards expire at the end of the month/year of their exp date
8772 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8773 $letter_data{payby} = 'credit card';
8774 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8775 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8777 }elsif ($payby eq 'COMP') {
8778 $letter_data{payby} = 'complimentary account';
8780 $letter_data{payby} = 'current method';
8782 $letter_data{expdate} = $expire_time;
8784 for (keys %{$options{extra_fields}}){
8785 $letter_data{$_} = $options{extra_fields}->{$_};
8788 unless(exists($letter_data{returnaddress})){
8789 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
8790 $self->agent_template)
8792 if ( length($retadd) ) {
8793 $letter_data{returnaddress} = $retadd;
8794 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
8795 $letter_data{returnaddress} =
8796 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
8797 $conf->config('company_address', $self->agentnum)
8800 $letter_data{returnaddress} = '~';
8804 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
8806 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
8808 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
8809 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
8813 ) or die "can't open temp file: $!\n";
8815 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
8817 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
8821 =item print_ps TEMPLATE
8823 Returns an postscript letter filled in from TEMPLATE, as a scalar.
8829 my $file = $self->generate_letter(@_);
8830 FS::Misc::generate_ps($file);
8833 =item print TEMPLATE
8835 Prints the filled in template.
8837 TEMPLATE is the name of a L<Text::Template> to fill in and print.
8841 sub queueable_print {
8844 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
8845 or die "invalid customer number: " . $opt{custvnum};
8847 my $error = $self->print( $opt{template} );
8848 die $error if $error;
8852 my ($self, $template) = (shift, shift);
8853 do_print [ $self->print_ps($template) ];
8856 #these three subs should just go away once agent stuff is all config overrides
8858 sub agent_template {
8860 $self->_agent_plandata('agent_templatename');
8863 sub agent_invoice_from {
8865 $self->_agent_plandata('agent_invoice_from');
8868 sub _agent_plandata {
8869 my( $self, $option ) = @_;
8871 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
8872 #agent-specific Conf
8874 use FS::part_event::Condition;
8876 my $agentnum = $self->agentnum;
8878 my $regexp = regexp_sql();
8880 my $part_event_option =
8882 'select' => 'part_event_option.*',
8883 'table' => 'part_event_option',
8885 LEFT JOIN part_event USING ( eventpart )
8886 LEFT JOIN part_event_option AS peo_agentnum
8887 ON ( part_event.eventpart = peo_agentnum.eventpart
8888 AND peo_agentnum.optionname = 'agentnum'
8889 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
8891 LEFT JOIN part_event_condition
8892 ON ( part_event.eventpart = part_event_condition.eventpart
8893 AND part_event_condition.conditionname = 'cust_bill_age'
8895 LEFT JOIN part_event_condition_option
8896 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
8897 AND part_event_condition_option.optionname = 'age'
8900 #'hashref' => { 'optionname' => $option },
8901 #'hashref' => { 'part_event_option.optionname' => $option },
8903 " WHERE part_event_option.optionname = ". dbh->quote($option).
8904 " AND action = 'cust_bill_send_agent' ".
8905 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
8906 " AND peo_agentnum.optionname = 'agentnum' ".
8907 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
8909 CASE WHEN part_event_condition_option.optionname IS NULL
8911 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
8913 , part_event.weight".
8917 unless ( $part_event_option ) {
8918 return $self->agent->invoice_template || ''
8919 if $option eq 'agent_templatename';
8923 $part_event_option->optionvalue;
8927 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
8929 Subroutine (not a method), designed to be called from the queue.
8931 Takes a list of options and values.
8933 Pulls up the customer record via the custnum option and calls bill_and_collect.
8938 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
8940 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
8941 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
8943 $cust_main->bill_and_collect( %args );
8946 sub _upgrade_data { #class method
8947 my ($class, %opts) = @_;
8949 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
8950 my $sth = dbh->prepare($sql) or die dbh->errstr;
8951 $sth->execute or die $sth->errstr;
8953 local($ignore_expired_card) = 1;
8954 $class->_upgrade_otaker(%opts);
8964 The delete method should possibly take an FS::cust_main object reference
8965 instead of a scalar customer number.
8967 Bill and collect options should probably be passed as references instead of a
8970 There should probably be a configuration file with a list of allowed credit
8973 No multiple currency support (probably a larger project than just this module).
8975 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
8977 Birthdates rely on negative epoch values.
8979 The payby for card/check batches is broken. With mixed batching, bad
8982 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
8986 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
8987 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
8988 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.