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;
67 use FS::payment_gateway;
68 use FS::agent_payment_gateway;
72 @EXPORT_OK = qw( smart_search );
74 $realtime_bop_decline_quiet = 0;
76 # 1 is mostly method/subroutine entry and options
77 # 2 traces progress of some operations
78 # 3 is even more information including possibly sensitive data
80 $me = '[FS::cust_main]';
83 $ignore_expired_card = 0;
86 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
88 @encrypted_fields = ('payinfo', 'paycvv');
89 sub nohistory_fields { ('paycvv'); }
91 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
93 #ask FS::UID to run this stuff for us later
94 #$FS::UID::callback{'FS::cust_main'} = sub {
95 install_callback FS::UID sub {
97 #yes, need it for stuff below (prolly should be cached)
102 my ( $hashref, $cache ) = @_;
103 if ( exists $hashref->{'pkgnum'} ) {
104 #@{ $self->{'_pkgnum'} } = ();
105 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
106 $self->{'_pkgnum'} = $subcache;
107 #push @{ $self->{'_pkgnum'} },
108 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
114 FS::cust_main - Object methods for cust_main records
120 $record = new FS::cust_main \%hash;
121 $record = new FS::cust_main { 'column' => 'value' };
123 $error = $record->insert;
125 $error = $new_record->replace($old_record);
127 $error = $record->delete;
129 $error = $record->check;
131 @cust_pkg = $record->all_pkgs;
133 @cust_pkg = $record->ncancelled_pkgs;
135 @cust_pkg = $record->suspended_pkgs;
137 $error = $record->bill;
138 $error = $record->bill %options;
139 $error = $record->bill 'time' => $time;
141 $error = $record->collect;
142 $error = $record->collect %options;
143 $error = $record->collect 'invoice_time' => $time,
148 An FS::cust_main object represents a customer. FS::cust_main inherits from
149 FS::Record. The following fields are currently supported:
155 Primary key (assigned automatically for new customers)
159 Agent (see L<FS::agent>)
163 Advertising source (see L<FS::part_referral>)
175 Cocial security number (optional)
191 (optional, see L<FS::cust_main_county>)
195 (see L<FS::cust_main_county>)
201 (see L<FS::cust_main_county>)
237 (optional, see L<FS::cust_main_county>)
241 (see L<FS::cust_main_county>)
247 (see L<FS::cust_main_county>)
263 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
267 Payment Information (See L<FS::payinfo_Mixin> for data format)
271 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
275 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
279 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
283 Start date month (maestro/solo cards only)
287 Start date year (maestro/solo cards only)
291 Issue number (maestro/solo cards only)
295 Name on card or billing name
299 IP address from which payment information was received
303 Tax exempt, empty or `Y'
307 Order taker (see L<FS::access_user>)
313 =item referral_custnum
315 Referring customer number
319 Enable individual CDR spooling, empty or `Y'
323 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
327 Discourage individual CDR printing, empty or `Y'
337 Creates a new customer. To add the customer to the database, see L<"insert">.
339 Note that this stores the hash reference, not a distinct copy of the hash it
340 points to. You can ask the object for a copy with the I<hash> method.
344 sub table { 'cust_main'; }
346 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
348 Adds this customer to the database. If there is an error, returns the error,
349 otherwise returns false.
351 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
352 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
353 are inserted atomicly, or the transaction is rolled back. Passing an empty
354 hash reference is equivalent to not supplying this parameter. There should be
355 a better explanation of this, but until then, here's an example:
358 tie %hash, 'Tie::RefHash'; #this part is important
360 $cust_pkg => [ $svc_acct ],
363 $cust_main->insert( \%hash );
365 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
366 be set as the invoicing list (see L<"invoicing_list">). Errors return as
367 expected and rollback the entire transaction; it is not necessary to call
368 check_invoicing_list first. The invoicing_list is set after the records in the
369 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
370 invoicing_list destination to the newly-created svc_acct. Here's an example:
372 $cust_main->insert( {}, [ $email, 'POST' ] );
374 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
376 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
377 on the supplied jobnum (they will not run until the specific job completes).
378 This can be used to defer provisioning until some action completes (such
379 as running the customer's credit card successfully).
381 The I<noexport> option is deprecated. If I<noexport> is set true, no
382 provisioning jobs (exports) are scheduled. (You can schedule them later with
383 the B<reexport> method.)
385 The I<tax_exemption> option can be set to an arrayref of tax names.
386 FS::cust_main_exemption records will be created and inserted.
392 my $cust_pkgs = @_ ? shift : {};
393 my $invoicing_list = @_ ? shift : '';
395 warn "$me insert called with options ".
396 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
399 local $SIG{HUP} = 'IGNORE';
400 local $SIG{INT} = 'IGNORE';
401 local $SIG{QUIT} = 'IGNORE';
402 local $SIG{TERM} = 'IGNORE';
403 local $SIG{TSTP} = 'IGNORE';
404 local $SIG{PIPE} = 'IGNORE';
406 my $oldAutoCommit = $FS::UID::AutoCommit;
407 local $FS::UID::AutoCommit = 0;
410 my $prepay_identifier = '';
411 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
413 if ( $self->payby eq 'PREPAY' ) {
415 $self->payby('BILL');
416 $prepay_identifier = $self->payinfo;
419 warn " looking up prepaid card $prepay_identifier\n"
422 my $error = $self->get_prepay( $prepay_identifier,
423 'amount_ref' => \$amount,
424 'seconds_ref' => \$seconds,
425 'upbytes_ref' => \$upbytes,
426 'downbytes_ref' => \$downbytes,
427 'totalbytes_ref' => \$totalbytes,
430 $dbh->rollback if $oldAutoCommit;
431 #return "error applying prepaid card (transaction rolled back): $error";
435 $payby = 'PREP' if $amount;
437 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
440 $self->payby('BILL');
441 $amount = $self->paid;
445 warn " inserting $self\n"
448 $self->signupdate(time) unless $self->signupdate;
450 $self->auto_agent_custid()
451 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
453 my $error = $self->SUPER::insert;
455 $dbh->rollback if $oldAutoCommit;
456 #return "inserting cust_main record (transaction rolled back): $error";
460 warn " setting invoicing list\n"
463 if ( $invoicing_list ) {
464 $error = $self->check_invoicing_list( $invoicing_list );
466 $dbh->rollback if $oldAutoCommit;
467 #return "checking invoicing_list (transaction rolled back): $error";
470 $self->invoicing_list( $invoicing_list );
473 warn " setting cust_main_exemption\n"
476 my $tax_exemption = delete $options{'tax_exemption'};
477 if ( $tax_exemption ) {
478 foreach my $taxname ( @$tax_exemption ) {
479 my $cust_main_exemption = new FS::cust_main_exemption {
480 'custnum' => $self->custnum,
481 'taxname' => $taxname,
483 my $error = $cust_main_exemption->insert;
485 $dbh->rollback if $oldAutoCommit;
486 return "inserting cust_main_exemption (transaction rolled back): $error";
491 if ( $conf->config('cust_main-skeleton_tables')
492 && $conf->config('cust_main-skeleton_custnum') ) {
494 warn " inserting skeleton records\n"
497 my $error = $self->start_copy_skel;
499 $dbh->rollback if $oldAutoCommit;
505 warn " ordering packages\n"
508 $error = $self->order_pkgs( $cust_pkgs,
510 'seconds_ref' => \$seconds,
511 'upbytes_ref' => \$upbytes,
512 'downbytes_ref' => \$downbytes,
513 'totalbytes_ref' => \$totalbytes,
516 $dbh->rollback if $oldAutoCommit;
521 $dbh->rollback if $oldAutoCommit;
522 return "No svc_acct record to apply pre-paid time";
524 if ( $upbytes || $downbytes || $totalbytes ) {
525 $dbh->rollback if $oldAutoCommit;
526 return "No svc_acct record to apply pre-paid data";
530 warn " inserting initial $payby payment of $amount\n"
532 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
534 $dbh->rollback if $oldAutoCommit;
535 return "inserting payment (transaction rolled back): $error";
539 unless ( $import || $skip_fuzzyfiles ) {
540 warn " queueing fuzzyfiles update\n"
542 $error = $self->queue_fuzzyfiles_update;
544 $dbh->rollback if $oldAutoCommit;
545 return "updating fuzzy search cache: $error";
549 warn " insert complete; committing transaction\n"
552 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
557 use File::CounterFile;
558 sub auto_agent_custid {
561 my $format = $conf->config('cust_main-auto_agent_custid');
563 if ( $format eq '1YMMXXXXXXXX' ) {
565 my $counter = new File::CounterFile 'cust_main.agent_custid';
568 my $ym = 100000000000 + time2str('%y%m00000000', time);
569 if ( $ym > $counter->value ) {
570 $counter->{'value'} = $agent_custid = $ym;
571 $counter->{'updated'} = 1;
573 $agent_custid = $counter->inc;
579 die "Unknown cust_main-auto_agent_custid format: $format";
582 $self->agent_custid($agent_custid);
586 sub start_copy_skel {
589 #'mg_user_preference' => {},
590 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
591 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
592 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
593 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
594 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
597 _copy_skel( 'cust_main', #tablename
598 $conf->config('cust_main-skeleton_custnum'), #sourceid
599 $self->custnum, #destid
600 @tables, #child tables
604 #recursive subroutine, not a method
606 my( $table, $sourceid, $destid, %child_tables ) = @_;
609 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
610 ( $table, $primary_key ) = ( $1, $2 );
612 my $dbdef_table = dbdef->table($table);
613 $primary_key = $dbdef_table->primary_key
614 or return "$table has no primary key".
615 " (or do you need to run dbdef-create?)";
618 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
619 join (', ', keys %child_tables). "\n"
622 foreach my $child_table_def ( keys %child_tables ) {
626 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
627 ( $child_table, $child_pkey ) = ( $1, $2 );
629 $child_table = $child_table_def;
631 $child_pkey = dbdef->table($child_table)->primary_key;
632 # or return "$table has no primary key".
633 # " (or do you need to run dbdef-create?)\n";
637 if ( keys %{ $child_tables{$child_table_def} } ) {
639 return "$child_table has no primary key".
640 " (run dbdef-create or try specifying it?)\n"
643 #false laziness w/Record::insert and only works on Pg
644 #refactor the proper last-inserted-id stuff out of Record::insert if this
645 # ever gets use for anything besides a quick kludge for one customer
646 my $default = dbdef->table($child_table)->column($child_pkey)->default;
647 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
648 or return "can't parse $child_table.$child_pkey default value ".
649 " for sequence name: $default";
654 my @sel_columns = grep { $_ ne $primary_key }
655 dbdef->table($child_table)->columns;
656 my $sel_columns = join(', ', @sel_columns );
658 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
659 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
660 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
662 my $sel_st = "SELECT $sel_columns FROM $child_table".
663 " WHERE $primary_key = $sourceid";
666 my $sel_sth = dbh->prepare( $sel_st )
667 or return dbh->errstr;
669 $sel_sth->execute or return $sel_sth->errstr;
671 while ( my $row = $sel_sth->fetchrow_hashref ) {
673 warn " selected row: ".
674 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
678 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
679 my $ins_sth =dbh->prepare($statement)
680 or return dbh->errstr;
681 my @param = ( $destid, map $row->{$_}, @ins_columns );
682 warn " $statement: [ ". join(', ', @param). " ]\n"
684 $ins_sth->execute( @param )
685 or return $ins_sth->errstr;
687 #next unless keys %{ $child_tables{$child_table} };
688 next unless $sequence;
690 #another section of that laziness
691 my $seq_sql = "SELECT currval('$sequence')";
692 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
693 $seq_sth->execute or return $seq_sth->errstr;
694 my $insertid = $seq_sth->fetchrow_arrayref->[0];
696 # don't drink soap! recurse! recurse! okay!
698 _copy_skel( $child_table_def,
699 $row->{$child_pkey}, #sourceid
701 %{ $child_tables{$child_table_def} },
703 return $error if $error;
713 =item order_pkg HASHREF | OPTION => VALUE ...
715 Orders a single package.
717 Options may be passed as a list of key/value pairs or as a hash reference.
728 Optional FS::cust_location object
732 Optional arryaref of FS::svc_* service objects.
736 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
737 jobs will have a dependancy on the supplied job (they will not run until the
738 specific job completes). This can be used to defer provisioning until some
739 action completes (such as running the customer's credit card successfully).
743 Optional subject for a ticket created and attached to this customer
747 Optional queue name for ticket additions
755 my $opt = ref($_[0]) ? shift : { @_ };
757 warn "$me order_pkg called with options ".
758 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
761 my $cust_pkg = $opt->{'cust_pkg'};
762 my $svcs = $opt->{'svcs'} || [];
764 my %svc_options = ();
765 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
766 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
768 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
769 qw( ticket_subject ticket_queue );
771 local $SIG{HUP} = 'IGNORE';
772 local $SIG{INT} = 'IGNORE';
773 local $SIG{QUIT} = 'IGNORE';
774 local $SIG{TERM} = 'IGNORE';
775 local $SIG{TSTP} = 'IGNORE';
776 local $SIG{PIPE} = 'IGNORE';
778 my $oldAutoCommit = $FS::UID::AutoCommit;
779 local $FS::UID::AutoCommit = 0;
782 if ( $opt->{'cust_location'} &&
783 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
784 my $error = $opt->{'cust_location'}->insert;
786 $dbh->rollback if $oldAutoCommit;
787 return "inserting cust_location (transaction rolled back): $error";
789 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
792 $cust_pkg->custnum( $self->custnum );
794 my $error = $cust_pkg->insert( %insert_params );
796 $dbh->rollback if $oldAutoCommit;
797 return "inserting cust_pkg (transaction rolled back): $error";
800 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
801 if ( $svc_something->svcnum ) {
802 my $old_cust_svc = $svc_something->cust_svc;
803 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
804 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
805 $error = $new_cust_svc->replace($old_cust_svc);
807 $svc_something->pkgnum( $cust_pkg->pkgnum );
808 if ( $svc_something->isa('FS::svc_acct') ) {
809 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
810 qw( seconds upbytes downbytes totalbytes ) ) {
811 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
812 ${ $opt->{$_.'_ref'} } = 0;
815 $error = $svc_something->insert(%svc_options);
818 $dbh->rollback if $oldAutoCommit;
819 return "inserting svc_ (transaction rolled back): $error";
823 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
828 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
829 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
831 Like the insert method on an existing record, this method orders multiple
832 packages and included services atomicaly. Pass a Tie::RefHash data structure
833 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
834 There should be a better explanation of this, but until then, here's an
838 tie %hash, 'Tie::RefHash'; #this part is important
840 $cust_pkg => [ $svc_acct ],
843 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
845 Services can be new, in which case they are inserted, or existing unaudited
846 services, in which case they are linked to the newly-created package.
848 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
849 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
851 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
852 on the supplied jobnum (they will not run until the specific job completes).
853 This can be used to defer provisioning until some action completes (such
854 as running the customer's credit card successfully).
856 The I<noexport> option is deprecated. If I<noexport> is set true, no
857 provisioning jobs (exports) are scheduled. (You can schedule them later with
858 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
859 on the cust_main object is not recommended, as existing services will also be
862 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
863 provided, the scalars (provided by references) will be incremented by the
864 values of the prepaid card.`
870 my $cust_pkgs = shift;
871 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
873 $seconds_ref ||= $options{'seconds_ref'};
875 warn "$me order_pkgs called with options ".
876 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
879 local $SIG{HUP} = 'IGNORE';
880 local $SIG{INT} = 'IGNORE';
881 local $SIG{QUIT} = 'IGNORE';
882 local $SIG{TERM} = 'IGNORE';
883 local $SIG{TSTP} = 'IGNORE';
884 local $SIG{PIPE} = 'IGNORE';
886 my $oldAutoCommit = $FS::UID::AutoCommit;
887 local $FS::UID::AutoCommit = 0;
890 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
892 foreach my $cust_pkg ( keys %$cust_pkgs ) {
894 my $error = $self->order_pkg(
895 'cust_pkg' => $cust_pkg,
896 'svcs' => $cust_pkgs->{$cust_pkg},
897 'seconds_ref' => $seconds_ref,
898 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
903 $dbh->rollback if $oldAutoCommit;
909 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
913 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
915 Recharges this (existing) customer with the specified prepaid card (see
916 L<FS::prepay_credit>), specified either by I<identifier> or as an
917 FS::prepay_credit object. If there is an error, returns the error, otherwise
920 Optionally, five scalar references can be passed as well. They will have their
921 values filled in with the amount, number of seconds, and number of upload,
922 download, and total bytes applied by this prepaid card.
926 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
927 #the only place that uses these args
928 sub recharge_prepay {
929 my( $self, $prepay_credit, $amountref, $secondsref,
930 $upbytesref, $downbytesref, $totalbytesref ) = @_;
932 local $SIG{HUP} = 'IGNORE';
933 local $SIG{INT} = 'IGNORE';
934 local $SIG{QUIT} = 'IGNORE';
935 local $SIG{TERM} = 'IGNORE';
936 local $SIG{TSTP} = 'IGNORE';
937 local $SIG{PIPE} = 'IGNORE';
939 my $oldAutoCommit = $FS::UID::AutoCommit;
940 local $FS::UID::AutoCommit = 0;
943 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
945 my $error = $self->get_prepay( $prepay_credit,
946 'amount_ref' => \$amount,
947 'seconds_ref' => \$seconds,
948 'upbytes_ref' => \$upbytes,
949 'downbytes_ref' => \$downbytes,
950 'totalbytes_ref' => \$totalbytes,
952 || $self->increment_seconds($seconds)
953 || $self->increment_upbytes($upbytes)
954 || $self->increment_downbytes($downbytes)
955 || $self->increment_totalbytes($totalbytes)
956 || $self->insert_cust_pay_prepay( $amount,
958 ? $prepay_credit->identifier
963 $dbh->rollback if $oldAutoCommit;
967 if ( defined($amountref) ) { $$amountref = $amount; }
968 if ( defined($secondsref) ) { $$secondsref = $seconds; }
969 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
970 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
971 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
973 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
978 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
980 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
981 specified either by I<identifier> or as an FS::prepay_credit object.
983 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
984 incremented by the values of the prepaid card.
986 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
987 check or set this customer's I<agentnum>.
989 If there is an error, returns the error, otherwise returns false.
995 my( $self, $prepay_credit, %opt ) = @_;
997 local $SIG{HUP} = 'IGNORE';
998 local $SIG{INT} = 'IGNORE';
999 local $SIG{QUIT} = 'IGNORE';
1000 local $SIG{TERM} = 'IGNORE';
1001 local $SIG{TSTP} = 'IGNORE';
1002 local $SIG{PIPE} = 'IGNORE';
1004 my $oldAutoCommit = $FS::UID::AutoCommit;
1005 local $FS::UID::AutoCommit = 0;
1008 unless ( ref($prepay_credit) ) {
1010 my $identifier = $prepay_credit;
1012 $prepay_credit = qsearchs(
1014 { 'identifier' => $prepay_credit },
1019 unless ( $prepay_credit ) {
1020 $dbh->rollback if $oldAutoCommit;
1021 return "Invalid prepaid card: ". $identifier;
1026 if ( $prepay_credit->agentnum ) {
1027 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1028 $dbh->rollback if $oldAutoCommit;
1029 return "prepaid card not valid for agent ". $self->agentnum;
1031 $self->agentnum($prepay_credit->agentnum);
1034 my $error = $prepay_credit->delete;
1036 $dbh->rollback if $oldAutoCommit;
1037 return "removing prepay_credit (transaction rolled back): $error";
1040 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1041 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1043 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1048 =item increment_upbytes SECONDS
1050 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1051 the specified number of upbytes. If there is an error, returns the error,
1052 otherwise returns false.
1056 sub increment_upbytes {
1057 _increment_column( shift, 'upbytes', @_);
1060 =item increment_downbytes SECONDS
1062 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1063 the specified number of downbytes. If there is an error, returns the error,
1064 otherwise returns false.
1068 sub increment_downbytes {
1069 _increment_column( shift, 'downbytes', @_);
1072 =item increment_totalbytes SECONDS
1074 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1075 the specified number of totalbytes. If there is an error, returns the error,
1076 otherwise returns false.
1080 sub increment_totalbytes {
1081 _increment_column( shift, 'totalbytes', @_);
1084 =item increment_seconds SECONDS
1086 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1087 the specified number of seconds. If there is an error, returns the error,
1088 otherwise returns false.
1092 sub increment_seconds {
1093 _increment_column( shift, 'seconds', @_);
1096 =item _increment_column AMOUNT
1098 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1099 the specified number of seconds or bytes. If there is an error, returns
1100 the error, otherwise returns false.
1104 sub _increment_column {
1105 my( $self, $column, $amount ) = @_;
1106 warn "$me increment_column called: $column, $amount\n"
1109 return '' unless $amount;
1111 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1112 $self->ncancelled_pkgs;
1114 if ( ! @cust_pkg ) {
1115 return 'No packages with primary or single services found'.
1116 ' to apply pre-paid time';
1117 } elsif ( scalar(@cust_pkg) > 1 ) {
1118 #maybe have a way to specify the package/account?
1119 return 'Multiple packages found to apply pre-paid time';
1122 my $cust_pkg = $cust_pkg[0];
1123 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1127 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1129 if ( ! @cust_svc ) {
1130 return 'No account found to apply pre-paid time';
1131 } elsif ( scalar(@cust_svc) > 1 ) {
1132 return 'Multiple accounts found to apply pre-paid time';
1135 my $svc_acct = $cust_svc[0]->svc_x;
1136 warn " found service svcnum ". $svc_acct->pkgnum.
1137 ' ('. $svc_acct->email. ")\n"
1140 $column = "increment_$column";
1141 $svc_acct->$column($amount);
1145 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1147 Inserts a prepayment in the specified amount for this customer. An optional
1148 second argument can specify the prepayment identifier for tracking purposes.
1149 If there is an error, returns the error, otherwise returns false.
1153 sub insert_cust_pay_prepay {
1154 shift->insert_cust_pay('PREP', @_);
1157 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1159 Inserts a cash payment in the specified amount for this customer. An optional
1160 second argument can specify the payment identifier for tracking purposes.
1161 If there is an error, returns the error, otherwise returns false.
1165 sub insert_cust_pay_cash {
1166 shift->insert_cust_pay('CASH', @_);
1169 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1171 Inserts a Western Union payment in the specified amount for this customer. An
1172 optional second argument can specify the prepayment identifier for tracking
1173 purposes. If there is an error, returns the error, otherwise returns false.
1177 sub insert_cust_pay_west {
1178 shift->insert_cust_pay('WEST', @_);
1181 sub insert_cust_pay {
1182 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1183 my $payinfo = scalar(@_) ? shift : '';
1185 my $cust_pay = new FS::cust_pay {
1186 'custnum' => $self->custnum,
1187 'paid' => sprintf('%.2f', $amount),
1188 #'_date' => #date the prepaid card was purchased???
1190 'payinfo' => $payinfo,
1198 This method is deprecated. See the I<depend_jobnum> option to the insert and
1199 order_pkgs methods for a better way to defer provisioning.
1201 Re-schedules all exports by calling the B<reexport> method of all associated
1202 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1203 otherwise returns false.
1210 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1211 "use the depend_jobnum option to insert or order_pkgs to delay export";
1213 local $SIG{HUP} = 'IGNORE';
1214 local $SIG{INT} = 'IGNORE';
1215 local $SIG{QUIT} = 'IGNORE';
1216 local $SIG{TERM} = 'IGNORE';
1217 local $SIG{TSTP} = 'IGNORE';
1218 local $SIG{PIPE} = 'IGNORE';
1220 my $oldAutoCommit = $FS::UID::AutoCommit;
1221 local $FS::UID::AutoCommit = 0;
1224 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1225 my $error = $cust_pkg->reexport;
1227 $dbh->rollback if $oldAutoCommit;
1232 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1237 =item delete NEW_CUSTNUM
1239 This deletes the customer. If there is an error, returns the error, otherwise
1242 This will completely remove all traces of the customer record. This is not
1243 what you want when a customer cancels service; for that, cancel all of the
1244 customer's packages (see L</cancel>).
1246 If the customer has any uncancelled packages, you need to pass a new (valid)
1247 customer number for those packages to be transferred to. Cancelled packages
1248 will be deleted. Did I mention that this is NOT what you want when a customer
1249 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1251 You can't delete a customer with invoices (see L<FS::cust_bill>),
1252 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1253 refunds (see L<FS::cust_refund>).
1260 local $SIG{HUP} = 'IGNORE';
1261 local $SIG{INT} = 'IGNORE';
1262 local $SIG{QUIT} = 'IGNORE';
1263 local $SIG{TERM} = 'IGNORE';
1264 local $SIG{TSTP} = 'IGNORE';
1265 local $SIG{PIPE} = 'IGNORE';
1267 my $oldAutoCommit = $FS::UID::AutoCommit;
1268 local $FS::UID::AutoCommit = 0;
1271 if ( $self->cust_bill ) {
1272 $dbh->rollback if $oldAutoCommit;
1273 return "Can't delete a customer with invoices";
1275 if ( $self->cust_credit ) {
1276 $dbh->rollback if $oldAutoCommit;
1277 return "Can't delete a customer with credits";
1279 if ( $self->cust_pay ) {
1280 $dbh->rollback if $oldAutoCommit;
1281 return "Can't delete a customer with payments";
1283 if ( $self->cust_refund ) {
1284 $dbh->rollback if $oldAutoCommit;
1285 return "Can't delete a customer with refunds";
1288 my @cust_pkg = $self->ncancelled_pkgs;
1290 my $new_custnum = shift;
1291 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1292 $dbh->rollback if $oldAutoCommit;
1293 return "Invalid new customer number: $new_custnum";
1295 foreach my $cust_pkg ( @cust_pkg ) {
1296 my %hash = $cust_pkg->hash;
1297 $hash{'custnum'} = $new_custnum;
1298 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1299 my $error = $new_cust_pkg->replace($cust_pkg,
1300 options => { $cust_pkg->options },
1303 $dbh->rollback if $oldAutoCommit;
1308 my @cancelled_cust_pkg = $self->all_pkgs;
1309 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1310 my $error = $cust_pkg->delete;
1312 $dbh->rollback if $oldAutoCommit;
1317 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1318 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1320 my $error = $cust_main_invoice->delete;
1322 $dbh->rollback if $oldAutoCommit;
1327 foreach my $cust_main_exemption (
1328 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } )
1330 my $error = $cust_main_exemption->delete;
1332 $dbh->rollback if $oldAutoCommit;
1337 my $error = $self->SUPER::delete;
1339 $dbh->rollback if $oldAutoCommit;
1343 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1348 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1351 Replaces the OLD_RECORD with this one in the database. If there is an error,
1352 returns the error, otherwise returns false.
1354 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1355 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1356 expected and rollback the entire transaction; it is not necessary to call
1357 check_invoicing_list first. Here's an example:
1359 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1361 Currently available options are: I<tax_exemption>.
1363 The I<tax_exemption> option can be set to an arrayref of tax names.
1364 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1371 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1373 : $self->replace_old;
1377 warn "$me replace called\n"
1380 my $curuser = $FS::CurrentUser::CurrentUser;
1381 if ( $self->payby eq 'COMP'
1382 && $self->payby ne $old->payby
1383 && ! $curuser->access_right('Complimentary customer')
1386 return "You are not permitted to create complimentary accounts.";
1389 local($ignore_expired_card) = 1
1390 if $old->payby =~ /^(CARD|DCRD)$/
1391 && $self->payby =~ /^(CARD|DCRD)$/
1392 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1394 local $SIG{HUP} = 'IGNORE';
1395 local $SIG{INT} = 'IGNORE';
1396 local $SIG{QUIT} = 'IGNORE';
1397 local $SIG{TERM} = 'IGNORE';
1398 local $SIG{TSTP} = 'IGNORE';
1399 local $SIG{PIPE} = 'IGNORE';
1401 my $oldAutoCommit = $FS::UID::AutoCommit;
1402 local $FS::UID::AutoCommit = 0;
1405 my $error = $self->SUPER::replace($old);
1408 $dbh->rollback if $oldAutoCommit;
1412 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1413 my $invoicing_list = shift @param;
1414 $error = $self->check_invoicing_list( $invoicing_list );
1416 $dbh->rollback if $oldAutoCommit;
1419 $self->invoicing_list( $invoicing_list );
1422 my %options = @param;
1424 my $tax_exemption = delete $options{'tax_exemption'};
1425 if ( $tax_exemption ) {
1427 my %cust_main_exemption =
1428 map { $_->taxname => $_ }
1429 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1431 foreach my $taxname ( @$tax_exemption ) {
1433 next if delete $cust_main_exemption{$taxname};
1435 my $cust_main_exemption = new FS::cust_main_exemption {
1436 'custnum' => $self->custnum,
1437 'taxname' => $taxname,
1439 my $error = $cust_main_exemption->insert;
1441 $dbh->rollback if $oldAutoCommit;
1442 return "inserting cust_main_exemption (transaction rolled back): $error";
1446 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1447 my $error = $cust_main_exemption->delete;
1449 $dbh->rollback if $oldAutoCommit;
1450 return "deleting cust_main_exemption (transaction rolled back): $error";
1456 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1457 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1458 # card/check/lec info has changed, want to retry realtime_ invoice events
1459 my $error = $self->retry_realtime;
1461 $dbh->rollback if $oldAutoCommit;
1466 unless ( $import || $skip_fuzzyfiles ) {
1467 $error = $self->queue_fuzzyfiles_update;
1469 $dbh->rollback if $oldAutoCommit;
1470 return "updating fuzzy search cache: $error";
1474 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1479 =item queue_fuzzyfiles_update
1481 Used by insert & replace to update the fuzzy search cache
1485 sub queue_fuzzyfiles_update {
1488 local $SIG{HUP} = 'IGNORE';
1489 local $SIG{INT} = 'IGNORE';
1490 local $SIG{QUIT} = 'IGNORE';
1491 local $SIG{TERM} = 'IGNORE';
1492 local $SIG{TSTP} = 'IGNORE';
1493 local $SIG{PIPE} = 'IGNORE';
1495 my $oldAutoCommit = $FS::UID::AutoCommit;
1496 local $FS::UID::AutoCommit = 0;
1499 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1500 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1502 $dbh->rollback if $oldAutoCommit;
1503 return "queueing job (transaction rolled back): $error";
1506 if ( $self->ship_last ) {
1507 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1508 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1510 $dbh->rollback if $oldAutoCommit;
1511 return "queueing job (transaction rolled back): $error";
1515 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1522 Checks all fields to make sure this is a valid customer record. If there is
1523 an error, returns the error, otherwise returns false. Called by the insert
1524 and replace methods.
1531 warn "$me check BEFORE: \n". $self->_dump
1535 $self->ut_numbern('custnum')
1536 || $self->ut_number('agentnum')
1537 || $self->ut_textn('agent_custid')
1538 || $self->ut_number('refnum')
1539 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1540 || $self->ut_textn('custbatch')
1541 || $self->ut_name('last')
1542 || $self->ut_name('first')
1543 || $self->ut_snumbern('birthdate')
1544 || $self->ut_snumbern('signupdate')
1545 || $self->ut_textn('company')
1546 || $self->ut_text('address1')
1547 || $self->ut_textn('address2')
1548 || $self->ut_text('city')
1549 || $self->ut_textn('county')
1550 || $self->ut_textn('state')
1551 || $self->ut_country('country')
1552 || $self->ut_anything('comments')
1553 || $self->ut_numbern('referral_custnum')
1554 || $self->ut_textn('stateid')
1555 || $self->ut_textn('stateid_state')
1556 || $self->ut_textn('invoice_terms')
1557 || $self->ut_alphan('geocode')
1558 || $self->ut_floatn('cdr_termination_percentage')
1561 #barf. need message catalogs. i18n. etc.
1562 $error .= "Please select an advertising source."
1563 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1564 return $error if $error;
1566 return "Unknown agent"
1567 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1569 return "Unknown refnum"
1570 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1572 return "Unknown referring custnum: ". $self->referral_custnum
1573 unless ! $self->referral_custnum
1574 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1576 if ( $self->censustract ne '' ) {
1577 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1578 or return "Illegal census tract: ". $self->censustract;
1580 $self->censustract("$1.$2");
1583 if ( $self->ss eq '' ) {
1588 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1589 or return "Illegal social security number: ". $self->ss;
1590 $self->ss("$1-$2-$3");
1594 # bad idea to disable, causes billing to fail because of no tax rates later
1595 # unless ( $import ) {
1596 unless ( qsearch('cust_main_county', {
1597 'country' => $self->country,
1600 return "Unknown state/county/country: ".
1601 $self->state. "/". $self->county. "/". $self->country
1602 unless qsearch('cust_main_county',{
1603 'state' => $self->state,
1604 'county' => $self->county,
1605 'country' => $self->country,
1611 $self->ut_phonen('daytime', $self->country)
1612 || $self->ut_phonen('night', $self->country)
1613 || $self->ut_phonen('fax', $self->country)
1614 || $self->ut_zip('zip', $self->country)
1616 return $error if $error;
1618 if ( $conf->exists('cust_main-require_phone')
1619 && ! length($self->daytime) && ! length($self->night)
1622 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1624 : FS::Msgcat::_gettext('daytime');
1625 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1627 : FS::Msgcat::_gettext('night');
1629 return "$daytime_label or $night_label is required"
1633 if ( $self->has_ship_address
1634 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1635 $self->addr_fields )
1639 $self->ut_name('ship_last')
1640 || $self->ut_name('ship_first')
1641 || $self->ut_textn('ship_company')
1642 || $self->ut_text('ship_address1')
1643 || $self->ut_textn('ship_address2')
1644 || $self->ut_text('ship_city')
1645 || $self->ut_textn('ship_county')
1646 || $self->ut_textn('ship_state')
1647 || $self->ut_country('ship_country')
1649 return $error if $error;
1651 #false laziness with above
1652 unless ( qsearchs('cust_main_county', {
1653 'country' => $self->ship_country,
1656 return "Unknown ship_state/ship_county/ship_country: ".
1657 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1658 unless qsearch('cust_main_county',{
1659 'state' => $self->ship_state,
1660 'county' => $self->ship_county,
1661 'country' => $self->ship_country,
1667 $self->ut_phonen('ship_daytime', $self->ship_country)
1668 || $self->ut_phonen('ship_night', $self->ship_country)
1669 || $self->ut_phonen('ship_fax', $self->ship_country)
1670 || $self->ut_zip('ship_zip', $self->ship_country)
1672 return $error if $error;
1674 return "Unit # is required."
1675 if $self->ship_address2 =~ /^\s*$/
1676 && $conf->exists('cust_main-require_address2');
1678 } else { # ship_ info eq billing info, so don't store dup info in database
1680 $self->setfield("ship_$_", '')
1681 foreach $self->addr_fields;
1683 return "Unit # is required."
1684 if $self->address2 =~ /^\s*$/
1685 && $conf->exists('cust_main-require_address2');
1689 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1690 # or return "Illegal payby: ". $self->payby;
1692 FS::payby->can_payby($self->table, $self->payby)
1693 or return "Illegal payby: ". $self->payby;
1695 $error = $self->ut_numbern('paystart_month')
1696 || $self->ut_numbern('paystart_year')
1697 || $self->ut_numbern('payissue')
1698 || $self->ut_textn('paytype')
1700 return $error if $error;
1702 if ( $self->payip eq '' ) {
1705 $error = $self->ut_ip('payip');
1706 return $error if $error;
1709 # If it is encrypted and the private key is not availaible then we can't
1710 # check the credit card.
1712 my $check_payinfo = 1;
1714 if ($self->is_encrypted($self->payinfo)) {
1718 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1720 my $payinfo = $self->payinfo;
1721 $payinfo =~ s/\D//g;
1722 $payinfo =~ /^(\d{13,16})$/
1723 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1725 $self->payinfo($payinfo);
1727 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1729 return gettext('unknown_card_type')
1730 if cardtype($self->payinfo) eq "Unknown";
1732 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1734 return 'Banned credit card: banned on '.
1735 time2str('%a %h %o at %r', $ban->_date).
1736 ' by '. $ban->otaker.
1737 ' (ban# '. $ban->bannum. ')';
1740 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1741 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1742 $self->paycvv =~ /^(\d{4})$/
1743 or return "CVV2 (CID) for American Express cards is four digits.";
1746 $self->paycvv =~ /^(\d{3})$/
1747 or return "CVV2 (CVC2/CID) is three digits.";
1754 my $cardtype = cardtype($payinfo);
1755 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1757 return "Start date or issue number is required for $cardtype cards"
1758 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1760 return "Start month must be between 1 and 12"
1761 if $self->paystart_month
1762 and $self->paystart_month < 1 || $self->paystart_month > 12;
1764 return "Start year must be 1990 or later"
1765 if $self->paystart_year
1766 and $self->paystart_year < 1990;
1768 return "Issue number must be beween 1 and 99"
1770 and $self->payissue < 1 || $self->payissue > 99;
1773 $self->paystart_month('');
1774 $self->paystart_year('');
1775 $self->payissue('');
1778 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1780 my $payinfo = $self->payinfo;
1781 $payinfo =~ s/[^\d\@]//g;
1782 if ( $conf->exists('echeck-nonus') ) {
1783 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1784 $payinfo = "$1\@$2";
1786 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1787 $payinfo = "$1\@$2";
1789 $self->payinfo($payinfo);
1792 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1794 return 'Banned ACH account: banned on '.
1795 time2str('%a %h %o at %r', $ban->_date).
1796 ' by '. $ban->otaker.
1797 ' (ban# '. $ban->bannum. ')';
1800 } elsif ( $self->payby eq 'LECB' ) {
1802 my $payinfo = $self->payinfo;
1803 $payinfo =~ s/\D//g;
1804 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1806 $self->payinfo($payinfo);
1809 } elsif ( $self->payby eq 'BILL' ) {
1811 $error = $self->ut_textn('payinfo');
1812 return "Illegal P.O. number: ". $self->payinfo if $error;
1815 } elsif ( $self->payby eq 'COMP' ) {
1817 my $curuser = $FS::CurrentUser::CurrentUser;
1818 if ( ! $self->custnum
1819 && ! $curuser->access_right('Complimentary customer')
1822 return "You are not permitted to create complimentary accounts."
1825 $error = $self->ut_textn('payinfo');
1826 return "Illegal comp account issuer: ". $self->payinfo if $error;
1829 } elsif ( $self->payby eq 'PREPAY' ) {
1831 my $payinfo = $self->payinfo;
1832 $payinfo =~ s/\W//g; #anything else would just confuse things
1833 $self->payinfo($payinfo);
1834 $error = $self->ut_alpha('payinfo');
1835 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1836 return "Unknown prepayment identifier"
1837 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1842 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1843 return "Expiration date required"
1844 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1848 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1849 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1850 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1851 ( $m, $y ) = ( $2, "19$1" );
1852 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1853 ( $m, $y ) = ( $3, "20$2" );
1855 return "Illegal expiration date: ". $self->paydate;
1857 $self->paydate("$y-$m-01");
1858 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1859 return gettext('expired_card')
1861 && !$ignore_expired_card
1862 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1865 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1866 ( ! $conf->exists('require_cardname')
1867 || $self->payby !~ /^(CARD|DCRD)$/ )
1869 $self->payname( $self->first. " ". $self->getfield('last') );
1871 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1872 or return gettext('illegal_name'). " payname: ". $self->payname;
1876 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1877 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1881 $self->otaker(getotaker) unless $self->otaker;
1883 warn "$me check AFTER: \n". $self->_dump
1886 $self->SUPER::check;
1891 Returns a list of fields which have ship_ duplicates.
1896 qw( last first company
1897 address1 address2 city county state zip country
1902 =item has_ship_address
1904 Returns true if this customer record has a separate shipping address.
1908 sub has_ship_address {
1910 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1915 Returns a list of key/value pairs, with the following keys: address1, adddress2,
1916 city, county, state, zip, country. The shipping address is used if present.
1920 #geocode? dependent on tax-ship_address config, not available in cust_location
1921 #mostly. not yet then.
1925 my $prefix = $self->has_ship_address ? 'ship_' : '';
1927 map { $_ => $self->get($prefix.$_) }
1928 qw( address1 address2 city county state zip country geocode );
1929 #fields that cust_location has
1932 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
1934 Returns all packages (see L<FS::cust_pkg>) for this customer.
1940 my $extra_qsearch = ref($_[0]) ? shift : {};
1942 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
1945 if ( $self->{'_pkgnum'} ) {
1946 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1948 @cust_pkg = $self->_cust_pkg($extra_qsearch);
1951 sort sort_packages @cust_pkg;
1956 Synonym for B<all_pkgs>.
1961 shift->all_pkgs(@_);
1966 Returns all locations (see L<FS::cust_location>) for this customer.
1972 qsearch('cust_location', { 'custnum' => $self->custnum } );
1975 =item location_label [ OPTION => VALUE ... ]
1977 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
1985 used to separate the address elements (defaults to ', ')
1987 =item escape_function
1989 a callback used for escaping the text of the address elements
1995 # false laziness with FS::cust_location::line
1997 sub location_label {
2001 my $separator = $opt{join_string} || ', ';
2002 my $escape = $opt{escape_function} || sub{ shift };
2004 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2005 my $prefix = length($self->ship_last) ? 'ship_' : '';
2008 foreach (qw ( address1 address2 ) ) {
2009 my $method = "$prefix$_";
2010 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2015 foreach (qw ( city county state zip ) ) {
2016 my $method = "$prefix$_";
2017 if ( $self->$method ) {
2018 $line .= ' (' if $method eq 'county';
2019 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2020 $line .= ' )' if $method eq 'county';
2024 $line .= $separator. &$escape(code2country($self->country))
2025 if $self->country ne $cydefault;
2030 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2032 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2036 sub ncancelled_pkgs {
2038 my $extra_qsearch = ref($_[0]) ? shift : {};
2040 return $self->num_ncancelled_pkgs unless wantarray;
2043 if ( $self->{'_pkgnum'} ) {
2045 warn "$me ncancelled_pkgs: returning cached objects"
2048 @cust_pkg = grep { ! $_->getfield('cancel') }
2049 values %{ $self->{'_pkgnum'}->cache };
2053 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2054 $self->custnum. "\n"
2057 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2059 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2063 sort sort_packages @cust_pkg;
2069 my $extra_qsearch = ref($_[0]) ? shift : {};
2071 $extra_qsearch->{'select'} ||= '*';
2072 $extra_qsearch->{'select'} .=
2073 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2077 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2082 'table' => 'cust_pkg',
2083 'hashref' => { 'custnum' => $self->custnum },
2088 # This should be generalized to use config options to determine order.
2091 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2092 return $locationsort if $locationsort;
2094 if ( $a->get('cancel') xor $b->get('cancel') ) {
2095 return -1 if $b->get('cancel');
2096 return 1 if $a->get('cancel');
2097 #shouldn't get here...
2100 my $a_num_cust_svc = $a->num_cust_svc;
2101 my $b_num_cust_svc = $b->num_cust_svc;
2102 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2103 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2104 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2105 my @a_cust_svc = $a->cust_svc;
2106 my @b_cust_svc = $b->cust_svc;
2107 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2112 =item suspended_pkgs
2114 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2118 sub suspended_pkgs {
2120 grep { $_->susp } $self->ncancelled_pkgs;
2123 =item unflagged_suspended_pkgs
2125 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2126 customer (thouse packages without the `manual_flag' set).
2130 sub unflagged_suspended_pkgs {
2132 return $self->suspended_pkgs
2133 unless dbdef->table('cust_pkg')->column('manual_flag');
2134 grep { ! $_->manual_flag } $self->suspended_pkgs;
2137 =item unsuspended_pkgs
2139 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2144 sub unsuspended_pkgs {
2146 grep { ! $_->susp } $self->ncancelled_pkgs;
2149 =item next_bill_date
2151 Returns the next date this customer will be billed, as a UNIX timestamp, or
2152 undef if no active package has a next bill date.
2156 sub next_bill_date {
2158 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2161 =item num_cancelled_pkgs
2163 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2168 sub num_cancelled_pkgs {
2169 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2172 sub num_ncancelled_pkgs {
2173 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2177 my( $self ) = shift;
2178 my $sql = scalar(@_) ? shift : '';
2179 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2180 my $sth = dbh->prepare(
2181 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2182 ) or die dbh->errstr;
2183 $sth->execute($self->custnum) or die $sth->errstr;
2184 $sth->fetchrow_arrayref->[0];
2189 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2190 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2191 on success or a list of errors.
2197 grep { $_->unsuspend } $self->suspended_pkgs;
2202 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2204 Returns a list: an empty list on success or a list of errors.
2210 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2213 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2215 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2216 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2217 of a list of pkgparts; the hashref has the following keys:
2221 =item pkgparts - listref of pkgparts
2223 =item (other options are passed to the suspend method)
2228 Returns a list: an empty list on success or a list of errors.
2232 sub suspend_if_pkgpart {
2234 my (@pkgparts, %opt);
2235 if (ref($_[0]) eq 'HASH'){
2236 @pkgparts = @{$_[0]{pkgparts}};
2241 grep { $_->suspend(%opt) }
2242 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2243 $self->unsuspended_pkgs;
2246 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2248 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2249 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2250 instead of a list of pkgparts; the hashref has the following keys:
2254 =item pkgparts - listref of pkgparts
2256 =item (other options are passed to the suspend method)
2260 Returns a list: an empty list on success or a list of errors.
2264 sub suspend_unless_pkgpart {
2266 my (@pkgparts, %opt);
2267 if (ref($_[0]) eq 'HASH'){
2268 @pkgparts = @{$_[0]{pkgparts}};
2273 grep { $_->suspend(%opt) }
2274 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2275 $self->unsuspended_pkgs;
2278 =item cancel [ OPTION => VALUE ... ]
2280 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2282 Available options are:
2286 =item quiet - can be set true to supress email cancellation notices.
2288 =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.
2290 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2292 =item nobill - can be set true to skip billing if it might otherwise be done.
2296 Always returns a list: an empty list on success or a list of errors.
2300 # nb that dates are not specified as valid options to this method
2303 my( $self, %opt ) = @_;
2305 warn "$me cancel called on customer ". $self->custnum. " with options ".
2306 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2309 return ( 'access denied' )
2310 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2312 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2314 #should try decryption (we might have the private key)
2315 # and if not maybe queue a job for the server that does?
2316 return ( "Can't (yet) ban encrypted credit cards" )
2317 if $self->is_encrypted($self->payinfo);
2319 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2320 my $error = $ban->insert;
2321 return ( $error ) if $error;
2325 my @pkgs = $self->ncancelled_pkgs;
2327 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2329 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2330 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2334 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2335 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2338 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2341 sub _banned_pay_hashref {
2352 'payby' => $payby2ban{$self->payby},
2353 'payinfo' => md5_base64($self->payinfo),
2354 #don't ever *search* on reason! #'reason' =>
2360 Returns all notes (see L<FS::cust_main_note>) for this customer.
2367 qsearch( 'cust_main_note',
2368 { 'custnum' => $self->custnum },
2370 'ORDER BY _DATE DESC'
2376 Returns the agent (see L<FS::agent>) for this customer.
2382 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2387 Returns the customer class, as an FS::cust_class object, or the empty string
2388 if there is no customer class.
2394 if ( $self->classnum ) {
2395 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2403 Returns the customer category name, or the empty string if there is no customer
2410 my $cust_class = $self->cust_class;
2412 ? $cust_class->categoryname
2418 Returns the customer class name, or the empty string if there is no customer
2425 my $cust_class = $self->cust_class;
2427 ? $cust_class->classname
2432 =item bill_and_collect
2434 Cancels and suspends any packages due, generates bills, applies payments and
2435 credits, and applies collection events to run cards, send bills and notices,
2438 By default, warns on errors and continues with the next operation (but see the
2439 "fatal" flag below).
2441 Options are passed as name-value pairs. Currently available options are:
2447 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:
2451 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2455 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.
2459 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2463 If set true, re-charges setup fees.
2467 If set any errors prevent subsequent operations from continusing. If set
2468 specifically to "return", returns the error (or false, if there is no error).
2469 Any other true value causes errors to die.
2473 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)
2477 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2478 options of those methods are also available.
2482 sub bill_and_collect {
2483 my( $self, %options ) = @_;
2487 #$options{actual_time} not $options{time} because freeside-daily -d is for
2488 #pre-printing invoices
2490 $options{'actual_time'} ||= time;
2492 $error = $self->cancel_expired_pkgs( $options{actual_time} );
2494 $error = "Error expiring custnum ". $self->custnum. ": $error";
2495 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2496 elsif ( $options{fatal} ) { die $error; }
2497 else { warn $error; }
2500 $error = $self->suspend_adjourned_pkgs( $options{actual_time} );
2502 $error = "Error adjourning custnum ". $self->custnum. ": $error";
2503 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2504 elsif ( $options{fatal} ) { die $error; }
2505 else { warn $error; }
2508 $error = $self->bill( %options );
2510 $error = "Error billing custnum ". $self->custnum. ": $error";
2511 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2512 elsif ( $options{fatal} ) { die $error; }
2513 else { warn $error; }
2516 $error = $self->apply_payments_and_credits;
2518 $error = "Error applying custnum ". $self->custnum. ": $error";
2519 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2520 elsif ( $options{fatal} ) { die $error; }
2521 else { warn $error; }
2524 unless ( $conf->exists('cancelled_cust-noevents')
2525 && ! $self->num_ncancelled_pkgs
2527 $error = $self->collect( %options );
2529 $error = "Error collecting custnum ". $self->custnum. ": $error";
2530 if ($options{fatal} && $options{fatal} eq 'return') { return $error; }
2531 elsif ($options{fatal} ) { die $error; }
2532 else { warn $error; }
2540 sub cancel_expired_pkgs {
2541 my ( $self, $time, %options ) = @_;
2543 my @cancel_pkgs = $self->ncancelled_pkgs( {
2544 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2549 foreach my $cust_pkg ( @cancel_pkgs ) {
2550 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2551 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2552 'reason_otaker' => $cpr->otaker
2556 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2559 scalar(@errors) ? join(' / ', @errors) : '';
2563 sub suspend_adjourned_pkgs {
2564 my ( $self, $time, %options ) = @_;
2566 my @susp_pkgs = $self->ncancelled_pkgs( {
2568 " AND ( susp IS NULL OR susp = 0 )
2569 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
2570 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2575 #only because there's no SQL test for is_prepaid :/
2577 grep { ( $_->part_pkg->is_prepaid
2582 && $_->adjourn <= $time
2590 foreach my $cust_pkg ( @susp_pkgs ) {
2591 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2592 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2593 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2594 'reason_otaker' => $cpr->otaker
2598 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2601 scalar(@errors) ? join(' / ', @errors) : '';
2607 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2608 conjunction with the collect method by calling B<bill_and_collect>.
2610 If there is an error, returns the error, otherwise returns false.
2612 Options are passed as name-value pairs. Currently available options are:
2618 If set true, re-charges setup fees.
2622 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:
2626 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2630 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2632 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2636 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2640 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.
2644 This boolean value informs the us that the package is being cancelled. This
2645 typically might mean not charging the normal recurring fee but only usage
2646 fees since the last billing. Setup charges may be charged. Not all package
2647 plans support this feature (they tend to charge 0).
2651 Optional terms to be printed on this invoice. Otherwise, customer-specific
2652 terms or the default terms are used.
2659 my( $self, %options ) = @_;
2660 return '' if $self->payby eq 'COMP';
2661 warn "$me bill customer ". $self->custnum. "\n"
2664 my $time = $options{'time'} || time;
2665 my $invoice_time = $options{'invoice_time'} || $time;
2667 $options{'not_pkgpart'} ||= {};
2668 $options{'not_pkgpart'} = { map { $_ => 1 }
2669 split(/\s*,\s*/, $options{'not_pkgpart'})
2671 unless ref($options{'not_pkgpart'});
2673 local $SIG{HUP} = 'IGNORE';
2674 local $SIG{INT} = 'IGNORE';
2675 local $SIG{QUIT} = 'IGNORE';
2676 local $SIG{TERM} = 'IGNORE';
2677 local $SIG{TSTP} = 'IGNORE';
2678 local $SIG{PIPE} = 'IGNORE';
2680 my $oldAutoCommit = $FS::UID::AutoCommit;
2681 local $FS::UID::AutoCommit = 0;
2684 $self->select_for_update; #mutex
2686 my $error = $self->do_cust_event(
2687 'debug' => ( $options{'debug'} || 0 ),
2688 'time' => $invoice_time,
2689 'check_freq' => $options{'check_freq'},
2690 'stage' => 'pre-bill',
2693 $dbh->rollback if $oldAutoCommit;
2697 #keep auto-charge and non-auto-charge line items separate
2698 my @passes = ( '', 'no_auto' );
2700 my %cust_bill_pkg = map { $_ => [] } @passes;
2703 # find the packages which are due for billing, find out how much they are
2704 # & generate invoice database.
2707 my %total_setup = map { my $z = 0; $_ => \$z; } @passes;
2708 my %total_recur = map { my $z = 0; $_ => \$z; } @passes;
2710 my %taxlisthash = map { $_ => {} } @passes;
2712 my @precommit_hooks = ();
2714 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
2715 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2717 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2719 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2721 #? to avoid use of uninitialized value errors... ?
2722 $cust_pkg->setfield('bill', '')
2723 unless defined($cust_pkg->bill);
2725 #my $part_pkg = $cust_pkg->part_pkg;
2727 my $real_pkgpart = $cust_pkg->pkgpart;
2728 my %hash = $cust_pkg->hash;
2730 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2732 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2734 my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
2737 $self->_make_lines( 'part_pkg' => $part_pkg,
2738 'cust_pkg' => $cust_pkg,
2739 'precommit_hooks' => \@precommit_hooks,
2740 'line_items' => $cust_bill_pkg{$pass},
2741 'setup' => $total_setup{$pass},
2742 'recur' => $total_recur{$pass},
2743 'tax_matrix' => $taxlisthash{$pass},
2745 'real_pkgpart' => $real_pkgpart,
2746 'options' => \%options,
2749 $dbh->rollback if $oldAutoCommit;
2753 } #foreach my $part_pkg
2755 } #foreach my $cust_pkg
2757 #if the customer isn't on an automatic payby, everything can go on a single
2759 #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
2760 #merge everything into one list
2763 foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
2765 my @cust_bill_pkg = @{ $cust_bill_pkg{$pass} };
2767 next unless @cust_bill_pkg; #don't create an invoice w/o line items
2769 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2770 !$conf->exists('postal_invoice-recurring_only')
2774 my $postal_pkg = $self->charge_postal_fee();
2775 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2777 $dbh->rollback if $oldAutoCommit;
2778 return "can't charge postal invoice fee for customer ".
2779 $self->custnum. ": $postal_pkg";
2781 } elsif ( $postal_pkg ) {
2783 my $real_pkgpart = $postal_pkg->pkgpart;
2784 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2785 my %postal_options = %options;
2786 delete $postal_options{cancel};
2788 $self->_make_lines( 'part_pkg' => $part_pkg,
2789 'cust_pkg' => $postal_pkg,
2790 'precommit_hooks' => \@precommit_hooks,
2791 'line_items' => \@cust_bill_pkg,
2792 'setup' => $total_setup{$pass},
2793 'recur' => $total_recur{$pass},
2794 'tax_matrix' => $taxlisthash{$pass},
2796 'real_pkgpart' => $real_pkgpart,
2797 'options' => \%postal_options,
2800 $dbh->rollback if $oldAutoCommit;
2809 my $listref_or_error =
2810 $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
2812 unless ( ref( $listref_or_error ) ) {
2813 $dbh->rollback if $oldAutoCommit;
2814 return $listref_or_error;
2817 foreach my $taxline ( @$listref_or_error ) {
2818 ${ $total_setup{$pass} } =
2819 sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
2820 push @cust_bill_pkg, $taxline;
2823 #add tax adjustments
2824 warn "adding tax adjustments...\n" if $DEBUG > 2;
2825 foreach my $cust_tax_adjustment (
2826 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
2832 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
2834 my $itemdesc = $cust_tax_adjustment->taxname;
2835 $itemdesc = '' if $itemdesc eq 'Tax';
2837 push @cust_bill_pkg, new FS::cust_bill_pkg {
2843 'itemdesc' => $itemdesc,
2844 'itemcomment' => $cust_tax_adjustment->comment,
2845 'cust_tax_adjustment' => $cust_tax_adjustment,
2846 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
2851 my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
2853 my @cust_bill = $self->cust_bill;
2854 my $balance = $self->balance;
2855 my $previous_balance = scalar(@cust_bill)
2856 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
2859 $previous_balance += $cust_bill[$#cust_bill]->charged
2860 if scalar(@cust_bill);
2861 #my $balance_adjustments =
2862 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
2864 #create the new invoice
2865 my $cust_bill = new FS::cust_bill ( {
2866 'custnum' => $self->custnum,
2867 '_date' => ( $invoice_time ),
2868 'charged' => $charged,
2869 'billing_balance' => $balance,
2870 'previous_balance' => $previous_balance,
2871 'invoice_terms' => $options{'invoice_terms'},
2873 $error = $cust_bill->insert;
2875 $dbh->rollback if $oldAutoCommit;
2876 return "can't create invoice for customer #". $self->custnum. ": $error";
2879 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2880 $cust_bill_pkg->invnum($cust_bill->invnum);
2881 my $error = $cust_bill_pkg->insert;
2883 $dbh->rollback if $oldAutoCommit;
2884 return "can't create invoice line item: $error";
2888 } #foreach my $pass ( keys %cust_bill_pkg )
2890 foreach my $hook ( @precommit_hooks ) {
2892 &{$hook}; #($self) ?
2895 $dbh->rollback if $oldAutoCommit;
2896 return "$@ running precommit hook $hook\n";
2900 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2904 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
2906 This is a weird one. Perhaps it should not even be exposed.
2908 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
2909 Usually used internally by bill method B<bill>.
2911 If there is an error, returns the error, otherwise returns reference to a
2912 list of line items suitable for insertion.
2918 An array ref of the line items being billed.
2922 A strange beast. The keys to this hash are internal identifiers consisting
2923 of the name of the tax object type, a space, and its unique identifier ( e.g.
2924 'cust_main_county 23' ). The values of the hash are listrefs. The first
2925 item in the list is the tax object. The remaining items are either line
2926 items or floating point values (currency amounts).
2928 The taxes are calculated on this entity. Calculated exemption records are
2929 transferred to the LINEITEMREF items on the assumption that they are related.
2935 This specifies the date appearing on the associated invoice. Some
2936 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
2941 sub calculate_taxes {
2942 my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
2944 my @tax_line_items = ();
2946 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2948 # keys are tax names (as printed on invoices / itemdesc )
2949 # values are listrefs of taxlisthash keys (internal identifiers)
2952 # keys are taxlisthash keys (internal identifiers)
2953 # values are (cumulative) amounts
2956 # keys are taxlisthash keys (internal identifiers)
2957 # values are listrefs of cust_bill_pkg_tax_location hashrefs
2958 my %tax_location = ();
2960 # keys are taxlisthash keys (internal identifiers)
2961 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
2962 my %tax_rate_location = ();
2964 foreach my $tax ( keys %$taxlisthash ) {
2965 my $tax_object = shift @{ $taxlisthash->{$tax} };
2966 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2967 warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
2968 my $hashref_or_error =
2969 $tax_object->taxline( $taxlisthash->{$tax},
2970 'custnum' => $self->custnum,
2971 'invoice_time' => $invoice_time
2973 return $hashref_or_error unless ref($hashref_or_error);
2975 unshift @{ $taxlisthash->{$tax} }, $tax_object;
2977 my $name = $hashref_or_error->{'name'};
2978 my $amount = $hashref_or_error->{'amount'};
2980 #warn "adding $amount as $name\n";
2981 $taxname{ $name } ||= [];
2982 push @{ $taxname{ $name } }, $tax;
2984 $tax{ $tax } += $amount;
2986 $tax_location{ $tax } ||= [];
2987 if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
2988 push @{ $tax_location{ $tax } },
2990 'taxnum' => $tax_object->taxnum,
2991 'taxtype' => ref($tax_object),
2992 'pkgnum' => $tax_object->get('pkgnum'),
2993 'locationnum' => $tax_object->get('locationnum'),
2994 'amount' => sprintf('%.2f', $amount ),
2998 $tax_rate_location{ $tax } ||= [];
2999 if ( ref($tax_object) eq 'FS::tax_rate' ) {
3000 my $taxratelocationnum =
3001 $tax_object->tax_rate_location->taxratelocationnum;
3002 push @{ $tax_rate_location{ $tax } },
3004 'taxnum' => $tax_object->taxnum,
3005 'taxtype' => ref($tax_object),
3006 'amount' => sprintf('%.2f', $amount ),
3007 'locationtaxid' => $tax_object->location,
3008 'taxratelocationnum' => $taxratelocationnum,
3014 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
3015 my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
3016 foreach my $tax ( keys %$taxlisthash ) {
3017 foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
3018 next unless ref($_) eq 'FS::cust_bill_pkg';
3020 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
3021 splice( @{ $_->_cust_tax_exempt_pkg } );
3025 #consolidate and create tax line items
3026 warn "consolidating and generating...\n" if $DEBUG > 2;
3027 foreach my $taxname ( keys %taxname ) {
3030 my @cust_bill_pkg_tax_location = ();
3031 my @cust_bill_pkg_tax_rate_location = ();
3032 warn "adding $taxname\n" if $DEBUG > 1;
3033 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
3034 next if $seen{$taxitem}++;
3035 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
3036 $tax += $tax{$taxitem};
3037 push @cust_bill_pkg_tax_location,
3038 map { new FS::cust_bill_pkg_tax_location $_ }
3039 @{ $tax_location{ $taxitem } };
3040 push @cust_bill_pkg_tax_rate_location,
3041 map { new FS::cust_bill_pkg_tax_rate_location $_ }
3042 @{ $tax_rate_location{ $taxitem } };
3046 $tax = sprintf('%.2f', $tax );
3048 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
3054 if ( $pkg_category and
3055 $conf->config('invoice_latexsummary') ||
3056 $conf->config('invoice_htmlsummary')
3060 my %hash = ( 'section' => $pkg_category->categoryname );
3061 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3065 push @tax_line_items, new FS::cust_bill_pkg {
3071 'itemdesc' => $taxname,
3072 'display' => \@display,
3073 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3074 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
3083 my ($self, %params) = @_;
3085 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
3086 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
3087 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
3088 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
3089 my $total_setup = $params{setup} or die "no setup accumulator specified";
3090 my $total_recur = $params{recur} or die "no recur accumulator specified";
3091 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
3092 my $time = $params{'time'} or die "no time specified";
3093 my (%options) = %{$params{options}};
3096 my $real_pkgpart = $params{real_pkgpart};
3097 my %hash = $cust_pkg->hash;
3098 my $old_cust_pkg = new FS::cust_pkg \%hash;
3104 $cust_pkg->pkgpart($part_pkg->pkgpart);
3112 if ( $options{'resetup'}
3113 || ( ! $cust_pkg->setup
3114 && ( ! $cust_pkg->start_date
3115 || $cust_pkg->start_date <= $time
3117 && ( ! $conf->exists('disable_setup_suspended_pkgs')
3118 || ( $conf->exists('disable_setup_suspended_pkgs') &&
3119 ! $cust_pkg->getfield('susp')
3126 warn " bill setup\n" if $DEBUG > 1;
3129 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
3130 return "$@ running calc_setup for $cust_pkg\n"
3133 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
3135 $cust_pkg->setfield('setup', $time)
3136 unless $cust_pkg->setup;
3137 #do need it, but it won't get written to the db
3138 #|| $cust_pkg->pkgpart != $real_pkgpart;
3140 $cust_pkg->setfield('start_date', '')
3141 if $cust_pkg->start_date;
3146 # bill recurring fee
3149 #XXX unit stuff here too
3153 if ( ! $cust_pkg->get('susp')
3154 and ! $cust_pkg->get('start_date')
3155 and ( $part_pkg->getfield('freq') ne '0'
3156 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3158 || ( $part_pkg->plan eq 'voip_cdr'
3159 && $part_pkg->option('bill_every_call')
3161 || ( $options{cancel} )
3164 # XXX should this be a package event? probably. events are called
3165 # at collection time at the moment, though...
3166 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
3167 if $part_pkg->can('reset_usage');
3168 #don't want to reset usage just cause we want a line item??
3169 #&& $part_pkg->pkgpart == $real_pkgpart;
3171 warn " bill recur\n" if $DEBUG > 1;
3174 # XXX shared with $recur_prog
3175 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
3179 #over two params! lets at least switch to a hashref for the rest...
3180 my $increment_next_bill = ( $part_pkg->freq ne '0'
3181 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3182 && !$options{cancel}
3184 my %param = ( 'precommit_hooks' => $precommit_hooks,
3185 'increment_next_bill' => $increment_next_bill,
3186 'discounts' => \@discounts,
3189 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
3190 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
3191 return "$@ running $method for $cust_pkg\n"
3194 if ( $increment_next_bill ) {
3196 my $next_bill = $part_pkg->add_freq($sdate);
3197 return "unparsable frequency: ". $part_pkg->freq
3198 if $next_bill == -1;
3200 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
3201 # only for figuring next bill date, nothing else, so, reset $sdate again
3203 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
3204 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
3205 $cust_pkg->last_bill($sdate);
3207 $cust_pkg->setfield('bill', $next_bill );
3213 warn "\$setup is undefined" unless defined($setup);
3214 warn "\$recur is undefined" unless defined($recur);
3215 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
3218 # If there's line items, create em cust_bill_pkg records
3219 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
3224 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
3225 # hmm.. and if just the options are modified in some weird price plan?
3227 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
3230 my $error = $cust_pkg->replace( $old_cust_pkg,
3231 'options' => { $cust_pkg->options },
3233 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
3234 if $error; #just in case
3237 $setup = sprintf( "%.2f", $setup );
3238 $recur = sprintf( "%.2f", $recur );
3239 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
3240 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3242 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3243 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3246 if ( $setup != 0 || $recur != 0 ) {
3248 warn " charges (setup=$setup, recur=$recur); adding line items\n"
3251 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3253 warn " adding customer package invoice detail: $_\n"
3254 foreach @cust_pkg_detail;
3256 push @details, @cust_pkg_detail;
3258 my $cust_bill_pkg = new FS::cust_bill_pkg {
3259 'pkgnum' => $cust_pkg->pkgnum,
3261 'unitsetup' => $unitsetup,
3263 'unitrecur' => $unitrecur,
3264 'quantity' => $cust_pkg->quantity,
3265 'details' => \@details,
3266 'discounts' => \@discounts,
3267 'hidden' => $part_pkg->hidden,
3270 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3271 $cust_bill_pkg->sdate( $hash{last_bill} );
3272 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
3273 $cust_bill_pkg->edate( $time ) if $options{cancel};
3274 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3275 $cust_bill_pkg->sdate( $sdate );
3276 $cust_bill_pkg->edate( $cust_pkg->bill );
3277 #$cust_bill_pkg->edate( $time ) if $options{cancel};
3280 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3281 unless $part_pkg->pkgpart == $real_pkgpart;
3283 $$total_setup += $setup;
3284 $$total_recur += $recur;
3291 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3292 return $error if $error;
3294 push @$cust_bill_pkgs, $cust_bill_pkg;
3296 } #if $setup != 0 || $recur != 0
3306 my $part_pkg = shift;
3307 my $taxlisthash = shift;
3308 my $cust_bill_pkg = shift;
3309 my $cust_pkg = shift;
3310 my $invoice_time = shift;
3311 my $real_pkgpart = shift;
3312 my $options = shift;
3314 my %cust_bill_pkg = ();
3318 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3319 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3320 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3321 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3323 if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3325 if ( $conf->exists('enable_taxproducts')
3326 && ( scalar($part_pkg->part_pkg_taxoverride)
3327 || $part_pkg->has_taxproduct
3332 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3333 return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3336 foreach my $class (@classes) {
3337 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3338 return $err_or_ref unless ref($err_or_ref);
3339 $taxes{$class} = $err_or_ref;
3342 unless (exists $taxes{''}) {
3343 my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3344 return $err_or_ref unless ref($err_or_ref);
3345 $taxes{''} = $err_or_ref;
3350 my @loc_keys = qw( city county state country );
3352 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3353 my $cust_location = $cust_pkg->cust_location;
3354 %taxhash = map { $_ => $cust_location->$_() } @loc_keys;
3357 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3360 %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3363 $taxhash{'taxclass'} = $part_pkg->taxclass;
3366 my %taxhash_elim = %taxhash;
3367 my @elim = qw( city county state );
3370 #first try a match with taxclass
3371 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3373 if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
3374 #then try a match without taxclass
3375 my %no_taxclass = %taxhash_elim;
3376 $no_taxclass{ 'taxclass' } = '';
3377 @taxes = qsearch( 'cust_main_county', \%no_taxclass );
3380 $taxhash_elim{ shift(@elim) } = '';
3382 } while ( !scalar(@taxes) && scalar(@elim) );
3384 @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3386 if $self->cust_main_exemption; #just to be safe
3388 if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3390 $_->set('pkgnum', $cust_pkg->pkgnum );
3391 $_->set('locationnum', $cust_pkg->locationnum );
3395 $taxes{''} = [ @taxes ];
3396 $taxes{'setup'} = [ @taxes ];
3397 $taxes{'recur'} = [ @taxes ];
3398 $taxes{$_} = [ @taxes ] foreach (@classes);
3400 # # maybe eliminate this entirely, along with all the 0% records
3401 # unless ( @taxes ) {
3403 # "fatal: can't find tax rate for state/county/country/taxclass ".
3404 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
3407 } #if $conf->exists('enable_taxproducts') ...
3412 my $separate = $conf->exists('separate_usage');
3413 my $usage_mandate = $cust_pkg->part_pkg->option('usage_mandate', 'Hush!');
3414 if ( $separate || $cust_bill_pkg->hidden || $usage_mandate ) {
3416 my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3417 my %hash = $cust_bill_pkg->hidden # maybe for all bill linked?
3418 ? ( 'section' => $temp_pkg->part_pkg->categoryname )
3421 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
3422 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
3424 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3425 push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3427 push @display, new FS::cust_bill_pkg_display
3430 ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3434 if ($separate && $section && $summary) {
3435 push @display, new FS::cust_bill_pkg_display { type => 'U',
3440 if ($usage_mandate || $section && $summary) {
3441 $hash{post_total} = 'Y';
3444 $hash{section} = $section if ($separate || $usage_mandate);
3445 push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3448 $cust_bill_pkg->set('display', \@display);
3450 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3451 foreach my $key (keys %tax_cust_bill_pkg) {
3452 my @taxes = @{ $taxes{$key} || [] };
3453 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3455 my %localtaxlisthash = ();
3456 foreach my $tax ( @taxes ) {
3458 my $taxname = ref( $tax ). ' '. $tax->taxnum;
3459 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3460 # ' locationnum'. $cust_pkg->locationnum
3461 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3463 $taxlisthash->{ $taxname } ||= [ $tax ];
3464 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
3466 $localtaxlisthash{ $taxname } ||= [ $tax ];
3467 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
3471 warn "finding taxed taxes...\n" if $DEBUG > 2;
3472 foreach my $tax ( keys %localtaxlisthash ) {
3473 my $tax_object = shift @{ $localtaxlisthash{$tax} };
3474 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3476 next unless $tax_object->can('tax_on_tax');
3478 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3479 my $totname = ref( $tot ). ' '. $tot->taxnum;
3481 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3483 next unless exists( $localtaxlisthash{ $totname } ); # only increase
3485 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3486 my $hashref_or_error =
3487 $tax_object->taxline( $localtaxlisthash{$tax},
3488 'custnum' => $self->custnum,
3489 'invoice_time' => $invoice_time,
3491 return $hashref_or_error
3492 unless ref($hashref_or_error);
3494 $taxlisthash->{ $totname } ||= [ $tot ];
3495 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
3507 my $part_pkg = shift;
3511 my $geocode = $self->geocode('cch');
3513 my @taxclassnums = map { $_->taxclassnum }
3514 $part_pkg->part_pkg_taxoverride($class);
3516 unless (@taxclassnums) {
3517 @taxclassnums = map { $_->taxclassnum }
3518 grep { $_->taxable eq 'Y' }
3519 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3521 warn "Found taxclassnum values of ". join(',', @taxclassnums)
3526 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3528 @taxes = qsearch({ 'table' => 'tax_rate',
3529 'hashref' => { 'geocode' => $geocode, },
3530 'extra_sql' => $extra_sql,
3532 if scalar(@taxclassnums);
3534 warn "Found taxes ".
3535 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
3542 =item collect [ HASHREF | OPTION => VALUE ... ]
3544 (Attempt to) collect money for this customer's outstanding invoices (see
3545 L<FS::cust_bill>). Usually used after the bill method.
3547 Actions are now triggered by billing events; see L<FS::part_event> and the
3548 billing events web interface. Old-style invoice events (see
3549 L<FS::part_bill_event>) have been deprecated.
3551 If there is an error, returns the error, otherwise returns false.
3553 Options are passed as name-value pairs.
3555 Currently available options are:
3561 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.
3565 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3569 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3573 set true to surpress email card/ACH decline notices.
3577 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)
3583 # allows for one time override of normal customer billing method
3588 my( $self, %options ) = @_;
3589 my $invoice_time = $options{'invoice_time'} || time;
3592 local $SIG{HUP} = 'IGNORE';
3593 local $SIG{INT} = 'IGNORE';
3594 local $SIG{QUIT} = 'IGNORE';
3595 local $SIG{TERM} = 'IGNORE';
3596 local $SIG{TSTP} = 'IGNORE';
3597 local $SIG{PIPE} = 'IGNORE';
3599 my $oldAutoCommit = $FS::UID::AutoCommit;
3600 local $FS::UID::AutoCommit = 0;
3603 $self->select_for_update; #mutex
3606 my $balance = $self->balance;
3607 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3610 if ( exists($options{'retry_card'}) ) {
3611 carp 'retry_card option passed to collect is deprecated; use retry';
3612 $options{'retry'} ||= $options{'retry_card'};
3614 if ( exists($options{'retry'}) && $options{'retry'} ) {
3615 my $error = $self->retry_realtime;
3617 $dbh->rollback if $oldAutoCommit;
3622 my $error = $self->do_cust_event(
3623 'debug' => ( $options{'debug'} || 0 ),
3624 'time' => $invoice_time,
3625 'check_freq' => $options{'check_freq'},
3626 'stage' => 'collect',
3629 $dbh->rollback if $oldAutoCommit;
3633 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3638 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3640 Runs billing events; see L<FS::part_event> and the billing events web
3643 If there is an error, returns the error, otherwise returns false.
3645 Options are passed as name-value pairs.
3647 Currently available options are:
3653 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.
3657 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3661 "collect" (the default) or "pre-bill"
3665 set true to surpress email card/ACH decline notices.
3669 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)
3675 # allows for one time override of normal customer billing method
3679 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3682 my( $self, %options ) = @_;
3683 my $time = $options{'time'} || time;
3686 local $SIG{HUP} = 'IGNORE';
3687 local $SIG{INT} = 'IGNORE';
3688 local $SIG{QUIT} = 'IGNORE';
3689 local $SIG{TERM} = 'IGNORE';
3690 local $SIG{TSTP} = 'IGNORE';
3691 local $SIG{PIPE} = 'IGNORE';
3693 my $oldAutoCommit = $FS::UID::AutoCommit;
3694 local $FS::UID::AutoCommit = 0;
3697 $self->select_for_update; #mutex
3700 my $balance = $self->balance;
3701 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
3704 # if ( exists($options{'retry_card'}) ) {
3705 # carp 'retry_card option passed to collect is deprecated; use retry';
3706 # $options{'retry'} ||= $options{'retry_card'};
3708 # if ( exists($options{'retry'}) && $options{'retry'} ) {
3709 # my $error = $self->retry_realtime;
3711 # $dbh->rollback if $oldAutoCommit;
3716 # false laziness w/pay_batch::import_results
3718 my $due_cust_event = $self->due_cust_event(
3719 'debug' => ( $options{'debug'} || 0 ),
3721 'check_freq' => $options{'check_freq'},
3722 'stage' => ( $options{'stage'} || 'collect' ),
3724 unless( ref($due_cust_event) ) {
3725 $dbh->rollback if $oldAutoCommit;
3726 return $due_cust_event;
3729 foreach my $cust_event ( @$due_cust_event ) {
3733 #re-eval event conditions (a previous event could have changed things)
3734 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
3735 #don't leave stray "new/locked" records around
3736 my $error = $cust_event->delete;
3738 #gah, even with transactions
3739 $dbh->commit if $oldAutoCommit; #well.
3746 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
3747 warn " running cust_event ". $cust_event->eventnum. "\n"
3751 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
3752 if ( my $error = $cust_event->do_event() ) {
3753 #XXX wtf is this? figure out a proper dealio with return value
3755 # gah, even with transactions.
3756 $dbh->commit if $oldAutoCommit; #well.
3763 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3768 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
3770 Inserts database records for and returns an ordered listref of new events due
3771 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
3772 events are due, an empty listref is returned. If there is an error, returns a
3773 scalar error message.
3775 To actually run the events, call each event's test_condition method, and if
3776 still true, call the event's do_event method.
3778 Options are passed as a hashref or as a list of name-value pairs. Available
3785 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.
3789 "collect" (the default) or "pre-bill"
3793 "Current time" for the events.
3797 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)
3801 Only return events for the specified eventtable (by default, events of all eventtables are returned)
3805 Explicitly pass the objects to be tested (typically used with eventtable).
3809 Set to true to return the objects, but not actually insert them into the
3816 sub due_cust_event {
3818 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
3821 #my $DEBUG = $opt{'debug'}
3822 local($DEBUG) = $opt{'debug'}
3823 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
3825 warn "$me due_cust_event called with options ".
3826 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
3829 $opt{'time'} ||= time;
3831 local $SIG{HUP} = 'IGNORE';
3832 local $SIG{INT} = 'IGNORE';
3833 local $SIG{QUIT} = 'IGNORE';
3834 local $SIG{TERM} = 'IGNORE';
3835 local $SIG{TSTP} = 'IGNORE';
3836 local $SIG{PIPE} = 'IGNORE';
3838 my $oldAutoCommit = $FS::UID::AutoCommit;
3839 local $FS::UID::AutoCommit = 0;
3842 $self->select_for_update #mutex
3843 unless $opt{testonly};
3846 # find possible events (initial search)
3849 my @cust_event = ();
3851 my @eventtable = $opt{'eventtable'}
3852 ? ( $opt{'eventtable'} )
3853 : FS::part_event->eventtables_runorder;
3855 foreach my $eventtable ( @eventtable ) {
3858 if ( $opt{'objects'} ) {
3860 @objects = @{ $opt{'objects'} };
3864 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
3865 @objects = ( $eventtable eq 'cust_main' )
3867 : ( $self->$eventtable() );
3871 my @e_cust_event = ();
3873 my $cross = "CROSS JOIN $eventtable";
3874 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
3875 unless $eventtable eq 'cust_main';
3877 foreach my $object ( @objects ) {
3879 #this first search uses the condition_sql magic for optimization.
3880 #the more possible events we can eliminate in this step the better
3882 my $cross_where = '';
3883 my $pkey = $object->primary_key;
3884 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
3886 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
3888 FS::part_event_condition->where_conditions_sql( $eventtable,
3889 'time'=>$opt{'time'}
3891 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
3893 $extra_sql = "AND $extra_sql" if $extra_sql;
3895 #here is the agent virtualization
3896 $extra_sql .= " AND ( part_event.agentnum IS NULL
3897 OR part_event.agentnum = ". $self->agentnum. ' )';
3899 $extra_sql .= " $order";
3901 warn "searching for events for $eventtable ". $object->$pkey. "\n"
3902 if $opt{'debug'} > 2;
3903 my @part_event = qsearch( {
3904 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
3905 'select' => 'part_event.*',
3906 'table' => 'part_event',
3907 'addl_from' => "$cross $join",
3908 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
3909 'eventtable' => $eventtable,
3912 'extra_sql' => "AND $cross_where $extra_sql",
3916 my $pkey = $object->primary_key;
3917 warn " ". scalar(@part_event).
3918 " possible events found for $eventtable ". $object->$pkey(). "\n";
3921 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
3925 warn " ". scalar(@e_cust_event).
3926 " subtotal possible cust events found for $eventtable\n"
3929 push @cust_event, @e_cust_event;
3933 warn " ". scalar(@cust_event).
3934 " total possible cust events found in initial search\n"
3942 $opt{stage} ||= 'collect';
3944 grep { my $stage = $_->part_event->event_stage;
3945 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
3955 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
3956 'stats_hashref' => \%unsat ),
3959 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
3962 warn " invalid conditions not eliminated with condition_sql:\n".
3963 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
3964 if keys %unsat && $DEBUG; # > 1;
3970 unless( $opt{testonly} ) {
3971 foreach my $cust_event ( @cust_event ) {
3973 my $error = $cust_event->insert();
3975 $dbh->rollback if $oldAutoCommit;
3982 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3988 warn " returning events: ". Dumper(@cust_event). "\n"
3995 =item retry_realtime
3997 Schedules realtime / batch credit card / electronic check / LEC billing
3998 events for for retry. Useful if card information has changed or manual
3999 retry is desired. The 'collect' method must be called to actually retry
4002 Implementation details: For either this customer, or for each of this
4003 customer's open invoices, changes the status of the first "done" (with
4004 statustext error) realtime processing event to "failed".
4008 sub retry_realtime {
4011 local $SIG{HUP} = 'IGNORE';
4012 local $SIG{INT} = 'IGNORE';
4013 local $SIG{QUIT} = 'IGNORE';
4014 local $SIG{TERM} = 'IGNORE';
4015 local $SIG{TSTP} = 'IGNORE';
4016 local $SIG{PIPE} = 'IGNORE';
4018 my $oldAutoCommit = $FS::UID::AutoCommit;
4019 local $FS::UID::AutoCommit = 0;
4022 #a little false laziness w/due_cust_event (not too bad, really)
4024 my $join = FS::part_event_condition->join_conditions_sql;
4025 my $order = FS::part_event_condition->order_conditions_sql;
4028 . join ( ' OR ' , map {
4029 "( part_event.eventtable = " . dbh->quote($_)
4030 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
4031 } FS::part_event->eventtables)
4034 #here is the agent virtualization
4035 my $agent_virt = " ( part_event.agentnum IS NULL
4036 OR part_event.agentnum = ". $self->agentnum. ' )';
4038 #XXX this shouldn't be hardcoded, actions should declare it...
4039 my @realtime_events = qw(
4040 cust_bill_realtime_card
4041 cust_bill_realtime_check
4042 cust_bill_realtime_lec
4046 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
4051 my @cust_event = qsearchs({
4052 'table' => 'cust_event',
4053 'select' => 'cust_event.*',
4054 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
4055 'hashref' => { 'status' => 'done' },
4056 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
4057 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
4060 my %seen_invnum = ();
4061 foreach my $cust_event (@cust_event) {
4063 #max one for the customer, one for each open invoice
4064 my $cust_X = $cust_event->cust_X;
4065 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
4069 or $cust_event->part_event->eventtable eq 'cust_bill'
4072 my $error = $cust_event->retry;
4074 $dbh->rollback if $oldAutoCommit;
4075 return "error scheduling event for retry: $error";
4080 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4088 =item realtime_collect [ OPTION => VALUE ... ]
4090 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4091 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4092 gateway. See L<http://420.am/business-onlinepayment> and
4093 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4095 On failure returns an error message.
4097 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.
4099 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4101 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
4102 then it is deduced from the customer record.
4104 If no I<amount> is specified, then the customer balance is used.
4106 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4107 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4108 if set, will override the value from the customer record.
4110 I<description> is a free-text field passed to the gateway. It defaults to
4111 the value defined by the business-onlinepayment-description configuration
4112 option, or "Internet services" if that is unset.
4114 If an I<invnum> is specified, this payment (if successful) is applied to the
4115 specified invoice. If you don't specify an I<invnum> you might want to
4116 call the B<apply_payments> method or set the I<apply> option.
4118 I<apply> can be set to true to apply a resulting payment.
4120 I<quiet> can be set true to surpress email decline notices.
4122 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4123 resulting paynum, if any.
4125 I<payunique> is a unique identifier for this payment.
4127 I<session_id> is a session identifier associated with this payment.
4129 I<depend_jobnum> allows payment capture to unlock export jobs
4133 sub realtime_collect {
4134 my( $self, %options ) = @_;
4137 warn "$me realtime_collect:\n";
4138 warn " $_ => $options{$_}\n" foreach keys %options;
4141 $options{amount} = $self->balance unless exists( $options{amount} );
4142 $options{method} = FS::payby->payby2bop($self->payby)
4143 unless exists( $options{method} );
4145 return $self->realtime_bop({%options});
4149 =item realtime_bop { [ ARG => VALUE ... ] }
4151 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4152 via a Business::OnlinePayment realtime gateway. See
4153 L<http://420.am/business-onlinepayment> for supported gateways.
4155 Required arguments in the hashref are I<method>, and I<amount>
4157 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4159 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4161 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4162 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4163 if set, will override the value from the customer record.
4165 I<description> is a free-text field passed to the gateway. It defaults to
4166 the value defined by the business-onlinepayment-description configuration
4167 option, or "Internet services" if that is unset.
4169 If an I<invnum> is specified, this payment (if successful) is applied to the
4170 specified invoice. If you don't specify an I<invnum> you might want to
4171 call the B<apply_payments> method or set the I<apply> option.
4173 I<apply> can be set to true to apply a resulting payment.
4175 I<quiet> can be set true to surpress email decline notices.
4177 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4178 resulting paynum, if any.
4180 I<payunique> is a unique identifier for this payment.
4182 I<session_id> is a session identifier associated with this payment.
4184 I<depend_jobnum> allows payment capture to unlock export jobs
4186 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4190 # some helper routines
4191 sub _bop_recurring_billing {
4192 my( $self, %opt ) = @_;
4194 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
4196 if ( defined($method) && $method eq 'transaction_is_recur' ) {
4198 return 1 if $opt{'trans_is_recur'};
4202 my %hash = ( 'custnum' => $self->custnum,
4207 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4208 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4218 sub _payment_gateway {
4219 my ($self, $options) = @_;
4221 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4222 unless exists($options->{payment_gateway});
4224 $options->{payment_gateway};
4228 my ($self, $options) = @_;
4231 'login' => $options->{payment_gateway}->gateway_username,
4232 'password' => $options->{payment_gateway}->gateway_password,
4237 my ($self, $options) = @_;
4239 $options->{payment_gateway}->gatewaynum
4240 ? $options->{payment_gateway}->options
4241 : @{ $options->{payment_gateway}->get('options') };
4245 my ($self, $options) = @_;
4247 unless ( $options->{'description'} ) {
4248 if ( $conf->exists('business-onlinepayment-description') ) {
4249 my $dtempl = $conf->config('business-onlinepayment-description');
4251 my $agent = $self->agent->agent;
4253 $options->{'description'} = eval qq("$dtempl");
4255 $options->{'description'} = 'Internet services';
4259 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4260 $options->{invnum} ||= '';
4261 $options->{payname} = $self->payname unless exists( $options->{payname} );
4265 my ($self, $options) = @_;
4268 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4269 $content{customer_ip} = $payip if length($payip);
4271 $content{invoice_number} = $options->{'invnum'}
4272 if exists($options->{'invnum'}) && length($options->{'invnum'});
4274 $content{email_customer} =
4275 ( $conf->exists('business-onlinepayment-email_customer')
4276 || $conf->exists('business-onlinepayment-email-override') );
4278 my ($payname, $payfirst, $paylast);
4279 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
4280 ($payname = $options->{payname}) =~
4281 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4282 or return "Illegal payname $payname";
4283 ($payfirst, $paylast) = ($1, $2);
4285 $payfirst = $self->getfield('first');
4286 $paylast = $self->getfield('last');
4287 $payname = "$payfirst $paylast";
4290 $content{last_name} = $paylast;
4291 $content{first_name} = $payfirst;
4293 $content{name} = $payname;
4295 $content{address} = exists($options->{'address1'})
4296 ? $options->{'address1'}
4298 my $address2 = exists($options->{'address2'})
4299 ? $options->{'address2'}
4301 $content{address} .= ", ". $address2 if length($address2);
4303 $content{city} = exists($options->{city})
4306 $content{state} = exists($options->{state})
4309 $content{zip} = exists($options->{zip})
4312 $content{country} = exists($options->{country})
4313 ? $options->{country}
4316 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4317 $content{phone} = $self->daytime || $self->night;
4322 my %bop_method2payby = (
4332 if (ref($_[0]) eq 'HASH') {
4333 %options = %{$_[0]};
4335 my ( $method, $amount ) = ( shift, shift );
4337 $options{method} = $method;
4338 $options{amount} = $amount;
4342 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
4343 warn " $_ => $options{$_}\n" foreach keys %options;
4346 return $self->fake_bop(%options) if $options{'fake'};
4348 $self->_bop_defaults(\%options);
4351 # set trans_is_recur based on invnum if there is one
4354 my $trans_is_recur = 0;
4355 if ( $options{'invnum'} ) {
4357 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
4358 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
4361 map { $_->part_pkg }
4363 map { $_->cust_pkg }
4364 $cust_bill->cust_bill_pkg;
4367 if grep { $_->freq ne '0' } @part_pkg;
4375 my $payment_gateway = $self->_payment_gateway( \%options );
4376 my $namespace = $payment_gateway->gateway_namespace;
4378 eval "use $namespace";
4382 # check for banned credit card/ACH
4385 my $ban = qsearchs('banned_pay', {
4386 'payby' => $bop_method2payby{$options{method}},
4387 'payinfo' => md5_base64($options{payinfo}),
4389 return "Banned credit card" if $ban;
4395 my $bop_content = $self->_bop_content(\%options);
4396 return $bop_content unless ref($bop_content);
4398 my @invoicing_list = $self->invoicing_list_emailonly;
4399 if ( $conf->exists('emailinvoiceautoalways')
4400 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4401 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4402 push @invoicing_list, $self->all_emails;
4405 my $email = ($conf->exists('business-onlinepayment-email-override'))
4406 ? $conf->config('business-onlinepayment-email-override')
4407 : $invoicing_list[0];
4411 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
4413 $content{card_number} = $options{payinfo};
4414 $paydate = exists($options{'paydate'})
4415 ? $options{'paydate'}
4417 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4418 $content{expiration} = "$2/$1";
4420 my $paycvv = exists($options{'paycvv'})
4421 ? $options{'paycvv'}
4423 $content{cvv2} = $paycvv
4426 my $paystart_month = exists($options{'paystart_month'})
4427 ? $options{'paystart_month'}
4428 : $self->paystart_month;
4430 my $paystart_year = exists($options{'paystart_year'})
4431 ? $options{'paystart_year'}
4432 : $self->paystart_year;
4434 $content{card_start} = "$paystart_month/$paystart_year"
4435 if $paystart_month && $paystart_year;
4437 my $payissue = exists($options{'payissue'})
4438 ? $options{'payissue'}
4440 $content{issue_number} = $payissue if $payissue;
4442 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
4443 'trans_is_recur' => $trans_is_recur,
4447 $content{recurring_billing} = 'YES';
4448 $content{acct_code} = 'rebill'
4449 if $conf->exists('credit_card-recurring_billing_acct_code');
4452 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
4453 ( $content{account_number}, $content{routing_code} ) =
4454 split('@', $options{payinfo});
4455 $content{bank_name} = $options{payname};
4456 $content{bank_state} = exists($options{'paystate'})
4457 ? $options{'paystate'}
4458 : $self->getfield('paystate');
4459 $content{account_type} = exists($options{'paytype'})
4460 ? uc($options{'paytype'}) || 'CHECKING'
4461 : uc($self->getfield('paytype')) || 'CHECKING';
4462 $content{account_name} = $self->getfield('first'). ' '.
4463 $self->getfield('last');
4465 $content{customer_org} = $self->company ? 'B' : 'I';
4466 $content{state_id} = exists($options{'stateid'})
4467 ? $options{'stateid'}
4468 : $self->getfield('stateid');
4469 $content{state_id_state} = exists($options{'stateid_state'})
4470 ? $options{'stateid_state'}
4471 : $self->getfield('stateid_state');
4472 $content{customer_ssn} = exists($options{'ss'})
4475 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
4476 $content{phone} = $options{payinfo};
4477 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4484 # run transaction(s)
4487 my $balance = exists( $options{'balance'} )
4488 ? $options{'balance'}
4491 $self->select_for_update; #mutex ... just until we get our pending record in
4493 #the checks here are intended to catch concurrent payments
4494 #double-form-submission prevention is taken care of in cust_pay_pending::check
4497 return "The customer's balance has changed; $options{method} transaction aborted."
4498 if $self->balance < $balance;
4499 #&& $self->balance < $options{amount}; #might as well anyway?
4501 #also check and make sure there aren't *other* pending payments for this cust
4503 my @pending = qsearch('cust_pay_pending', {
4504 'custnum' => $self->custnum,
4505 'status' => { op=>'!=', value=>'done' }
4507 return "A payment is already being processed for this customer (".
4508 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4509 "); $options{method} transaction aborted."
4510 if scalar(@pending);
4512 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4514 my $cust_pay_pending = new FS::cust_pay_pending {
4515 'custnum' => $self->custnum,
4516 #'invnum' => $options{'invnum'},
4517 'paid' => $options{amount},
4519 'payby' => $bop_method2payby{$options{method}},
4520 'payinfo' => $options{payinfo},
4521 'paydate' => $paydate,
4522 'recurring_billing' => $content{recurring_billing},
4523 'pkgnum' => $options{'pkgnum'},
4525 'gatewaynum' => $payment_gateway->gatewaynum || '',
4526 'session_id' => $options{session_id} || '',
4527 'jobnum' => $options{depend_jobnum} || '',
4529 $cust_pay_pending->payunique( $options{payunique} )
4530 if defined($options{payunique}) && length($options{payunique});
4531 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4532 return $cpp_new_err if $cpp_new_err;
4534 my( $action1, $action2 ) =
4535 split( /\s*\,\s*/, $payment_gateway->gateway_action );
4537 my $transaction = new $namespace( $payment_gateway->gateway_module,
4538 $self->_bop_options(\%options),
4541 $transaction->content(
4542 'type' => $options{method},
4543 $self->_bop_auth(\%options),
4544 'action' => $action1,
4545 'description' => $options{'description'},
4546 'amount' => $options{amount},
4547 #'invoice_number' => $options{'invnum'},
4548 'customer_id' => $self->custnum,
4550 'reference' => $cust_pay_pending->paypendingnum, #for now
4555 $cust_pay_pending->status('pending');
4556 my $cpp_pending_err = $cust_pay_pending->replace;
4557 return $cpp_pending_err if $cpp_pending_err;
4560 my $BOP_TESTING = 0;
4561 my $BOP_TESTING_SUCCESS = 1;
4563 unless ( $BOP_TESTING ) {
4564 $transaction->submit();
4566 if ( $BOP_TESTING_SUCCESS ) {
4567 $transaction->is_success(1);
4568 $transaction->authorization('fake auth');
4570 $transaction->is_success(0);
4571 $transaction->error_message('fake failure');
4575 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4577 return { reference => $cust_pay_pending->paypendingnum,
4578 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
4580 } elsif ( $transaction->is_success() && $action2 ) {
4582 $cust_pay_pending->status('authorized');
4583 my $cpp_authorized_err = $cust_pay_pending->replace;
4584 return $cpp_authorized_err if $cpp_authorized_err;
4586 my $auth = $transaction->authorization;
4587 my $ordernum = $transaction->can('order_number')
4588 ? $transaction->order_number
4592 new Business::OnlinePayment( $payment_gateway->gateway_module,
4593 $self->_bop_options(\%options),
4598 type => $options{method},
4600 $self->_bop_auth(\%options),
4601 order_number => $ordernum,
4602 amount => $options{amount},
4603 authorization => $auth,
4604 description => $options{'description'},
4607 foreach my $field (qw( authorization_source_code returned_ACI
4608 transaction_identifier validation_code
4609 transaction_sequence_num local_transaction_date
4610 local_transaction_time AVS_result_code )) {
4611 $capture{$field} = $transaction->$field() if $transaction->can($field);
4614 $capture->content( %capture );
4618 unless ( $capture->is_success ) {
4619 my $e = "Authorization successful but capture failed, custnum #".
4620 $self->custnum. ': '. $capture->result_code.
4621 ": ". $capture->error_message;
4629 # remove paycvv after initial transaction
4632 #false laziness w/misc/process/payment.cgi - check both to make sure working
4634 if ( defined $self->dbdef_table->column('paycvv')
4635 && length($self->paycvv)
4636 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
4638 my $error = $self->remove_cvv;
4640 warn "WARNING: error removing cvv: $error\n";
4648 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
4660 if (ref($_[0]) eq 'HASH') {
4661 %options = %{$_[0]};
4663 my ( $method, $amount ) = ( shift, shift );
4665 $options{method} = $method;
4666 $options{amount} = $amount;
4669 if ( $options{'fake_failure'} ) {
4670 return "Error: No error; test failure requested with fake_failure";
4674 #if ( $payment_gateway->gatewaynum ) { # agent override
4675 # $paybatch = $payment_gateway->gatewaynum. '-';
4678 #$paybatch .= "$processor:". $transaction->authorization;
4680 #$paybatch .= ':'. $transaction->order_number
4681 # if $transaction->can('order_number')
4682 # && length($transaction->order_number);
4684 my $paybatch = 'FakeProcessor:54:32';
4686 my $cust_pay = new FS::cust_pay ( {
4687 'custnum' => $self->custnum,
4688 'invnum' => $options{'invnum'},
4689 'paid' => $options{amount},
4691 'payby' => $bop_method2payby{$options{method}},
4692 #'payinfo' => $payinfo,
4693 'payinfo' => '4111111111111111',
4694 'paybatch' => $paybatch,
4695 #'paydate' => $paydate,
4696 'paydate' => '2012-05-01',
4698 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
4700 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4703 $cust_pay->invnum(''); #try again with no specific invnum
4704 my $error2 = $cust_pay->insert( $options{'manual'} ?
4705 ( 'manual' => 1 ) : ()
4708 # gah, even with transactions.
4709 my $e = 'WARNING: Card/ACH debited but database not updated - '.
4710 "error inserting (fake!) payment: $error2".
4711 " (previously tried insert with invnum #$options{'invnum'}" .
4718 if ( $options{'paynum_ref'} ) {
4719 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4722 return ''; #no error
4727 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
4729 # Wraps up processing of a realtime credit card, ACH (electronic check) or
4730 # phone bill transaction.
4732 sub _realtime_bop_result {
4733 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
4735 warn "$me _realtime_bop_result: pending transaction ".
4736 $cust_pay_pending->paypendingnum. "\n";
4737 warn " $_ => $options{$_}\n" foreach keys %options;
4740 my $payment_gateway = $options{payment_gateway}
4741 or return "no payment gateway in arguments to _realtime_bop_result";
4743 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
4744 my $cpp_captured_err = $cust_pay_pending->replace;
4745 return $cpp_captured_err if $cpp_captured_err;
4747 if ( $transaction->is_success() ) {
4750 if ( $payment_gateway->gatewaynum ) { # agent override
4751 $paybatch = $payment_gateway->gatewaynum. '-';
4754 $paybatch .= $payment_gateway->gateway_module. ":".
4755 $transaction->authorization;
4757 $paybatch .= ':'. $transaction->order_number
4758 if $transaction->can('order_number')
4759 && length($transaction->order_number);
4761 my $cust_pay = new FS::cust_pay ( {
4762 'custnum' => $self->custnum,
4763 'invnum' => $options{'invnum'},
4764 'paid' => $cust_pay_pending->paid,
4766 'payby' => $cust_pay_pending->payby,
4767 #'payinfo' => $payinfo,
4768 'paybatch' => $paybatch,
4769 'paydate' => $cust_pay_pending->paydate,
4770 'pkgnum' => $cust_pay_pending->pkgnum,
4772 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
4773 $cust_pay->payunique( $options{payunique} )
4774 if defined($options{payunique}) && length($options{payunique});
4776 my $oldAutoCommit = $FS::UID::AutoCommit;
4777 local $FS::UID::AutoCommit = 0;
4780 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
4782 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
4785 $cust_pay->invnum(''); #try again with no specific invnum
4786 my $error2 = $cust_pay->insert( $options{'manual'} ?
4787 ( 'manual' => 1 ) : ()
4790 # gah. but at least we have a record of the state we had to abort in
4791 # from cust_pay_pending now.
4792 my $e = "WARNING: $options{method} captured but payment not recorded -".
4793 " error inserting payment (". $payment_gateway->gateway_module.
4795 " (previously tried insert with invnum #$options{'invnum'}" .
4796 ": $error ) - pending payment saved as paypendingnum ".
4797 $cust_pay_pending->paypendingnum. "\n";
4803 my $jobnum = $cust_pay_pending->jobnum;
4805 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
4807 unless ( $placeholder ) {
4808 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4809 my $e = "WARNING: $options{method} captured but job $jobnum not ".
4810 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
4815 $error = $placeholder->delete;
4818 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4819 my $e = "WARNING: $options{method} captured but could not delete ".
4820 "job $jobnum for paypendingnum ".
4821 $cust_pay_pending->paypendingnum. ": $error\n";
4828 if ( $options{'paynum_ref'} ) {
4829 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
4832 $cust_pay_pending->status('done');
4833 $cust_pay_pending->statustext('captured');
4834 $cust_pay_pending->paynum($cust_pay->paynum);
4835 my $cpp_done_err = $cust_pay_pending->replace;
4837 if ( $cpp_done_err ) {
4839 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4840 my $e = "WARNING: $options{method} captured but payment not recorded - ".
4841 "error updating status for paypendingnum ".
4842 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
4848 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4850 if ( $options{'apply'} ) {
4851 my $apply_error = $self->apply_payments_and_credits;
4852 if ( $apply_error ) {
4853 warn "WARNING: error applying payment: $apply_error\n";
4854 #but we still should return no error cause the payment otherwise went
4859 return ''; #no error
4865 my $perror = $payment_gateway->gateway_module. " error: ".
4866 $transaction->error_message;
4868 my $jobnum = $cust_pay_pending->jobnum;
4870 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
4872 if ( $placeholder ) {
4873 my $error = $placeholder->depended_delete;
4874 $error ||= $placeholder->delete;
4875 warn "error removing provisioning jobs after declined paypendingnum ".
4876 $cust_pay_pending->paypendingnum. "\n";
4878 my $e = "error finding job $jobnum for declined paypendingnum ".
4879 $cust_pay_pending->paypendingnum. "\n";
4885 unless ( $transaction->error_message ) {
4888 if ( $transaction->can('response_page') ) {
4890 'page' => ( $transaction->can('response_page')
4891 ? $transaction->response_page
4894 'code' => ( $transaction->can('response_code')
4895 ? $transaction->response_code
4898 'headers' => ( $transaction->can('response_headers')
4899 ? $transaction->response_headers
4905 "No additional debugging information available for ".
4906 $payment_gateway->gateway_module;
4909 $perror .= "No error_message returned from ".
4910 $payment_gateway->gateway_module. " -- ".
4911 ( ref($t_response) ? Dumper($t_response) : $t_response );
4915 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
4916 && $conf->exists('emaildecline')
4917 && grep { $_ ne 'POST' } $self->invoicing_list
4918 && ! grep { $transaction->error_message =~ /$_/ }
4919 $conf->config('emaildecline-exclude')
4921 my @templ = $conf->config('declinetemplate');
4922 my $template = new Text::Template (
4924 SOURCE => [ map "$_\n", @templ ],
4925 ) or return "($perror) can't create template: $Text::Template::ERROR";
4926 $template->compile()
4927 or return "($perror) can't compile template: $Text::Template::ERROR";
4931 scalar( $conf->config('company_name', $self->agentnum ) ),
4932 'company_address' =>
4933 join("\n", $conf->config('company_address', $self->agentnum ) ),
4934 'error' => $transaction->error_message,
4937 my $error = send_email(
4938 'from' => $conf->config('invoice_from', $self->agentnum ),
4939 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
4940 'subject' => 'Your payment could not be processed',
4941 'body' => [ $template->fill_in(HASH => $templ_hash) ],
4944 $perror .= " (also received error sending decline notification: $error)"
4949 $cust_pay_pending->status('done');
4950 $cust_pay_pending->statustext("declined: $perror");
4951 my $cpp_done_err = $cust_pay_pending->replace;
4952 if ( $cpp_done_err ) {
4953 my $e = "WARNING: $options{method} declined but pending payment not ".
4954 "resolved - error updating status for paypendingnum ".
4955 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
4957 $perror = "$e ($perror)";
4965 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
4967 Verifies successful third party processing of a realtime credit card,
4968 ACH (electronic check) or phone bill transaction via a
4969 Business::OnlineThirdPartyPayment realtime gateway. See
4970 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4972 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
4974 The additional options I<payname>, I<city>, I<state>,
4975 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
4976 if set, will override the value from the customer record.
4978 I<description> is a free-text field passed to the gateway. It defaults to
4979 "Internet services".
4981 If an I<invnum> is specified, this payment (if successful) is applied to the
4982 specified invoice. If you don't specify an I<invnum> you might want to
4983 call the B<apply_payments> method.
4985 I<quiet> can be set true to surpress email decline notices.
4987 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
4988 resulting paynum, if any.
4990 I<payunique> is a unique identifier for this payment.
4992 Returns a hashref containing elements bill_error (which will be undefined
4993 upon success) and session_id of any associated session.
4997 sub realtime_botpp_capture {
4998 my( $self, $cust_pay_pending, %options ) = @_;
5000 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5001 warn " $_ => $options{$_}\n" foreach keys %options;
5004 eval "use Business::OnlineThirdPartyPayment";
5008 # select the gateway
5011 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5013 my $payment_gateway = $cust_pay_pending->gatewaynum
5014 ? qsearchs( 'payment_gateway',
5015 { gatewaynum => $cust_pay_pending->gatewaynum }
5017 : $self->agent->payment_gateway( 'method' => $method,
5018 # 'invnum' => $cust_pay_pending->invnum,
5019 # 'payinfo' => $cust_pay_pending->payinfo,
5022 $options{payment_gateway} = $payment_gateway; # for the helper subs
5028 my @invoicing_list = $self->invoicing_list_emailonly;
5029 if ( $conf->exists('emailinvoiceautoalways')
5030 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5031 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5032 push @invoicing_list, $self->all_emails;
5035 my $email = ($conf->exists('business-onlinepayment-email-override'))
5036 ? $conf->config('business-onlinepayment-email-override')
5037 : $invoicing_list[0];
5041 $content{email_customer} =
5042 ( $conf->exists('business-onlinepayment-email_customer')
5043 || $conf->exists('business-onlinepayment-email-override') );
5046 # run transaction(s)
5050 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5051 $self->_bop_options(\%options),
5054 $transaction->reference({ %options });
5056 $transaction->content(
5058 $self->_bop_auth(\%options),
5059 'action' => 'Post Authorization',
5060 'description' => $options{'description'},
5061 'amount' => $cust_pay_pending->paid,
5062 #'invoice_number' => $options{'invnum'},
5063 'customer_id' => $self->custnum,
5064 'referer' => 'http://cleanwhisker.420.am/',
5065 'reference' => $cust_pay_pending->paypendingnum,
5067 'phone' => $self->daytime || $self->night,
5069 # plus whatever is required for bogus capture avoidance
5072 $transaction->submit();
5075 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5078 bill_error => $error,
5079 session_id => $cust_pay_pending->session_id,
5084 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5088 sub default_payment_gateway {
5089 my( $self, $method ) = @_;
5091 die "Real-time processing not enabled\n"
5092 unless $conf->exists('business-onlinepayment');
5094 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5097 my $bop_config = 'business-onlinepayment';
5098 $bop_config .= '-ach'
5099 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5100 my ( $processor, $login, $password, $action, @bop_options ) =
5101 $conf->config($bop_config);
5102 $action ||= 'normal authorization';
5103 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5104 die "No real-time processor is enabled - ".
5105 "did you set the business-onlinepayment configuration value?\n"
5108 ( $processor, $login, $password, $action, @bop_options )
5113 Removes the I<paycvv> field from the database directly.
5115 If there is an error, returns the error, otherwise returns false.
5121 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5122 or return dbh->errstr;
5123 $sth->execute($self->custnum)
5124 or return $sth->errstr;
5129 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5131 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5132 via a Business::OnlinePayment realtime gateway. See
5133 L<http://420.am/business-onlinepayment> for supported gateways.
5135 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5137 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5139 Most gateways require a reference to an original payment transaction to refund,
5140 so you probably need to specify a I<paynum>.
5142 I<amount> defaults to the original amount of the payment if not specified.
5144 I<reason> specifies a reason for the refund.
5146 I<paydate> specifies the expiration date for a credit card overriding the
5147 value from the customer record or the payment record. Specified as yyyy-mm-dd
5149 Implementation note: If I<amount> is unspecified or equal to the amount of the
5150 orignal payment, first an attempt is made to "void" the transaction via
5151 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5152 the normal attempt is made to "refund" ("credit") the transaction via the
5153 gateway is attempted.
5155 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5156 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
5157 #if set, will override the value from the customer record.
5159 #If an I<invnum> is specified, this payment (if successful) is applied to the
5160 #specified invoice. If you don't specify an I<invnum> you might want to
5161 #call the B<apply_payments> method.
5165 #some false laziness w/realtime_bop, not enough to make it worth merging
5166 #but some useful small subs should be pulled out
5167 sub realtime_refund_bop {
5171 if (ref($_[0]) ne 'HASH') {
5172 %options = %{$_[0]};
5176 $options{method} = $method;
5180 warn "$me realtime_refund_bop (new): $options{method} refund\n";
5181 warn " $_ => $options{$_}\n" foreach keys %options;
5185 # look up the original payment and optionally a gateway for that payment
5189 my $amount = $options{'amount'};
5191 my( $processor, $login, $password, @bop_options, $namespace ) ;
5192 my( $auth, $order_number ) = ( '', '', '' );
5194 if ( $options{'paynum'} ) {
5196 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
5197 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5198 or return "Unknown paynum $options{'paynum'}";
5199 $amount ||= $cust_pay->paid;
5201 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5202 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5203 $cust_pay->paybatch;
5204 my $gatewaynum = '';
5205 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5207 if ( $gatewaynum ) { #gateway for the payment to be refunded
5209 my $payment_gateway =
5210 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5211 die "payment gateway $gatewaynum not found"
5212 unless $payment_gateway;
5214 $processor = $payment_gateway->gateway_module;
5215 $login = $payment_gateway->gateway_username;
5216 $password = $payment_gateway->gateway_password;
5217 $namespace = $payment_gateway->gateway_namespace;
5218 @bop_options = $payment_gateway->options;
5220 } else { #try the default gateway
5223 my $payment_gateway =
5224 $self->agent->payment_gateway('method' => $options{method});
5226 ( $conf_processor, $login, $password, $namespace ) =
5227 map { my $method = "gateway_$_"; $payment_gateway->$method }
5228 qw( module username password namespace );
5230 @bop_options = $payment_gateway->gatewaynum
5231 ? $payment_gateway->options
5232 : @{ $payment_gateway->get('options') };
5234 return "processor of payment $options{'paynum'} $processor does not".
5235 " match default processor $conf_processor"
5236 unless $processor eq $conf_processor;
5241 } else { # didn't specify a paynum, so look for agent gateway overrides
5242 # like a normal transaction
5244 my $payment_gateway =
5245 $self->agent->payment_gateway( 'method' => $options{method},
5246 #'payinfo' => $payinfo,
5248 my( $processor, $login, $password, $namespace ) =
5249 map { my $method = "gateway_$_"; $payment_gateway->$method }
5250 qw( module username password namespace );
5252 my @bop_options = $payment_gateway->gatewaynum
5253 ? $payment_gateway->options
5254 : @{ $payment_gateway->get('options') };
5257 return "neither amount nor paynum specified" unless $amount;
5259 eval "use $namespace";
5263 'type' => $options{method},
5265 'password' => $password,
5266 'order_number' => $order_number,
5267 'amount' => $amount,
5268 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5270 $content{authorization} = $auth
5271 if length($auth); #echeck/ACH transactions have an order # but no auth
5272 #(at least with authorize.net)
5274 my $disable_void_after;
5275 if ($conf->exists('disable_void_after')
5276 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5277 $disable_void_after = $1;
5280 #first try void if applicable
5281 if ( $cust_pay && $cust_pay->paid == $amount
5283 ( not defined($disable_void_after) )
5284 || ( time < ($cust_pay->_date + $disable_void_after ) )
5287 warn " attempting void\n" if $DEBUG > 1;
5288 my $void = new Business::OnlinePayment( $processor, @bop_options );
5289 if ( $void->can('info') ) {
5290 if ( $cust_pay->payby eq 'CARD'
5291 && $void->info('CC_void_requires_card') )
5293 $content{'card_number'} = $cust_pay->payinfo;
5294 } elsif ( $cust_pay->payby eq 'CHEK'
5295 && $void->info('ECHECK_void_requires_account') )
5297 ( $content{'account_number'}, $content{'routing_code'} ) =
5298 split('@', $cust_pay->payinfo);
5299 $content{'name'} = $self->get('first'). ' '. $self->get('last');
5302 $void->content( 'action' => 'void', %content );
5304 if ( $void->is_success ) {
5305 my $error = $cust_pay->void($options{'reason'});
5307 # gah, even with transactions.
5308 my $e = 'WARNING: Card/ACH voided but database not updated - '.
5309 "error voiding payment: $error";
5313 warn " void successful\n" if $DEBUG > 1;
5318 warn " void unsuccessful, trying refund\n"
5322 my $address = $self->address1;
5323 $address .= ", ". $self->address2 if $self->address2;
5325 my($payname, $payfirst, $paylast);
5326 if ( $self->payname && $options{method} ne 'ECHECK' ) {
5327 $payname = $self->payname;
5328 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5329 or return "Illegal payname $payname";
5330 ($payfirst, $paylast) = ($1, $2);
5332 $payfirst = $self->getfield('first');
5333 $paylast = $self->getfield('last');
5334 $payname = "$payfirst $paylast";
5337 my @invoicing_list = $self->invoicing_list_emailonly;
5338 if ( $conf->exists('emailinvoiceautoalways')
5339 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5340 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5341 push @invoicing_list, $self->all_emails;
5344 my $email = ($conf->exists('business-onlinepayment-email-override'))
5345 ? $conf->config('business-onlinepayment-email-override')
5346 : $invoicing_list[0];
5348 my $payip = exists($options{'payip'})
5351 $content{customer_ip} = $payip
5355 if ( $options{method} eq 'CC' ) {
5358 $content{card_number} = $payinfo = $cust_pay->payinfo;
5359 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
5360 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
5361 ($content{expiration} = "$2/$1"); # where available
5363 $content{card_number} = $payinfo = $self->payinfo;
5364 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
5365 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5366 $content{expiration} = "$2/$1";
5369 } elsif ( $options{method} eq 'ECHECK' ) {
5372 $payinfo = $cust_pay->payinfo;
5374 $payinfo = $self->payinfo;
5376 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
5377 $content{bank_name} = $self->payname;
5378 $content{account_type} = 'CHECKING';
5379 $content{account_name} = $payname;
5380 $content{customer_org} = $self->company ? 'B' : 'I';
5381 $content{customer_ssn} = $self->ss;
5382 } elsif ( $options{method} eq 'LEC' ) {
5383 $content{phone} = $payinfo = $self->payinfo;
5387 my $refund = new Business::OnlinePayment( $processor, @bop_options );
5388 my %sub_content = $refund->content(
5389 'action' => 'credit',
5390 'customer_id' => $self->custnum,
5391 'last_name' => $paylast,
5392 'first_name' => $payfirst,
5394 'address' => $address,
5395 'city' => $self->city,
5396 'state' => $self->state,
5397 'zip' => $self->zip,
5398 'country' => $self->country,
5400 'phone' => $self->daytime || $self->night,
5403 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
5407 return "$processor error: ". $refund->error_message
5408 unless $refund->is_success();
5410 my $paybatch = "$processor:". $refund->authorization;
5411 $paybatch .= ':'. $refund->order_number
5412 if $refund->can('order_number') && $refund->order_number;
5414 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
5415 my @cust_bill_pay = $cust_pay->cust_bill_pay;
5416 last unless @cust_bill_pay;
5417 my $cust_bill_pay = pop @cust_bill_pay;
5418 my $error = $cust_bill_pay->delete;
5422 my $cust_refund = new FS::cust_refund ( {
5423 'custnum' => $self->custnum,
5424 'paynum' => $options{'paynum'},
5425 'refund' => $amount,
5427 'payby' => $bop_method2payby{$options{method}},
5428 'payinfo' => $payinfo,
5429 'paybatch' => $paybatch,
5430 'reason' => $options{'reason'} || 'card or ACH refund',
5432 my $error = $cust_refund->insert;
5434 $cust_refund->paynum(''); #try again with no specific paynum
5435 my $error2 = $cust_refund->insert;
5437 # gah, even with transactions.
5438 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
5439 "error inserting refund ($processor): $error2".
5440 " (previously tried insert with paynum #$options{'paynum'}" .
5451 =item batch_card OPTION => VALUE...
5453 Adds a payment for this invoice to the pending credit card batch (see
5454 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
5455 runs the payment using a realtime gateway.
5460 my ($self, %options) = @_;
5463 if (exists($options{amount})) {
5464 $amount = $options{amount};
5466 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
5468 return '' unless $amount > 0;
5470 my $invnum = delete $options{invnum};
5471 my $payby = $options{invnum} || $self->payby; #dubious
5473 if ($options{'realtime'}) {
5474 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
5480 my $oldAutoCommit = $FS::UID::AutoCommit;
5481 local $FS::UID::AutoCommit = 0;
5484 #this needs to handle mysql as well as Pg, like svc_acct.pm
5485 #(make it into a common function if folks need to do batching with mysql)
5486 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
5487 or return "Cannot lock pay_batch: " . $dbh->errstr;
5491 'payby' => FS::payby->payby2payment($payby),
5494 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
5496 unless ( $pay_batch ) {
5497 $pay_batch = new FS::pay_batch \%pay_batch;
5498 my $error = $pay_batch->insert;
5500 $dbh->rollback if $oldAutoCommit;
5501 die "error creating new batch: $error\n";
5505 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
5506 'batchnum' => $pay_batch->batchnum,
5507 'custnum' => $self->custnum,
5510 foreach (qw( address1 address2 city state zip country payby payinfo paydate
5512 $options{$_} = '' unless exists($options{$_});
5515 my $cust_pay_batch = new FS::cust_pay_batch ( {
5516 'batchnum' => $pay_batch->batchnum,
5517 'invnum' => $invnum || 0, # is there a better value?
5518 # this field should be
5520 # cust_bill_pay_batch now
5521 'custnum' => $self->custnum,
5522 'last' => $self->getfield('last'),
5523 'first' => $self->getfield('first'),
5524 'address1' => $options{address1} || $self->address1,
5525 'address2' => $options{address2} || $self->address2,
5526 'city' => $options{city} || $self->city,
5527 'state' => $options{state} || $self->state,
5528 'zip' => $options{zip} || $self->zip,
5529 'country' => $options{country} || $self->country,
5530 'payby' => $options{payby} || $self->payby,
5531 'payinfo' => $options{payinfo} || $self->payinfo,
5532 'exp' => $options{paydate} || $self->paydate,
5533 'payname' => $options{payname} || $self->payname,
5534 'amount' => $amount, # consolidating
5537 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
5538 if $old_cust_pay_batch;
5541 if ($old_cust_pay_batch) {
5542 $error = $cust_pay_batch->replace($old_cust_pay_batch)
5544 $error = $cust_pay_batch->insert;
5548 $dbh->rollback if $oldAutoCommit;
5552 my $unapplied = $self->total_unapplied_credits
5553 + $self->total_unapplied_payments
5554 + $self->in_transit_payments;
5555 foreach my $cust_bill ($self->open_cust_bill) {
5556 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
5557 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
5558 'invnum' => $cust_bill->invnum,
5559 'paybatchnum' => $cust_pay_batch->paybatchnum,
5560 'amount' => $cust_bill->owed,
5563 if ($unapplied >= $cust_bill_pay_batch->amount){
5564 $unapplied -= $cust_bill_pay_batch->amount;
5567 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
5568 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
5570 $error = $cust_bill_pay_batch->insert;
5572 $dbh->rollback if $oldAutoCommit;
5577 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5581 =item apply_payments_and_credits [ OPTION => VALUE ... ]
5583 Applies unapplied payments and credits.
5585 In most cases, this new method should be used in place of sequential
5586 apply_payments and apply_credits methods.
5588 A hash of optional arguments may be passed. Currently "manual" is supported.
5589 If true, a payment receipt is sent instead of a statement when
5590 'payment_receipt_email' configuration option is set.
5592 If there is an error, returns the error, otherwise returns false.
5596 sub apply_payments_and_credits {
5597 my( $self, %options ) = @_;
5599 local $SIG{HUP} = 'IGNORE';
5600 local $SIG{INT} = 'IGNORE';
5601 local $SIG{QUIT} = 'IGNORE';
5602 local $SIG{TERM} = 'IGNORE';
5603 local $SIG{TSTP} = 'IGNORE';
5604 local $SIG{PIPE} = 'IGNORE';
5606 my $oldAutoCommit = $FS::UID::AutoCommit;
5607 local $FS::UID::AutoCommit = 0;
5610 $self->select_for_update; #mutex
5612 foreach my $cust_bill ( $self->open_cust_bill ) {
5613 my $error = $cust_bill->apply_payments_and_credits(%options);
5615 $dbh->rollback if $oldAutoCommit;
5616 return "Error applying: $error";
5620 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5625 =item apply_credits OPTION => VALUE ...
5627 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
5628 to outstanding invoice balances in chronological order (or reverse
5629 chronological order if the I<order> option is set to B<newest>) and returns the
5630 value of any remaining unapplied credits available for refund (see
5631 L<FS::cust_refund>).
5633 Dies if there is an error.
5641 local $SIG{HUP} = 'IGNORE';
5642 local $SIG{INT} = 'IGNORE';
5643 local $SIG{QUIT} = 'IGNORE';
5644 local $SIG{TERM} = 'IGNORE';
5645 local $SIG{TSTP} = 'IGNORE';
5646 local $SIG{PIPE} = 'IGNORE';
5648 my $oldAutoCommit = $FS::UID::AutoCommit;
5649 local $FS::UID::AutoCommit = 0;
5652 $self->select_for_update; #mutex
5654 unless ( $self->total_unapplied_credits ) {
5655 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5659 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
5660 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
5662 my @invoices = $self->open_cust_bill;
5663 @invoices = sort { $b->_date <=> $a->_date } @invoices
5664 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
5666 if ( $conf->exists('pkg-balances') ) {
5667 # limit @credits to those w/ a pkgnum grepped from $self
5669 foreach my $i (@invoices) {
5670 foreach my $li ( $i->cust_bill_pkg ) {
5671 $pkgnums{$li->pkgnum} = 1;
5674 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
5679 foreach my $cust_bill ( @invoices ) {
5681 if ( !defined($credit) || $credit->credited == 0) {
5682 $credit = pop @credits or last;
5686 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
5687 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
5689 $owed = $cust_bill->owed;
5691 unless ( $owed > 0 ) {
5692 push @credits, $credit;
5696 my $amount = min( $credit->credited, $owed );
5698 my $cust_credit_bill = new FS::cust_credit_bill ( {
5699 'crednum' => $credit->crednum,
5700 'invnum' => $cust_bill->invnum,
5701 'amount' => $amount,
5703 $cust_credit_bill->pkgnum( $credit->pkgnum )
5704 if $conf->exists('pkg-balances') && $credit->pkgnum;
5705 my $error = $cust_credit_bill->insert;
5707 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5711 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5715 my $total_unapplied_credits = $self->total_unapplied_credits;
5717 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5719 return $total_unapplied_credits;
5722 =item apply_payments [ OPTION => VALUE ... ]
5724 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
5725 to outstanding invoice balances in chronological order.
5727 #and returns the value of any remaining unapplied payments.
5729 A hash of optional arguments may be passed. Currently "manual" is supported.
5730 If true, a payment receipt is sent instead of a statement when
5731 'payment_receipt_email' configuration option is set.
5733 Dies if there is an error.
5737 sub apply_payments {
5738 my( $self, %options ) = @_;
5740 local $SIG{HUP} = 'IGNORE';
5741 local $SIG{INT} = 'IGNORE';
5742 local $SIG{QUIT} = 'IGNORE';
5743 local $SIG{TERM} = 'IGNORE';
5744 local $SIG{TSTP} = 'IGNORE';
5745 local $SIG{PIPE} = 'IGNORE';
5747 my $oldAutoCommit = $FS::UID::AutoCommit;
5748 local $FS::UID::AutoCommit = 0;
5751 $self->select_for_update; #mutex
5755 my @payments = sort { $b->_date <=> $a->_date }
5756 grep { $_->unapplied > 0 }
5759 my @invoices = sort { $a->_date <=> $b->_date}
5760 grep { $_->owed > 0 }
5763 if ( $conf->exists('pkg-balances') ) {
5764 # limit @payments to those w/ a pkgnum grepped from $self
5766 foreach my $i (@invoices) {
5767 foreach my $li ( $i->cust_bill_pkg ) {
5768 $pkgnums{$li->pkgnum} = 1;
5771 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
5776 foreach my $cust_bill ( @invoices ) {
5778 if ( !defined($payment) || $payment->unapplied == 0 ) {
5779 $payment = pop @payments or last;
5783 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
5784 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
5786 $owed = $cust_bill->owed;
5788 unless ( $owed > 0 ) {
5789 push @payments, $payment;
5793 my $amount = min( $payment->unapplied, $owed );
5795 my $cust_bill_pay = new FS::cust_bill_pay ( {
5796 'paynum' => $payment->paynum,
5797 'invnum' => $cust_bill->invnum,
5798 'amount' => $amount,
5800 $cust_bill_pay->pkgnum( $payment->pkgnum )
5801 if $conf->exists('pkg-balances') && $payment->pkgnum;
5802 my $error = $cust_bill_pay->insert(%options);
5804 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5808 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
5812 my $total_unapplied_payments = $self->total_unapplied_payments;
5814 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5816 return $total_unapplied_payments;
5821 Returns the total owed for this customer on all invoices
5822 (see L<FS::cust_bill/owed>).
5828 $self->total_owed_date(2145859200); #12/31/2037
5831 =item total_owed_date TIME
5833 Returns the total owed for this customer on all invoices with date earlier than
5834 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
5835 see L<Time::Local> and L<Date::Parse> for conversion functions.
5839 sub total_owed_date {
5843 # my $custnum = $self->custnum;
5845 # my $owed_sql = FS::cust_bill->owed_sql;
5848 # SELECT SUM($owed_sql) FROM cust_bill
5849 # WHERE custnum = $custnum
5850 # AND _date <= $time
5853 # my $sth = dbh->prepare($sql) or die dbh->errstr;
5854 # $sth->execute() or die $sth->errstr;
5856 # return sprintf( '%.2f', $sth->fetchrow_arrayref->[0] );
5859 foreach my $cust_bill (
5860 grep { $_->_date <= $time }
5861 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
5863 $total_bill += $cust_bill->owed;
5865 sprintf( "%.2f", $total_bill );
5869 =item total_owed_pkgnum PKGNUM
5871 Returns the total owed on all invoices for this customer's specific package
5872 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
5876 sub total_owed_pkgnum {
5877 my( $self, $pkgnum ) = @_;
5878 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
5881 =item total_owed_date_pkgnum TIME PKGNUM
5883 Returns the total owed for this customer's specific package when using
5884 experimental package balances on all invoices with date earlier than
5885 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
5886 see L<Time::Local> and L<Date::Parse> for conversion functions.
5890 sub total_owed_date_pkgnum {
5891 my( $self, $time, $pkgnum ) = @_;
5894 foreach my $cust_bill (
5895 grep { $_->_date <= $time }
5896 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
5898 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
5900 sprintf( "%.2f", $total_bill );
5906 Returns the total amount of all payments.
5913 $total += $_->paid foreach $self->cust_pay;
5914 sprintf( "%.2f", $total );
5917 =item total_unapplied_credits
5919 Returns the total outstanding credit (see L<FS::cust_credit>) for this
5920 customer. See L<FS::cust_credit/credited>.
5922 =item total_credited
5924 Old name for total_unapplied_credits. Don't use.
5928 sub total_credited {
5929 #carp "total_credited deprecated, use total_unapplied_credits";
5930 shift->total_unapplied_credits(@_);
5933 sub total_unapplied_credits {
5935 my $total_credit = 0;
5936 $total_credit += $_->credited foreach $self->cust_credit;
5937 sprintf( "%.2f", $total_credit );
5940 =item total_unapplied_credits_pkgnum PKGNUM
5942 Returns the total outstanding credit (see L<FS::cust_credit>) for this
5943 customer. See L<FS::cust_credit/credited>.
5947 sub total_unapplied_credits_pkgnum {
5948 my( $self, $pkgnum ) = @_;
5949 my $total_credit = 0;
5950 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
5951 sprintf( "%.2f", $total_credit );
5955 =item total_unapplied_payments
5957 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
5958 See L<FS::cust_pay/unapplied>.
5962 sub total_unapplied_payments {
5964 my $total_unapplied = 0;
5965 $total_unapplied += $_->unapplied foreach $self->cust_pay;
5966 sprintf( "%.2f", $total_unapplied );
5969 =item total_unapplied_payments_pkgnum PKGNUM
5971 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
5972 specific package when using experimental package balances. See
5973 L<FS::cust_pay/unapplied>.
5977 sub total_unapplied_payments_pkgnum {
5978 my( $self, $pkgnum ) = @_;
5979 my $total_unapplied = 0;
5980 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
5981 sprintf( "%.2f", $total_unapplied );
5985 =item total_unapplied_refunds
5987 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
5988 customer. See L<FS::cust_refund/unapplied>.
5992 sub total_unapplied_refunds {
5994 my $total_unapplied = 0;
5995 $total_unapplied += $_->unapplied foreach $self->cust_refund;
5996 sprintf( "%.2f", $total_unapplied );
6001 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6002 total_unapplied_credits minus total_unapplied_payments).
6010 + $self->total_unapplied_refunds
6011 - $self->total_unapplied_credits
6012 - $self->total_unapplied_payments
6016 =item balance_date TIME
6018 Returns the balance for this customer, only considering invoices with date
6019 earlier than TIME (total_owed_date minus total_credited minus
6020 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
6021 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
6030 $self->total_owed_date($time)
6031 + $self->total_unapplied_refunds
6032 - $self->total_unapplied_credits
6033 - $self->total_unapplied_payments
6037 =item balance_date_range START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
6039 Returns the balance for this customer, only considering invoices with date
6040 earlier than START_TIME, and optionally not later than END_TIME
6041 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
6043 Times are specified as SQL fragments or numeric
6044 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
6045 L<Date::Parse> for conversion functions. The empty string can be passed
6046 to disable that time constraint completely.
6048 Available options are:
6052 =item unapplied_date
6054 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)
6060 sub balance_date_range {
6062 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
6063 ') FROM cust_main WHERE custnum='. $self->custnum;
6064 sprintf( "%.2f", $self->scalar_sql($sql) );
6067 =item balance_pkgnum PKGNUM
6069 Returns the balance for this customer's specific package when using
6070 experimental package balances (total_owed plus total_unrefunded, minus
6071 total_unapplied_credits minus total_unapplied_payments)
6075 sub balance_pkgnum {
6076 my( $self, $pkgnum ) = @_;
6079 $self->total_owed_pkgnum($pkgnum)
6080 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6081 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
6082 - $self->total_unapplied_credits_pkgnum($pkgnum)
6083 - $self->total_unapplied_payments_pkgnum($pkgnum)
6087 =item in_transit_payments
6089 Returns the total of requests for payments for this customer pending in
6090 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
6094 sub in_transit_payments {
6096 my $in_transit_payments = 0;
6097 foreach my $pay_batch ( qsearch('pay_batch', {
6100 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6101 'batchnum' => $pay_batch->batchnum,
6102 'custnum' => $self->custnum,
6104 $in_transit_payments += $cust_pay_batch->amount;
6107 sprintf( "%.2f", $in_transit_payments );
6112 Returns a hash of useful information for making a payment.
6122 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6123 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6124 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6128 For credit card transactions:
6140 For electronic check transactions:
6155 $return{balance} = $self->balance;
6157 $return{payname} = $self->payname
6158 || ( $self->first. ' '. $self->get('last') );
6160 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6162 $return{payby} = $self->payby;
6163 $return{stateid_state} = $self->stateid_state;
6165 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6166 $return{card_type} = cardtype($self->payinfo);
6167 $return{payinfo} = $self->paymask;
6169 @return{'month', 'year'} = $self->paydate_monthyear;
6173 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6174 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6175 $return{payinfo1} = $payinfo1;
6176 $return{payinfo2} = $payinfo2;
6177 $return{paytype} = $self->paytype;
6178 $return{paystate} = $self->paystate;
6182 #doubleclick protection
6184 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6190 =item paydate_monthyear
6192 Returns a two-element list consisting of the month and year of this customer's
6193 paydate (credit card expiration date for CARD customers)
6197 sub paydate_monthyear {
6199 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6201 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6208 =item tax_exemption TAXNAME
6213 my( $self, $taxname ) = @_;
6215 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6216 'taxname' => $taxname,
6221 =item cust_main_exemption
6225 sub cust_main_exemption {
6227 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6230 =item invoicing_list [ ARRAYREF ]
6232 If an arguement is given, sets these email addresses as invoice recipients
6233 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
6234 (except as warnings), so use check_invoicing_list first.
6236 Returns a list of email addresses (with svcnum entries expanded).
6238 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
6239 check it without disturbing anything by passing nothing.
6241 This interface may change in the future.
6245 sub invoicing_list {
6246 my( $self, $arrayref ) = @_;
6249 my @cust_main_invoice;
6250 if ( $self->custnum ) {
6251 @cust_main_invoice =
6252 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6254 @cust_main_invoice = ();
6256 foreach my $cust_main_invoice ( @cust_main_invoice ) {
6257 #warn $cust_main_invoice->destnum;
6258 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6259 #warn $cust_main_invoice->destnum;
6260 my $error = $cust_main_invoice->delete;
6261 warn $error if $error;
6264 if ( $self->custnum ) {
6265 @cust_main_invoice =
6266 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6268 @cust_main_invoice = ();
6270 my %seen = map { $_->address => 1 } @cust_main_invoice;
6271 foreach my $address ( @{$arrayref} ) {
6272 next if exists $seen{$address} && $seen{$address};
6273 $seen{$address} = 1;
6274 my $cust_main_invoice = new FS::cust_main_invoice ( {
6275 'custnum' => $self->custnum,
6278 my $error = $cust_main_invoice->insert;
6279 warn $error if $error;
6283 if ( $self->custnum ) {
6285 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6292 =item check_invoicing_list ARRAYREF
6294 Checks these arguements as valid input for the invoicing_list method. If there
6295 is an error, returns the error, otherwise returns false.
6299 sub check_invoicing_list {
6300 my( $self, $arrayref ) = @_;
6302 foreach my $address ( @$arrayref ) {
6304 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6305 return 'Can\'t add FAX invoice destination with a blank FAX number.';
6308 my $cust_main_invoice = new FS::cust_main_invoice ( {
6309 'custnum' => $self->custnum,
6312 my $error = $self->custnum
6313 ? $cust_main_invoice->check
6314 : $cust_main_invoice->checkdest
6316 return $error if $error;
6320 return "Email address required"
6321 if $conf->exists('cust_main-require_invoicing_list_email')
6322 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6327 =item set_default_invoicing_list
6329 Sets the invoicing list to all accounts associated with this customer,
6330 overwriting any previous invoicing list.
6334 sub set_default_invoicing_list {
6336 $self->invoicing_list($self->all_emails);
6341 Returns the email addresses of all accounts provisioned for this customer.
6348 foreach my $cust_pkg ( $self->all_pkgs ) {
6349 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6351 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6352 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6354 $list{$_}=1 foreach map { $_->email } @svc_acct;
6359 =item invoicing_list_addpost
6361 Adds postal invoicing to this customer. If this customer is already configured
6362 to receive postal invoices, does nothing.
6366 sub invoicing_list_addpost {
6368 return if grep { $_ eq 'POST' } $self->invoicing_list;
6369 my @invoicing_list = $self->invoicing_list;
6370 push @invoicing_list, 'POST';
6371 $self->invoicing_list(\@invoicing_list);
6374 =item invoicing_list_emailonly
6376 Returns the list of email invoice recipients (invoicing_list without non-email
6377 destinations such as POST and FAX).
6381 sub invoicing_list_emailonly {
6383 warn "$me invoicing_list_emailonly called"
6385 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
6388 =item invoicing_list_emailonly_scalar
6390 Returns the list of email invoice recipients (invoicing_list without non-email
6391 destinations such as POST and FAX) as a comma-separated scalar.
6395 sub invoicing_list_emailonly_scalar {
6397 warn "$me invoicing_list_emailonly_scalar called"
6399 join(', ', $self->invoicing_list_emailonly);
6402 =item referral_custnum_cust_main
6404 Returns the customer who referred this customer (or the empty string, if
6405 this customer was not referred).
6407 Note the difference with referral_cust_main method: This method,
6408 referral_custnum_cust_main returns the single customer (if any) who referred
6409 this customer, while referral_cust_main returns an array of customers referred
6414 sub referral_custnum_cust_main {
6416 return '' unless $self->referral_custnum;
6417 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6420 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
6422 Returns an array of customers referred by this customer (referral_custnum set
6423 to this custnum). If DEPTH is given, recurses up to the given depth, returning
6424 customers referred by customers referred by this customer and so on, inclusive.
6425 The default behavior is DEPTH 1 (no recursion).
6427 Note the difference with referral_custnum_cust_main method: This method,
6428 referral_cust_main, returns an array of customers referred BY this customer,
6429 while referral_custnum_cust_main returns the single customer (if any) who
6430 referred this customer.
6434 sub referral_cust_main {
6436 my $depth = @_ ? shift : 1;
6437 my $exclude = @_ ? shift : {};
6440 map { $exclude->{$_->custnum}++; $_; }
6441 grep { ! $exclude->{ $_->custnum } }
6442 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
6446 map { $_->referral_cust_main($depth-1, $exclude) }
6453 =item referral_cust_main_ncancelled
6455 Same as referral_cust_main, except only returns customers with uncancelled
6460 sub referral_cust_main_ncancelled {
6462 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
6465 =item referral_cust_pkg [ DEPTH ]
6467 Like referral_cust_main, except returns a flat list of all unsuspended (and
6468 uncancelled) packages for each customer. The number of items in this list may
6469 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
6473 sub referral_cust_pkg {
6475 my $depth = @_ ? shift : 1;
6477 map { $_->unsuspended_pkgs }
6478 grep { $_->unsuspended_pkgs }
6479 $self->referral_cust_main($depth);
6482 =item referring_cust_main
6484 Returns the single cust_main record for the customer who referred this customer
6485 (referral_custnum), or false.
6489 sub referring_cust_main {
6491 return '' unless $self->referral_custnum;
6492 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6495 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
6497 Applies a credit to this customer. If there is an error, returns the error,
6498 otherwise returns false.
6500 REASON can be a text string, an FS::reason object, or a scalar reference to
6501 a reasonnum. If a text string, it will be automatically inserted as a new
6502 reason, and a 'reason_type' option must be passed to indicate the
6503 FS::reason_type for the new reason.
6505 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
6507 Any other options are passed to FS::cust_credit::insert.
6512 my( $self, $amount, $reason, %options ) = @_;
6514 my $cust_credit = new FS::cust_credit {
6515 'custnum' => $self->custnum,
6516 'amount' => $amount,
6519 if ( ref($reason) ) {
6521 if ( ref($reason) eq 'SCALAR' ) {
6522 $cust_credit->reasonnum( $$reason );
6524 $cust_credit->reasonnum( $reason->reasonnum );
6528 $cust_credit->set('reason', $reason)
6531 for (qw( addlinfo eventnum )) {
6532 $cust_credit->$_( delete $options{$_} )
6533 if exists($options{$_});
6536 $cust_credit->insert(%options);
6540 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
6542 Creates a one-time charge for this customer. If there is an error, returns
6543 the error, otherwise returns false.
6545 New-style, with a hashref of options:
6547 my $error = $cust_main->charge(
6551 'start_date' => str2time('7/4/2009'),
6552 'pkg' => 'Description',
6553 'comment' => 'Comment',
6554 'additional' => [], #extra invoice detail
6555 'classnum' => 1, #pkg_class
6557 'setuptax' => '', # or 'Y' for tax exempt
6560 'taxclass' => 'Tax class',
6563 'taxproduct' => 2, #part_pkg_taxproduct
6564 'override' => {}, #XXX describe
6566 #will be filled in with the new object
6567 'cust_pkg_ref' => \$cust_pkg,
6569 #generate an invoice immediately
6571 'invoice_terms' => '', #with these terms
6577 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
6583 my ( $amount, $quantity, $start_date, $classnum );
6584 my ( $pkg, $comment, $additional );
6585 my ( $setuptax, $taxclass ); #internal taxes
6586 my ( $taxproduct, $override ); #vendor (CCH) taxes
6588 my $cust_pkg_ref = '';
6589 my ( $bill_now, $invoice_terms ) = ( 0, '' );
6590 if ( ref( $_[0] ) ) {
6591 $amount = $_[0]->{amount};
6592 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
6593 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
6594 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
6595 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
6596 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
6597 : '$'. sprintf("%.2f",$amount);
6598 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
6599 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
6600 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
6601 $additional = $_[0]->{additional} || [];
6602 $taxproduct = $_[0]->{taxproductnum};
6603 $override = { '' => $_[0]->{tax_override} };
6604 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
6605 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
6606 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
6611 $pkg = @_ ? shift : 'One-time charge';
6612 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
6614 $taxclass = @_ ? shift : '';
6618 local $SIG{HUP} = 'IGNORE';
6619 local $SIG{INT} = 'IGNORE';
6620 local $SIG{QUIT} = 'IGNORE';
6621 local $SIG{TERM} = 'IGNORE';
6622 local $SIG{TSTP} = 'IGNORE';
6623 local $SIG{PIPE} = 'IGNORE';
6625 my $oldAutoCommit = $FS::UID::AutoCommit;
6626 local $FS::UID::AutoCommit = 0;
6629 my $part_pkg = new FS::part_pkg ( {
6631 'comment' => $comment,
6635 'classnum' => ( $classnum ? $classnum : '' ),
6636 'setuptax' => $setuptax,
6637 'taxclass' => $taxclass,
6638 'taxproductnum' => $taxproduct,
6641 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
6642 ( 0 .. @$additional - 1 )
6644 'additional_count' => scalar(@$additional),
6645 'setup_fee' => $amount,
6648 my $error = $part_pkg->insert( options => \%options,
6649 tax_overrides => $override,
6652 $dbh->rollback if $oldAutoCommit;
6656 my $pkgpart = $part_pkg->pkgpart;
6657 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
6658 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
6659 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
6660 $error = $type_pkgs->insert;
6662 $dbh->rollback if $oldAutoCommit;
6667 my $cust_pkg = new FS::cust_pkg ( {
6668 'custnum' => $self->custnum,
6669 'pkgpart' => $pkgpart,
6670 'quantity' => $quantity,
6671 'start_date' => $start_date,
6672 'no_auto' => $no_auto,
6675 $error = $cust_pkg->insert;
6677 $dbh->rollback if $oldAutoCommit;
6679 } elsif ( $cust_pkg_ref ) {
6680 ${$cust_pkg_ref} = $cust_pkg;
6684 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
6685 'pkg_list' => [ $cust_pkg ],
6688 $dbh->rollback if $oldAutoCommit;
6693 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6698 #=item charge_postal_fee
6700 #Applies a one time charge this customer. If there is an error,
6701 #returns the error, returns the cust_pkg charge object or false
6702 #if there was no charge.
6706 # This should be a customer event. For that to work requires that bill
6707 # also be a customer event.
6709 sub charge_postal_fee {
6712 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
6713 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
6715 my $cust_pkg = new FS::cust_pkg ( {
6716 'custnum' => $self->custnum,
6717 'pkgpart' => $pkgpart,
6721 my $error = $cust_pkg->insert;
6722 $error ? $error : $cust_pkg;
6727 Returns all the invoices (see L<FS::cust_bill>) for this customer.
6733 map { $_ } #return $self->num_cust_bill unless wantarray;
6734 sort { $a->_date <=> $b->_date }
6735 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6738 =item open_cust_bill
6740 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
6745 sub open_cust_bill {
6749 'table' => 'cust_bill',
6750 'hashref' => { 'custnum' => $self->custnum, },
6751 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
6752 'order_by' => 'ORDER BY _date ASC',
6757 =item cust_statements
6759 Returns all the statements (see L<FS::cust_statement>) for this customer.
6763 sub cust_statement {
6765 map { $_ } #return $self->num_cust_statement unless wantarray;
6766 sort { $a->_date <=> $b->_date }
6767 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
6772 Returns all the credits (see L<FS::cust_credit>) for this customer.
6778 map { $_ } #return $self->num_cust_credit unless wantarray;
6779 sort { $a->_date <=> $b->_date }
6780 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
6783 =item cust_credit_pkgnum
6785 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
6786 package when using experimental package balances.
6790 sub cust_credit_pkgnum {
6791 my( $self, $pkgnum ) = @_;
6792 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
6793 sort { $a->_date <=> $b->_date }
6794 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
6795 'pkgnum' => $pkgnum,
6802 Returns all the payments (see L<FS::cust_pay>) for this customer.
6808 return $self->num_cust_pay unless wantarray;
6809 sort { $a->_date <=> $b->_date }
6810 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
6815 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
6816 called automatically when the cust_pay method is used in a scalar context.
6822 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
6823 my $sth = dbh->prepare($sql) or die dbh->errstr;
6824 $sth->execute($self->custnum) or die $sth->errstr;
6825 $sth->fetchrow_arrayref->[0];
6828 =item cust_pay_pkgnum
6830 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
6831 package when using experimental package balances.
6835 sub cust_pay_pkgnum {
6836 my( $self, $pkgnum ) = @_;
6837 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
6838 sort { $a->_date <=> $b->_date }
6839 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
6840 'pkgnum' => $pkgnum,
6847 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
6853 map { $_ } #return $self->num_cust_pay_void unless wantarray;
6854 sort { $a->_date <=> $b->_date }
6855 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
6858 =item cust_pay_batch
6860 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
6864 sub cust_pay_batch {
6866 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
6867 sort { $a->paybatchnum <=> $b->paybatchnum }
6868 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
6871 =item cust_pay_pending
6873 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
6874 (without status "done").
6878 sub cust_pay_pending {
6880 return $self->num_cust_pay_pending unless wantarray;
6881 sort { $a->_date <=> $b->_date }
6882 qsearch( 'cust_pay_pending', {
6883 'custnum' => $self->custnum,
6884 'status' => { op=>'!=', value=>'done' },
6889 =item num_cust_pay_pending
6891 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
6892 customer (without status "done"). Also called automatically when the
6893 cust_pay_pending method is used in a scalar context.
6897 sub num_cust_pay_pending {
6899 my $sql = " SELECT COUNT(*) FROM cust_pay_pending ".
6900 " WHERE custnum = ? AND status != 'done' ";
6901 my $sth = dbh->prepare($sql) or die dbh->errstr;
6902 $sth->execute($self->custnum) or die $sth->errstr;
6903 $sth->fetchrow_arrayref->[0];
6908 Returns all the refunds (see L<FS::cust_refund>) for this customer.
6914 map { $_ } #return $self->num_cust_refund unless wantarray;
6915 sort { $a->_date <=> $b->_date }
6916 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
6919 =item display_custnum
6921 Returns the displayed customer number for this customer: agent_custid if
6922 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
6926 sub display_custnum {
6928 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
6929 return $self->agent_custid;
6931 return $self->custnum;
6937 Returns a name string for this customer, either "Company (Last, First)" or
6944 my $name = $self->contact;
6945 $name = $self->company. " ($name)" if $self->company;
6951 Returns a name string for this (service/shipping) contact, either
6952 "Company (Last, First)" or "Last, First".
6958 if ( $self->get('ship_last') ) {
6959 my $name = $self->ship_contact;
6960 $name = $self->ship_company. " ($name)" if $self->ship_company;
6969 Returns a name string for this customer, either "Company" or "First Last".
6975 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
6978 =item ship_name_short
6980 Returns a name string for this (service/shipping) contact, either "Company"
6985 sub ship_name_short {
6987 if ( $self->get('ship_last') ) {
6988 $self->ship_company !~ /^\s*$/
6989 ? $self->ship_company
6990 : $self->ship_contact_firstlast;
6992 $self->name_company_or_firstlast;
6998 Returns this customer's full (billing) contact name only, "Last, First"
7004 $self->get('last'). ', '. $self->first;
7009 Returns this customer's full (shipping) contact name only, "Last, First"
7015 $self->get('ship_last')
7016 ? $self->get('ship_last'). ', '. $self->ship_first
7020 =item contact_firstlast
7022 Returns this customers full (billing) contact name only, "First Last".
7026 sub contact_firstlast {
7028 $self->first. ' '. $self->get('last');
7031 =item ship_contact_firstlast
7033 Returns this customer's full (shipping) contact name only, "First Last".
7037 sub ship_contact_firstlast {
7039 $self->get('ship_last')
7040 ? $self->first. ' '. $self->get('ship_last')
7041 : $self->contact_firstlast;
7046 Returns this customer's full country name
7052 code2country($self->country);
7055 =item geocode DATA_VENDOR
7057 Returns a value for the customer location as encoded by DATA_VENDOR.
7058 Currently this only makes sense for "CCH" as DATA_VENDOR.
7063 my ($self, $data_vendor) = (shift, shift); #always cch for now
7065 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
7066 return $geocode if $geocode;
7068 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7072 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7073 if $self->country eq 'US';
7077 #CCH specific location stuff
7078 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7080 my @cust_tax_location =
7082 'table' => 'cust_tax_location',
7083 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7084 'extra_sql' => $extra_sql,
7085 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
7088 $geocode = $cust_tax_location[0]->geocode
7089 if scalar(@cust_tax_location);
7098 Returns a status string for this customer, currently:
7102 =item prospect - No packages have ever been ordered
7104 =item active - One or more recurring packages is active
7106 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7108 =item suspended - All non-cancelled recurring packages are suspended
7110 =item cancelled - All recurring packages are cancelled
7116 sub status { shift->cust_status(@_); }
7120 for my $status (qw( prospect active inactive suspended cancelled )) {
7121 my $method = $status.'_sql';
7122 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7123 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7124 $sth->execute( ($self->custnum) x $numnum )
7125 or die "Error executing 'SELECT $sql': ". $sth->errstr;
7126 return $status if $sth->fetchrow_arrayref->[0];
7130 =item ucfirst_cust_status
7132 =item ucfirst_status
7134 Returns the status with the first character capitalized.
7138 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7140 sub ucfirst_cust_status {
7142 ucfirst($self->cust_status);
7147 Returns a hex triplet color string for this customer's status.
7151 use vars qw(%statuscolor);
7152 tie %statuscolor, 'Tie::IxHash',
7153 'prospect' => '7e0079', #'000000', #black? naw, purple
7154 'active' => '00CC00', #green
7155 'inactive' => '0000CC', #blue
7156 'suspended' => 'FF9900', #yellow
7157 'cancelled' => 'FF0000', #red
7160 sub statuscolor { shift->cust_statuscolor(@_); }
7162 sub cust_statuscolor {
7164 $statuscolor{$self->cust_status};
7169 Returns an array of hashes representing the customer's RT tickets.
7176 my $num = $conf->config('cust_main-max_tickets') || 10;
7179 if ( $conf->config('ticket_system') ) {
7180 unless ( $conf->config('ticket_system-custom_priority_field') ) {
7182 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7186 foreach my $priority (
7187 $conf->config('ticket_system-custom_priority_field-values'), ''
7189 last if scalar(@tickets) >= $num;
7191 @{ FS::TicketSystem->customer_tickets( $self->custnum,
7192 $num - scalar(@tickets),
7202 # Return services representing svc_accts in customer support packages
7203 sub support_services {
7205 my %packages = map { $_ => 1 } $conf->config('support_packages');
7207 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7208 grep { $_->part_svc->svcdb eq 'svc_acct' }
7209 map { $_->cust_svc }
7210 grep { exists $packages{ $_->pkgpart } }
7211 $self->ncancelled_pkgs;
7215 # Return a list of latitude/longitude for one of the services (if any)
7216 sub service_coordinates {
7220 grep { $_->latitude && $_->longitude }
7222 map { $_->cust_svc }
7223 $self->ncancelled_pkgs;
7225 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7230 =head1 CLASS METHODS
7236 Class method that returns the list of possible status strings for customers
7237 (see L<the status method|/status>). For example:
7239 @statuses = FS::cust_main->statuses();
7244 #my $self = shift; #could be class...
7250 Returns an SQL expression identifying prospective cust_main records (customers
7251 with no packages ever ordered)
7255 use vars qw($select_count_pkgs);
7256 $select_count_pkgs =
7257 "SELECT COUNT(*) FROM cust_pkg
7258 WHERE cust_pkg.custnum = cust_main.custnum";
7260 sub select_count_pkgs_sql {
7264 sub prospect_sql { "
7265 0 = ( $select_count_pkgs )
7270 Returns an SQL expression identifying active cust_main records (customers with
7271 active recurring packages).
7276 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
7282 Returns an SQL expression identifying inactive cust_main records (customers with
7283 no active recurring packages, but otherwise unsuspended/uncancelled).
7287 sub inactive_sql { "
7288 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7290 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7296 Returns an SQL expression identifying suspended cust_main records.
7301 sub suspended_sql { susp_sql(@_); }
7303 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
7305 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
7311 Returns an SQL expression identifying cancelled cust_main records.
7315 sub cancelled_sql { cancel_sql(@_); }
7318 my $recurring_sql = FS::cust_pkg->recurring_sql;
7319 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7322 0 < ( $select_count_pkgs )
7323 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
7324 AND 0 = ( $select_count_pkgs AND $recurring_sql
7325 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7327 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7333 =item uncancelled_sql
7335 Returns an SQL expression identifying un-cancelled cust_main records.
7339 sub uncancelled_sql { uncancel_sql(@_); }
7340 sub uncancel_sql { "
7341 ( 0 < ( $select_count_pkgs
7342 AND ( cust_pkg.cancel IS NULL
7343 OR cust_pkg.cancel = 0
7346 OR 0 = ( $select_count_pkgs )
7352 Returns an SQL fragment to retreive the balance.
7357 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7358 WHERE cust_bill.custnum = cust_main.custnum )
7359 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
7360 WHERE cust_pay.custnum = cust_main.custnum )
7361 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
7362 WHERE cust_credit.custnum = cust_main.custnum )
7363 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
7364 WHERE cust_refund.custnum = cust_main.custnum )
7367 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7369 Returns an SQL fragment to retreive the balance for this customer, only
7370 considering invoices with date earlier than START_TIME, and optionally not
7371 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7372 total_unapplied_payments).
7374 Times are specified as SQL fragments or numeric
7375 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7376 L<Date::Parse> for conversion functions. The empty string can be passed
7377 to disable that time constraint completely.
7379 Available options are:
7383 =item unapplied_date
7385 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)
7390 set to true to remove all customer comparison clauses, for totals
7395 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
7400 JOIN clause (typically used with the total option)
7404 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
7405 time will be ignored. Note that START_TIME and END_TIME only limit the date
7406 range for invoices and I<unapplied> payments, credits, and refunds.
7412 sub balance_date_sql {
7413 my( $class, $start, $end, %opt ) = @_;
7415 my $cutoff = $opt{'cutoff'};
7417 my $owed = FS::cust_bill->owed_sql($cutoff);
7418 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
7419 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
7420 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
7422 my $j = $opt{'join'} || '';
7424 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
7425 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
7426 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
7427 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
7429 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
7430 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
7431 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
7432 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
7437 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
7439 Returns an SQL fragment to retreive the total unapplied payments for this
7440 customer, only considering invoices with date earlier than START_TIME, and
7441 optionally not later than END_TIME.
7443 Times are specified as SQL fragments or numeric
7444 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
7445 L<Date::Parse> for conversion functions. The empty string can be passed
7446 to disable that time constraint completely.
7448 Available options are:
7452 sub unapplied_payments_date_sql {
7453 my( $class, $start, $end, ) = @_;
7455 my $unapp_pay = FS::cust_pay->unapplied_sql;
7457 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
7458 'unapplied_date'=>1 );
7460 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
7463 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7465 Helper method for balance_date_sql; name (and usage) subject to change
7466 (suggestions welcome).
7468 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
7469 cust_refund, cust_credit or cust_pay).
7471 If TABLE is "cust_bill" or the unapplied_date option is true, only
7472 considers records with date earlier than START_TIME, and optionally not
7473 later than END_TIME .
7477 sub _money_table_where {
7478 my( $class, $table, $start, $end, %opt ) = @_;
7481 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
7482 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
7483 push @where, "$table._date <= $start" if defined($start) && length($start);
7484 push @where, "$table._date > $end" if defined($end) && length($end);
7486 push @where, @{$opt{'where'}} if $opt{'where'};
7487 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
7493 =item search HASHREF
7497 Returns a qsearch hash expression to search for parameters specified in
7498 HASHREF. Valid parameters are
7506 =item cancelled_pkgs
7512 listref of start date, end date
7522 =item current_balance
7524 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
7528 =item flattened_pkgs
7537 my ($class, $params) = @_;
7548 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
7550 "cust_main.agentnum = $1";
7554 # do the same for user
7557 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
7559 "cust_main.usernum = $1";
7566 #prospect active inactive suspended cancelled
7567 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
7568 my $method = $params->{'status'}. '_sql';
7569 #push @where, $class->$method();
7570 push @where, FS::cust_main->$method();
7574 # parse cancelled package checkbox
7579 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
7580 unless $params->{'cancelled_pkgs'};
7583 # parse without census tract checkbox
7586 push @where, "(censustract = '' or censustract is null)"
7587 if $params->{'no_censustract'};
7593 foreach my $field (qw( signupdate )) {
7595 next unless exists($params->{$field});
7597 my($beginning, $ending, $hour) = @{$params->{$field}};
7600 "cust_main.$field IS NOT NULL",
7601 "cust_main.$field >= $beginning",
7602 "cust_main.$field <= $ending";
7604 # XXX: do this for mysql and/or pull it out of here
7606 if ($dbh->{Driver}->{Name} eq 'Pg') {
7607 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
7610 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
7614 $orderby ||= "ORDER BY cust_main.$field";
7622 if ( $params->{'classnum'} ) {
7624 my @classnum = ref( $params->{'classnum'} )
7625 ? @{ $params->{'classnum'} }
7626 : ( $params->{'classnum'} );
7628 @classnum = grep /^(\d*)$/, @classnum;
7631 push @where, '( '. join(' OR ', map {
7632 $_ ? "cust_main.classnum = $_"
7633 : "cust_main.classnum IS NULL"
7646 if ( $params->{'payby'} ) {
7648 my @payby = ref( $params->{'payby'} )
7649 ? @{ $params->{'payby'} }
7650 : ( $params->{'payby'} );
7652 @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
7654 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
7660 # paydate_year / paydate_month
7663 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
7665 $params->{'paydate_month'} =~ /^(\d\d?)$/
7666 or die "paydate_year without paydate_month?";
7670 'paydate IS NOT NULL',
7672 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
7680 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
7682 if ( $1 eq 'NULL' ) {
7684 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
7687 "cust_main.invoice_terms IS NOT NULL",
7688 "cust_main.invoice_terms = '$1'";
7696 if ( $params->{'current_balance'} ) {
7698 #my $balance_sql = $class->balance_sql();
7699 my $balance_sql = FS::cust_main->balance_sql();
7701 my @current_balance =
7702 ref( $params->{'current_balance'} )
7703 ? @{ $params->{'current_balance'} }
7704 : ( $params->{'current_balance'} );
7706 push @where, map { s/current_balance/$balance_sql/; $_ }
7715 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
7717 "cust_main.custbatch = '$1'";
7721 # setup queries, subs, etc. for the search
7724 $orderby ||= 'ORDER BY custnum';
7726 # here is the agent virtualization
7727 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
7729 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
7731 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
7733 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
7735 my $select = join(', ',
7736 'cust_main.custnum',
7737 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
7740 my(@extra_headers) = ();
7741 my(@extra_fields) = ();
7743 if ($params->{'flattened_pkgs'}) {
7745 if ($dbh->{Driver}->{Name} eq 'Pg') {
7747 $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";
7749 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
7750 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
7751 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
7753 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
7754 "omitting packing information from report.";
7757 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";
7759 my $sth = dbh->prepare($header_query) or die dbh->errstr;
7760 $sth->execute() or die $sth->errstr;
7761 my $headerrow = $sth->fetchrow_arrayref;
7762 my $headercount = $headerrow ? $headerrow->[0] : 0;
7763 while($headercount) {
7764 unshift @extra_headers, "Package ". $headercount;
7765 unshift @extra_fields, eval q!sub {my $c = shift;
7766 my @a = split '\|', $c->magic;
7767 my $p = $a[!.--$headercount. q!];
7775 'table' => 'cust_main',
7776 'select' => $select,
7778 'extra_sql' => $extra_sql,
7779 'order_by' => $orderby,
7780 'count_query' => $count_query,
7781 'extra_headers' => \@extra_headers,
7782 'extra_fields' => \@extra_fields,
7787 =item email_search_result HASHREF
7791 Emails a notice to the specified customers.
7793 Valid parameters are those of the L<search> method, plus the following:
7815 Optional job queue job for status updates.
7819 Returns an error message, or false for success.
7821 If an error occurs during any email, stops the enture send and returns that
7822 error. Presumably if you're getting SMTP errors aborting is better than
7823 retrying everything.
7827 sub email_search_result {
7828 my($class, $params) = @_;
7830 my $from = delete $params->{from};
7831 my $subject = delete $params->{subject};
7832 my $html_body = delete $params->{html_body};
7833 my $text_body = delete $params->{text_body};
7835 my $job = delete $params->{'job'};
7837 $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
7838 unless ref($params->{'payby'});
7840 my $sql_query = $class->search($params);
7842 my $count_query = delete($sql_query->{'count_query'});
7843 my $count_sth = dbh->prepare($count_query)
7844 or die "Error preparing $count_query: ". dbh->errstr;
7846 or die "Error executing $count_query: ". $count_sth->errstr;
7847 my $count_arrayref = $count_sth->fetchrow_arrayref;
7848 my $num_cust = $count_arrayref->[0];
7850 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
7851 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
7854 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
7856 #eventually order+limit magic to reduce memory use?
7857 foreach my $cust_main ( qsearch($sql_query) ) {
7859 my $to = $cust_main->invoicing_list_emailonly_scalar;
7862 my $error = send_email(
7866 'subject' => $subject,
7867 'html_body' => $html_body,
7868 'text_body' => $text_body,
7871 return $error if $error;
7873 if ( $job ) { #progressbar foo
7875 if ( time - $min_sec > $last ) {
7876 my $error = $job->update_statustext(
7877 int( 100 * $num / $num_cust )
7879 die $error if $error;
7889 use Storable qw(thaw);
7892 sub process_email_search_result {
7894 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
7896 my $param = thaw(decode_base64(shift));
7897 warn Dumper($param) if $DEBUG;
7899 $param->{'job'} = $job;
7901 $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
7902 unless ref($param->{'payby'});
7904 my $error = FS::cust_main->email_search_result( $param );
7905 die $error if $error;
7909 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
7911 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
7912 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
7913 specified (the appropriate ship_ field is also searched).
7915 Additional options are the same as FS::Record::qsearch
7920 my( $self, $fuzzy, $hash, @opt) = @_;
7925 check_and_rebuild_fuzzyfiles();
7926 foreach my $field ( keys %$fuzzy ) {
7928 my $all = $self->all_X($field);
7929 next unless scalar(@$all);
7932 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
7935 foreach ( keys %match ) {
7936 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
7937 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
7940 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
7943 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
7945 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
7953 Returns a masked version of the named field
7958 my ($self,$field) = @_;
7962 'x'x(length($self->getfield($field))-4).
7963 substr($self->getfield($field), (length($self->getfield($field))-4));
7973 =item smart_search OPTION => VALUE ...
7975 Accepts the following options: I<search>, the string to search for. The string
7976 will be searched for as a customer number, phone number, name or company name,
7977 as an exact, or, in some cases, a substring or fuzzy match (see the source code
7978 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
7979 skip fuzzy matching when an exact match is found.
7981 Any additional options are treated as an additional qualifier on the search
7984 Returns a (possibly empty) array of FS::cust_main objects.
7991 #here is the agent virtualization
7992 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
7996 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
7997 my $search = delete $options{'search'};
7998 ( my $alphanum_search = $search ) =~ s/\W//g;
8000 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8002 #false laziness w/Record::ut_phone
8003 my $phonen = "$1-$2-$3";
8004 $phonen .= " x$4" if $4;
8006 push @cust_main, qsearch( {
8007 'table' => 'cust_main',
8008 'hashref' => { %options },
8009 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8011 join(' OR ', map "$_ = '$phonen'",
8012 qw( daytime night fax
8013 ship_daytime ship_night ship_fax )
8016 " AND $agentnums_sql", #agent virtualization
8019 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8020 #try looking for matches with extensions unless one was specified
8022 push @cust_main, qsearch( {
8023 'table' => 'cust_main',
8024 'hashref' => { %options },
8025 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8027 join(' OR ', map "$_ LIKE '$phonen\%'",
8029 ship_daytime ship_night )
8032 " AND $agentnums_sql", #agent virtualization
8037 # custnum search (also try agent_custid), with some tweaking options if your
8038 # legacy cust "numbers" have letters
8041 if ( $search =~ /^\s*(\d+)\s*$/
8042 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8043 && $search =~ /^\s*(\w\w?\d+)\s*$/
8045 || ( $conf->exists('address1-search' )
8046 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
8053 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
8054 push @cust_main, qsearch( {
8055 'table' => 'cust_main',
8056 'hashref' => { 'custnum' => $num, %options },
8057 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8061 push @cust_main, qsearch( {
8062 'table' => 'cust_main',
8063 'hashref' => { 'agent_custid' => $num, %options },
8064 'extra_sql' => " AND $agentnums_sql", #agent virtualization
8067 if ( $conf->exists('address1-search') ) {
8068 my $len = length($num);
8070 foreach my $prefix ( '', 'ship_' ) {
8071 push @cust_main, qsearch( {
8072 'table' => 'cust_main',
8073 'hashref' => { %options, },
8075 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8076 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
8077 " AND $agentnums_sql",
8082 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8084 my($company, $last, $first) = ( $1, $2, $3 );
8086 # "Company (Last, First)"
8087 #this is probably something a browser remembered,
8088 #so just do an exact search (but case-insensitive, so USPS standardization
8089 #doesn't throw a wrench in the works)
8091 foreach my $prefix ( '', 'ship_' ) {
8092 push @cust_main, qsearch( {
8093 'table' => 'cust_main',
8094 'hashref' => { %options },
8096 ( keys(%options) ? ' AND ' : ' WHERE ' ).
8098 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
8099 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
8100 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
8106 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8107 # try (ship_){last,company}
8111 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8112 # # full strings the browser remembers won't work
8113 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8115 use Lingua::EN::NameParse;
8116 my $NameParse = new Lingua::EN::NameParse(
8118 allow_reversed => 1,
8121 my($last, $first) = ( '', '' );
8122 #maybe disable this too and just rely on NameParse?
8123 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8125 ($last, $first) = ( $1, $2 );
8127 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
8128 } elsif ( ! $NameParse->parse($value) ) {
8130 my %name = $NameParse->components;
8131 $first = $name{'given_name_1'};
8132 $last = $name{'surname_1'};
8136 if ( $first && $last ) {
8138 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8141 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8143 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8144 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8147 push @cust_main, qsearch( {
8148 'table' => 'cust_main',
8149 'hashref' => \%options,
8150 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8153 # or it just be something that was typed in... (try that in a sec)
8157 my $q_value = dbh->quote($value);
8160 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8161 $sql .= " ( LOWER(last) = $q_value
8162 OR LOWER(company) = $q_value
8163 OR LOWER(ship_last) = $q_value
8164 OR LOWER(ship_company) = $q_value
8166 $sql .= " OR LOWER(address1) = $q_value
8167 OR LOWER(ship_address1) = $q_value
8169 if $conf->exists('address1-search');
8172 push @cust_main, qsearch( {
8173 'table' => 'cust_main',
8174 'hashref' => \%options,
8175 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8178 #no exact match, trying substring/fuzzy
8179 #always do substring & fuzzy (unless they're explicity config'ed off)
8180 #getting complaints searches are not returning enough
8181 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8183 #still some false laziness w/search (was search/cust_main.cgi)
8188 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
8189 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8192 if ( $first && $last ) {
8195 { 'first' => { op=>'ILIKE', value=>"%$first%" },
8196 'last' => { op=>'ILIKE', value=>"%$last%" },
8198 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
8199 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
8206 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
8207 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
8211 if ( $conf->exists('address1-search') ) {
8213 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
8214 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
8218 foreach my $hashref ( @hashrefs ) {
8220 push @cust_main, qsearch( {
8221 'table' => 'cust_main',
8222 'hashref' => { %$hashref,
8225 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8234 " AND $agentnums_sql", #extra_sql #agent virtualization
8237 if ( $first && $last ) {
8238 push @cust_main, FS::cust_main->fuzzy_search(
8239 { 'last' => $last, #fuzzy hashref
8240 'first' => $first }, #
8244 foreach my $field ( 'last', 'company' ) {
8246 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8248 if ( $conf->exists('address1-search') ) {
8250 FS::cust_main->fuzzy_search( { 'address1' => $value }, @fuzopts );
8257 #eliminate duplicates
8259 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8267 Accepts the following options: I<email>, the email address to search for. The
8268 email address will be searched for as an email invoice destination and as an
8271 #Any additional options are treated as an additional qualifier on the search
8272 #(i.e. I<agentnum>).
8274 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8284 my $email = delete $options{'email'};
8286 #we're only being used by RT at the moment... no agent virtualization yet
8287 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8291 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8293 my ( $user, $domain ) = ( $1, $2 );
8295 warn "$me smart_search: searching for $user in domain $domain"
8301 'table' => 'cust_main_invoice',
8302 'hashref' => { 'dest' => $email },
8309 map $_->cust_svc->cust_pkg,
8311 'table' => 'svc_acct',
8312 'hashref' => { 'username' => $user, },
8314 'AND ( SELECT domain FROM svc_domain
8315 WHERE svc_acct.domsvc = svc_domain.svcnum
8316 ) = '. dbh->quote($domain),
8322 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8324 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8331 =item check_and_rebuild_fuzzyfiles
8335 sub check_and_rebuild_fuzzyfiles {
8336 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8337 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8340 =item rebuild_fuzzyfiles
8344 sub rebuild_fuzzyfiles {
8346 use Fcntl qw(:flock);
8348 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8349 mkdir $dir, 0700 unless -d $dir;
8351 foreach my $fuzzy ( @fuzzyfields ) {
8353 open(LOCK,">>$dir/cust_main.$fuzzy")
8354 or die "can't open $dir/cust_main.$fuzzy: $!";
8356 or die "can't lock $dir/cust_main.$fuzzy: $!";
8358 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8359 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8361 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8362 my $sth = dbh->prepare("SELECT $field FROM cust_main".
8363 " WHERE $field != '' AND $field IS NOT NULL");
8364 $sth->execute or die $sth->errstr;
8366 while ( my $row = $sth->fetchrow_arrayref ) {
8367 print CACHE $row->[0]. "\n";
8372 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8374 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8385 my( $self, $field ) = @_;
8386 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8387 open(CACHE,"<$dir/cust_main.$field")
8388 or die "can't open $dir/cust_main.$field: $!";
8389 my @array = map { chomp; $_; } <CACHE>;
8394 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
8398 sub append_fuzzyfiles {
8399 #my( $first, $last, $company ) = @_;
8401 &check_and_rebuild_fuzzyfiles;
8403 use Fcntl qw(:flock);
8405 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8407 foreach my $field (@fuzzyfields) {
8412 open(CACHE,">>$dir/cust_main.$field")
8413 or die "can't open $dir/cust_main.$field: $!";
8414 flock(CACHE,LOCK_EX)
8415 or die "can't lock $dir/cust_main.$field: $!";
8417 print CACHE "$value\n";
8419 flock(CACHE,LOCK_UN)
8420 or die "can't unlock $dir/cust_main.$field: $!";
8435 #warn join('-',keys %$param);
8436 my $fh = $param->{filehandle};
8437 my @fields = @{$param->{fields}};
8439 eval "use Text::CSV_XS;";
8442 my $csv = new Text::CSV_XS;
8449 local $SIG{HUP} = 'IGNORE';
8450 local $SIG{INT} = 'IGNORE';
8451 local $SIG{QUIT} = 'IGNORE';
8452 local $SIG{TERM} = 'IGNORE';
8453 local $SIG{TSTP} = 'IGNORE';
8454 local $SIG{PIPE} = 'IGNORE';
8456 my $oldAutoCommit = $FS::UID::AutoCommit;
8457 local $FS::UID::AutoCommit = 0;
8460 #while ( $columns = $csv->getline($fh) ) {
8462 while ( defined($line=<$fh>) ) {
8464 $csv->parse($line) or do {
8465 $dbh->rollback if $oldAutoCommit;
8466 return "can't parse: ". $csv->error_input();
8469 my @columns = $csv->fields();
8470 #warn join('-',@columns);
8473 foreach my $field ( @fields ) {
8474 $row{$field} = shift @columns;
8477 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
8478 unless ( $cust_main ) {
8479 $dbh->rollback if $oldAutoCommit;
8480 return "unknown custnum $row{'custnum'}";
8483 if ( $row{'amount'} > 0 ) {
8484 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8486 $dbh->rollback if $oldAutoCommit;
8490 } elsif ( $row{'amount'} < 0 ) {
8491 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8494 $dbh->rollback if $oldAutoCommit;
8504 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8506 return "Empty file!" unless $imported;
8512 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8514 Sends a templated email notification to the customer (see L<Text::Template>).
8516 OPTIONS is a hash and may include
8518 I<from> - the email sender (default is invoice_from)
8520 I<to> - comma-separated scalar or arrayref of recipients
8521 (default is invoicing_list)
8523 I<subject> - The subject line of the sent email notification
8524 (default is "Notice from company_name")
8526 I<extra_fields> - a hashref of name/value pairs which will be substituted
8529 The following variables are vavailable in the template.
8531 I<$first> - the customer first name
8532 I<$last> - the customer last name
8533 I<$company> - the customer company
8534 I<$payby> - a description of the method of payment for the customer
8535 # would be nice to use FS::payby::shortname
8536 I<$payinfo> - the account information used to collect for this customer
8537 I<$expdate> - the expiration of the customer payment in seconds from epoch
8542 my ($self, $template, %options) = @_;
8544 return unless $conf->exists($template);
8546 my $from = $conf->config('invoice_from', $self->agentnum)
8547 if $conf->exists('invoice_from', $self->agentnum);
8548 $from = $options{from} if exists($options{from});
8550 my $to = join(',', $self->invoicing_list_emailonly);
8551 $to = $options{to} if exists($options{to});
8553 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
8554 if $conf->exists('company_name', $self->agentnum);
8555 $subject = $options{subject} if exists($options{subject});
8557 my $notify_template = new Text::Template (TYPE => 'ARRAY',
8558 SOURCE => [ map "$_\n",
8559 $conf->config($template)]
8561 or die "can't create new Text::Template object: Text::Template::ERROR";
8562 $notify_template->compile()
8563 or die "can't compile template: Text::Template::ERROR";
8565 $FS::notify_template::_template::company_name =
8566 $conf->config('company_name', $self->agentnum);
8567 $FS::notify_template::_template::company_address =
8568 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
8570 my $paydate = $self->paydate || '2037-12-31';
8571 $FS::notify_template::_template::first = $self->first;
8572 $FS::notify_template::_template::last = $self->last;
8573 $FS::notify_template::_template::company = $self->company;
8574 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
8575 my $payby = $self->payby;
8576 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8577 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8579 #credit cards expire at the end of the month/year of their exp date
8580 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8581 $FS::notify_template::_template::payby = 'credit card';
8582 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8583 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8585 }elsif ($payby eq 'COMP') {
8586 $FS::notify_template::_template::payby = 'complimentary account';
8588 $FS::notify_template::_template::payby = 'current method';
8590 $FS::notify_template::_template::expdate = $expire_time;
8592 for (keys %{$options{extra_fields}}){
8594 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
8597 send_email(from => $from,
8599 subject => $subject,
8600 body => $notify_template->fill_in( PACKAGE =>
8601 'FS::notify_template::_template' ),
8606 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8608 Generates a templated notification to the customer (see L<Text::Template>).
8610 OPTIONS is a hash and may include
8612 I<extra_fields> - a hashref of name/value pairs which will be substituted
8613 into the template. These values may override values mentioned below
8614 and those from the customer record.
8616 The following variables are available in the template instead of or in addition
8617 to the fields of the customer record.
8619 I<$payby> - a description of the method of payment for the customer
8620 # would be nice to use FS::payby::shortname
8621 I<$payinfo> - the masked account information used to collect for this customer
8622 I<$expdate> - the expiration of the customer payment method in seconds from epoch
8623 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
8627 sub generate_letter {
8628 my ($self, $template, %options) = @_;
8630 return unless $conf->exists($template);
8632 my $letter_template = new Text::Template
8634 SOURCE => [ map "$_\n", $conf->config($template)],
8635 DELIMITERS => [ '[@--', '--@]' ],
8637 or die "can't create new Text::Template object: Text::Template::ERROR";
8639 $letter_template->compile()
8640 or die "can't compile template: Text::Template::ERROR";
8642 my %letter_data = map { $_ => $self->$_ } $self->fields;
8643 $letter_data{payinfo} = $self->mask_payinfo;
8645 #my $paydate = $self->paydate || '2037-12-31';
8646 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
8648 my $payby = $self->payby;
8649 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
8650 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
8652 #credit cards expire at the end of the month/year of their exp date
8653 if ($payby eq 'CARD' || $payby eq 'DCRD') {
8654 $letter_data{payby} = 'credit card';
8655 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
8656 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
8658 }elsif ($payby eq 'COMP') {
8659 $letter_data{payby} = 'complimentary account';
8661 $letter_data{payby} = 'current method';
8663 $letter_data{expdate} = $expire_time;
8665 for (keys %{$options{extra_fields}}){
8666 $letter_data{$_} = $options{extra_fields}->{$_};
8669 unless(exists($letter_data{returnaddress})){
8670 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
8671 $self->agent_template)
8673 if ( length($retadd) ) {
8674 $letter_data{returnaddress} = $retadd;
8675 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
8676 $letter_data{returnaddress} =
8677 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
8678 $conf->config('company_address', $self->agentnum)
8681 $letter_data{returnaddress} = '~';
8685 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
8687 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
8689 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
8690 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
8694 ) or die "can't open temp file: $!\n";
8696 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
8698 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
8702 =item print_ps TEMPLATE
8704 Returns an postscript letter filled in from TEMPLATE, as a scalar.
8710 my $file = $self->generate_letter(@_);
8711 FS::Misc::generate_ps($file);
8714 =item print TEMPLATE
8716 Prints the filled in template.
8718 TEMPLATE is the name of a L<Text::Template> to fill in and print.
8722 sub queueable_print {
8725 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
8726 or die "invalid customer number: " . $opt{custvnum};
8728 my $error = $self->print( $opt{template} );
8729 die $error if $error;
8733 my ($self, $template) = (shift, shift);
8734 do_print [ $self->print_ps($template) ];
8737 #these three subs should just go away once agent stuff is all config overrides
8739 sub agent_template {
8741 $self->_agent_plandata('agent_templatename');
8744 sub agent_invoice_from {
8746 $self->_agent_plandata('agent_invoice_from');
8749 sub _agent_plandata {
8750 my( $self, $option ) = @_;
8752 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
8753 #agent-specific Conf
8755 use FS::part_event::Condition;
8757 my $agentnum = $self->agentnum;
8759 my $regexp = regexp_sql();
8761 my $part_event_option =
8763 'select' => 'part_event_option.*',
8764 'table' => 'part_event_option',
8766 LEFT JOIN part_event USING ( eventpart )
8767 LEFT JOIN part_event_option AS peo_agentnum
8768 ON ( part_event.eventpart = peo_agentnum.eventpart
8769 AND peo_agentnum.optionname = 'agentnum'
8770 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
8772 LEFT JOIN part_event_condition
8773 ON ( part_event.eventpart = part_event_condition.eventpart
8774 AND part_event_condition.conditionname = 'cust_bill_age'
8776 LEFT JOIN part_event_condition_option
8777 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
8778 AND part_event_condition_option.optionname = 'age'
8781 #'hashref' => { 'optionname' => $option },
8782 #'hashref' => { 'part_event_option.optionname' => $option },
8784 " WHERE part_event_option.optionname = ". dbh->quote($option).
8785 " AND action = 'cust_bill_send_agent' ".
8786 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
8787 " AND peo_agentnum.optionname = 'agentnum' ".
8788 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
8790 CASE WHEN part_event_condition_option.optionname IS NULL
8792 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
8794 , part_event.weight".
8798 unless ( $part_event_option ) {
8799 return $self->agent->invoice_template || ''
8800 if $option eq 'agent_templatename';
8804 $part_event_option->optionvalue;
8809 ## actual sub, not a method, designed to be called from the queue.
8810 ## sets up the customer, and calls the bill_and_collect
8811 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
8812 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
8813 $cust_main->bill_and_collect(
8818 sub _upgrade_data { #class method
8819 my ($class, %opts) = @_;
8821 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
8822 my $sth = dbh->prepare($sql) or die dbh->errstr;
8823 $sth->execute or die $sth->errstr;
8825 local($ignore_expired_card) = 1;
8826 $class->_upgrade_otaker(%opts);
8836 The delete method should possibly take an FS::cust_main object reference
8837 instead of a scalar customer number.
8839 Bill and collect options should probably be passed as references instead of a
8842 There should probably be a configuration file with a list of allowed credit
8845 No multiple currency support (probably a larger project than just this module).
8847 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
8849 Birthdates rely on negative epoch values.
8851 The payby for card/check batches is broken. With mixed batching, bad
8854 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
8858 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
8859 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
8860 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.