5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 use Scalar::Util qw( blessed );
12 use Time::Local qw(timelocal timelocal_nocheck);
15 use Digest::MD5 qw(md5_base64);
18 use File::Temp qw( tempfile );
19 use String::Approx qw(amatch);
20 use Business::CreditCard 0.28;
22 use FS::UID qw( getotaker dbh driver_name );
23 use FS::Record qw( qsearchs qsearch dbdef );
24 use FS::Misc qw( generate_email send_email generate_ps do_print );
25 use FS::Msgcat qw(gettext);
29 use FS::cust_bill_pkg;
30 use FS::cust_bill_pkg_display;
32 use FS::cust_pay_pending;
33 use FS::cust_pay_void;
34 use FS::cust_pay_batch;
37 use FS::part_referral;
38 use FS::cust_main_county;
39 use FS::cust_location;
41 use FS::cust_tax_location;
42 use FS::part_pkg_taxrate;
44 use FS::cust_main_invoice;
45 use FS::cust_credit_bill;
46 use FS::cust_bill_pay;
47 use FS::prepay_credit;
51 use FS::part_event_condition;
54 use FS::payment_gateway;
55 use FS::agent_payment_gateway;
57 use FS::payinfo_Mixin;
60 @ISA = qw( FS::payinfo_Mixin FS::Record );
62 @EXPORT_OK = qw( smart_search );
64 $realtime_bop_decline_quiet = 0;
66 # 1 is mostly method/subroutine entry and options
67 # 2 traces progress of some operations
68 # 3 is even more information including possibly sensitive data
70 $me = '[FS::cust_main]';
74 $ignore_expired_card = 0;
76 @encrypted_fields = ('payinfo', 'paycvv');
77 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
79 #ask FS::UID to run this stuff for us later
80 #$FS::UID::callback{'FS::cust_main'} = sub {
81 install_callback FS::UID sub {
83 #yes, need it for stuff below (prolly should be cached)
88 my ( $hashref, $cache ) = @_;
89 if ( exists $hashref->{'pkgnum'} ) {
90 #@{ $self->{'_pkgnum'} } = ();
91 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
92 $self->{'_pkgnum'} = $subcache;
93 #push @{ $self->{'_pkgnum'} },
94 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
100 FS::cust_main - Object methods for cust_main records
106 $record = new FS::cust_main \%hash;
107 $record = new FS::cust_main { 'column' => 'value' };
109 $error = $record->insert;
111 $error = $new_record->replace($old_record);
113 $error = $record->delete;
115 $error = $record->check;
117 @cust_pkg = $record->all_pkgs;
119 @cust_pkg = $record->ncancelled_pkgs;
121 @cust_pkg = $record->suspended_pkgs;
123 $error = $record->bill;
124 $error = $record->bill %options;
125 $error = $record->bill 'time' => $time;
127 $error = $record->collect;
128 $error = $record->collect %options;
129 $error = $record->collect 'invoice_time' => $time,
134 An FS::cust_main object represents a customer. FS::cust_main inherits from
135 FS::Record. The following fields are currently supported:
141 Primary key (assigned automatically for new customers)
145 Agent (see L<FS::agent>)
149 Advertising source (see L<FS::part_referral>)
161 Cocial security number (optional)
177 (optional, see L<FS::cust_main_county>)
181 (see L<FS::cust_main_county>)
187 (see L<FS::cust_main_county>)
223 (optional, see L<FS::cust_main_county>)
227 (see L<FS::cust_main_county>)
233 (see L<FS::cust_main_county>)
249 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
253 Payment Information (See L<FS::payinfo_Mixin> for data format)
257 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
261 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
265 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
269 Start date month (maestro/solo cards only)
273 Start date year (maestro/solo cards only)
277 Issue number (maestro/solo cards only)
281 Name on card or billing name
285 IP address from which payment information was received
289 Tax exempt, empty or `Y'
293 Order taker (assigned automatically, see L<FS::UID>)
299 =item referral_custnum
301 Referring customer number
305 Enable individual CDR spooling, empty or `Y'
309 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
313 Discourage individual CDR printing, empty or `Y'
323 Creates a new customer. To add the customer to the database, see L<"insert">.
325 Note that this stores the hash reference, not a distinct copy of the hash it
326 points to. You can ask the object for a copy with the I<hash> method.
330 sub table { 'cust_main'; }
332 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
334 Adds this customer to the database. If there is an error, returns the error,
335 otherwise returns false.
337 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
338 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
339 are inserted atomicly, or the transaction is rolled back. Passing an empty
340 hash reference is equivalent to not supplying this parameter. There should be
341 a better explanation of this, but until then, here's an example:
344 tie %hash, 'Tie::RefHash'; #this part is important
346 $cust_pkg => [ $svc_acct ],
349 $cust_main->insert( \%hash );
351 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
352 be set as the invoicing list (see L<"invoicing_list">). Errors return as
353 expected and rollback the entire transaction; it is not necessary to call
354 check_invoicing_list first. The invoicing_list is set after the records in the
355 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
356 invoicing_list destination to the newly-created svc_acct. Here's an example:
358 $cust_main->insert( {}, [ $email, 'POST' ] );
360 Currently available options are: I<depend_jobnum> and I<noexport>.
362 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
363 on the supplied jobnum (they will not run until the specific job completes).
364 This can be used to defer provisioning until some action completes (such
365 as running the customer's credit card successfully).
367 The I<noexport> option is deprecated. If I<noexport> is set true, no
368 provisioning jobs (exports) are scheduled. (You can schedule them later with
369 the B<reexport> method.)
375 my $cust_pkgs = @_ ? shift : {};
376 my $invoicing_list = @_ ? shift : '';
378 warn "$me insert called with options ".
379 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
382 local $SIG{HUP} = 'IGNORE';
383 local $SIG{INT} = 'IGNORE';
384 local $SIG{QUIT} = 'IGNORE';
385 local $SIG{TERM} = 'IGNORE';
386 local $SIG{TSTP} = 'IGNORE';
387 local $SIG{PIPE} = 'IGNORE';
389 my $oldAutoCommit = $FS::UID::AutoCommit;
390 local $FS::UID::AutoCommit = 0;
393 my $prepay_identifier = '';
394 my( $amount, $seconds ) = ( 0, 0 );
396 if ( $self->payby eq 'PREPAY' ) {
398 $self->payby('BILL');
399 $prepay_identifier = $self->payinfo;
402 warn " looking up prepaid card $prepay_identifier\n"
405 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
407 $dbh->rollback if $oldAutoCommit;
408 #return "error applying prepaid card (transaction rolled back): $error";
412 $payby = 'PREP' if $amount;
414 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
417 $self->payby('BILL');
418 $amount = $self->paid;
422 warn " inserting $self\n"
425 $self->signupdate(time) unless $self->signupdate;
427 $self->auto_agent_custid()
428 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
430 my $error = $self->SUPER::insert;
432 $dbh->rollback if $oldAutoCommit;
433 #return "inserting cust_main record (transaction rolled back): $error";
437 warn " setting invoicing list\n"
440 if ( $invoicing_list ) {
441 $error = $self->check_invoicing_list( $invoicing_list );
443 $dbh->rollback if $oldAutoCommit;
444 #return "checking invoicing_list (transaction rolled back): $error";
447 $self->invoicing_list( $invoicing_list );
450 if ( $conf->config('cust_main-skeleton_tables')
451 && $conf->config('cust_main-skeleton_custnum') ) {
453 warn " inserting skeleton records\n"
456 my $error = $self->start_copy_skel;
458 $dbh->rollback if $oldAutoCommit;
464 warn " ordering packages\n"
467 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
469 $dbh->rollback if $oldAutoCommit;
474 $dbh->rollback if $oldAutoCommit;
475 return "No svc_acct record to apply pre-paid time";
479 warn " inserting initial $payby payment of $amount\n"
481 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
483 $dbh->rollback if $oldAutoCommit;
484 return "inserting payment (transaction rolled back): $error";
488 unless ( $import || $skip_fuzzyfiles ) {
489 warn " queueing fuzzyfiles update\n"
491 $error = $self->queue_fuzzyfiles_update;
493 $dbh->rollback if $oldAutoCommit;
494 return "updating fuzzy search cache: $error";
498 warn " insert complete; committing transaction\n"
501 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
506 use File::CounterFile;
507 sub auto_agent_custid {
510 my $format = $conf->config('cust_main-auto_agent_custid');
512 if ( $format eq '1YMMXXXXXXXX' ) {
514 my $counter = new File::CounterFile 'cust_main.agent_custid';
517 my $ym = 100000000000 + time2str('%y%m00000000', time);
518 if ( $ym > $counter->value ) {
519 $counter->{'value'} = $agent_custid = $ym;
520 $counter->{'updated'} = 1;
522 $agent_custid = $counter->inc;
528 die "Unknown cust_main-auto_agent_custid format: $format";
531 $self->agent_custid($agent_custid);
535 sub start_copy_skel {
538 #'mg_user_preference' => {},
539 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
540 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
541 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
542 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
543 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
546 _copy_skel( 'cust_main', #tablename
547 $conf->config('cust_main-skeleton_custnum'), #sourceid
548 $self->custnum, #destid
549 @tables, #child tables
553 #recursive subroutine, not a method
555 my( $table, $sourceid, $destid, %child_tables ) = @_;
558 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
559 ( $table, $primary_key ) = ( $1, $2 );
561 my $dbdef_table = dbdef->table($table);
562 $primary_key = $dbdef_table->primary_key
563 or return "$table has no primary key".
564 " (or do you need to run dbdef-create?)";
567 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
568 join (', ', keys %child_tables). "\n"
571 foreach my $child_table_def ( keys %child_tables ) {
575 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
576 ( $child_table, $child_pkey ) = ( $1, $2 );
578 $child_table = $child_table_def;
580 $child_pkey = dbdef->table($child_table)->primary_key;
581 # or return "$table has no primary key".
582 # " (or do you need to run dbdef-create?)\n";
586 if ( keys %{ $child_tables{$child_table_def} } ) {
588 return "$child_table has no primary key".
589 " (run dbdef-create or try specifying it?)\n"
592 #false laziness w/Record::insert and only works on Pg
593 #refactor the proper last-inserted-id stuff out of Record::insert if this
594 # ever gets use for anything besides a quick kludge for one customer
595 my $default = dbdef->table($child_table)->column($child_pkey)->default;
596 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
597 or return "can't parse $child_table.$child_pkey default value ".
598 " for sequence name: $default";
603 my @sel_columns = grep { $_ ne $primary_key }
604 dbdef->table($child_table)->columns;
605 my $sel_columns = join(', ', @sel_columns );
607 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
608 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
609 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
611 my $sel_st = "SELECT $sel_columns FROM $child_table".
612 " WHERE $primary_key = $sourceid";
615 my $sel_sth = dbh->prepare( $sel_st )
616 or return dbh->errstr;
618 $sel_sth->execute or return $sel_sth->errstr;
620 while ( my $row = $sel_sth->fetchrow_hashref ) {
622 warn " selected row: ".
623 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
627 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
628 my $ins_sth =dbh->prepare($statement)
629 or return dbh->errstr;
630 my @param = ( $destid, map $row->{$_}, @ins_columns );
631 warn " $statement: [ ". join(', ', @param). " ]\n"
633 $ins_sth->execute( @param )
634 or return $ins_sth->errstr;
636 #next unless keys %{ $child_tables{$child_table} };
637 next unless $sequence;
639 #another section of that laziness
640 my $seq_sql = "SELECT currval('$sequence')";
641 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
642 $seq_sth->execute or return $seq_sth->errstr;
643 my $insertid = $seq_sth->fetchrow_arrayref->[0];
645 # don't drink soap! recurse! recurse! okay!
647 _copy_skel( $child_table_def,
648 $row->{$child_pkey}, #sourceid
650 %{ $child_tables{$child_table_def} },
652 return $error if $error;
662 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
664 Like the insert method on an existing record, this method orders a package
665 and included services atomicaly. Pass a Tie::RefHash data structure to this
666 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
667 be a better explanation of this, but until then, here's an example:
670 tie %hash, 'Tie::RefHash'; #this part is important
672 $cust_pkg => [ $svc_acct ],
675 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
677 Services can be new, in which case they are inserted, or existing unaudited
678 services, in which case they are linked to the newly-created package.
680 Currently available options are: I<depend_jobnum> and I<noexport>.
682 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
683 on the supplied jobnum (they will not run until the specific job completes).
684 This can be used to defer provisioning until some action completes (such
685 as running the customer's credit card successfully).
687 The I<noexport> option is deprecated. If I<noexport> is set true, no
688 provisioning jobs (exports) are scheduled. (You can schedule them later with
689 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
690 on the cust_main object is not recommended, as existing services will also be
697 my $cust_pkgs = shift;
700 my %svc_options = ();
701 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
702 if exists $options{'depend_jobnum'};
703 warn "$me order_pkgs called with options ".
704 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
707 local $SIG{HUP} = 'IGNORE';
708 local $SIG{INT} = 'IGNORE';
709 local $SIG{QUIT} = 'IGNORE';
710 local $SIG{TERM} = 'IGNORE';
711 local $SIG{TSTP} = 'IGNORE';
712 local $SIG{PIPE} = 'IGNORE';
714 my $oldAutoCommit = $FS::UID::AutoCommit;
715 local $FS::UID::AutoCommit = 0;
718 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
720 foreach my $cust_pkg ( keys %$cust_pkgs ) {
721 $cust_pkg->custnum( $self->custnum );
722 my $error = $cust_pkg->insert;
724 $dbh->rollback if $oldAutoCommit;
725 return "inserting cust_pkg (transaction rolled back): $error";
727 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
728 if ( $svc_something->svcnum ) {
729 my $old_cust_svc = $svc_something->cust_svc;
730 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
731 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
732 $error = $new_cust_svc->replace($old_cust_svc);
734 $svc_something->pkgnum( $cust_pkg->pkgnum );
735 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
736 $svc_something->seconds( $svc_something->seconds + $$seconds );
739 $error = $svc_something->insert(%svc_options);
742 $dbh->rollback if $oldAutoCommit;
743 #return "inserting svc_ (transaction rolled back): $error";
749 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
753 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
755 Recharges this (existing) customer with the specified prepaid card (see
756 L<FS::prepay_credit>), specified either by I<identifier> or as an
757 FS::prepay_credit object. If there is an error, returns the error, otherwise
760 Optionally, four scalar references can be passed as well. They will have their
761 values filled in with the amount, number of seconds, and number of upload and
762 download bytes applied by this prepaid
767 sub recharge_prepay {
768 my( $self, $prepay_credit, $amountref, $secondsref,
769 $upbytesref, $downbytesref, $totalbytesref ) = @_;
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 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
784 my $error = $self->get_prepay($prepay_credit, \$amount,
785 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
786 || $self->increment_seconds($seconds)
787 || $self->increment_upbytes($upbytes)
788 || $self->increment_downbytes($downbytes)
789 || $self->increment_totalbytes($totalbytes)
790 || $self->insert_cust_pay_prepay( $amount,
792 ? $prepay_credit->identifier
797 $dbh->rollback if $oldAutoCommit;
801 if ( defined($amountref) ) { $$amountref = $amount; }
802 if ( defined($secondsref) ) { $$secondsref = $seconds; }
803 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
804 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
805 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
807 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
812 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
814 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
815 specified either by I<identifier> or as an FS::prepay_credit object.
817 References to I<amount> and I<seconds> scalars should be passed as arguments
818 and will be incremented by the values of the prepaid card.
820 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
821 check or set this customer's I<agentnum>.
823 If there is an error, returns the error, otherwise returns false.
829 my( $self, $prepay_credit, $amountref, $secondsref,
830 $upref, $downref, $totalref) = @_;
832 local $SIG{HUP} = 'IGNORE';
833 local $SIG{INT} = 'IGNORE';
834 local $SIG{QUIT} = 'IGNORE';
835 local $SIG{TERM} = 'IGNORE';
836 local $SIG{TSTP} = 'IGNORE';
837 local $SIG{PIPE} = 'IGNORE';
839 my $oldAutoCommit = $FS::UID::AutoCommit;
840 local $FS::UID::AutoCommit = 0;
843 unless ( ref($prepay_credit) ) {
845 my $identifier = $prepay_credit;
847 $prepay_credit = qsearchs(
849 { 'identifier' => $prepay_credit },
854 unless ( $prepay_credit ) {
855 $dbh->rollback if $oldAutoCommit;
856 return "Invalid prepaid card: ". $identifier;
861 if ( $prepay_credit->agentnum ) {
862 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
863 $dbh->rollback if $oldAutoCommit;
864 return "prepaid card not valid for agent ". $self->agentnum;
866 $self->agentnum($prepay_credit->agentnum);
869 my $error = $prepay_credit->delete;
871 $dbh->rollback if $oldAutoCommit;
872 return "removing prepay_credit (transaction rolled back): $error";
875 $$amountref += $prepay_credit->amount;
876 $$secondsref += $prepay_credit->seconds;
877 $$upref += $prepay_credit->upbytes;
878 $$downref += $prepay_credit->downbytes;
879 $$totalref += $prepay_credit->totalbytes;
881 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
886 =item increment_upbytes SECONDS
888 Updates this customer's single or primary account (see L<FS::svc_acct>) by
889 the specified number of upbytes. If there is an error, returns the error,
890 otherwise returns false.
894 sub increment_upbytes {
895 _increment_column( shift, 'upbytes', @_);
898 =item increment_downbytes SECONDS
900 Updates this customer's single or primary account (see L<FS::svc_acct>) by
901 the specified number of downbytes. If there is an error, returns the error,
902 otherwise returns false.
906 sub increment_downbytes {
907 _increment_column( shift, 'downbytes', @_);
910 =item increment_totalbytes SECONDS
912 Updates this customer's single or primary account (see L<FS::svc_acct>) by
913 the specified number of totalbytes. If there is an error, returns the error,
914 otherwise returns false.
918 sub increment_totalbytes {
919 _increment_column( shift, 'totalbytes', @_);
922 =item increment_seconds SECONDS
924 Updates this customer's single or primary account (see L<FS::svc_acct>) by
925 the specified number of seconds. If there is an error, returns the error,
926 otherwise returns false.
930 sub increment_seconds {
931 _increment_column( shift, 'seconds', @_);
934 =item _increment_column AMOUNT
936 Updates this customer's single or primary account (see L<FS::svc_acct>) by
937 the specified number of seconds or bytes. If there is an error, returns
938 the error, otherwise returns false.
942 sub _increment_column {
943 my( $self, $column, $amount ) = @_;
944 warn "$me increment_column called: $column, $amount\n"
947 return '' unless $amount;
949 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
950 $self->ncancelled_pkgs;
953 return 'No packages with primary or single services found'.
954 ' to apply pre-paid time';
955 } elsif ( scalar(@cust_pkg) > 1 ) {
956 #maybe have a way to specify the package/account?
957 return 'Multiple packages found to apply pre-paid time';
960 my $cust_pkg = $cust_pkg[0];
961 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
965 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
968 return 'No account found to apply pre-paid time';
969 } elsif ( scalar(@cust_svc) > 1 ) {
970 return 'Multiple accounts found to apply pre-paid time';
973 my $svc_acct = $cust_svc[0]->svc_x;
974 warn " found service svcnum ". $svc_acct->pkgnum.
975 ' ('. $svc_acct->email. ")\n"
978 $column = "increment_$column";
979 $svc_acct->$column($amount);
983 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
985 Inserts a prepayment in the specified amount for this customer. An optional
986 second argument can specify the prepayment identifier for tracking purposes.
987 If there is an error, returns the error, otherwise returns false.
991 sub insert_cust_pay_prepay {
992 shift->insert_cust_pay('PREP', @_);
995 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
997 Inserts a cash payment in the specified amount for this customer. An optional
998 second argument can specify the payment identifier for tracking purposes.
999 If there is an error, returns the error, otherwise returns false.
1003 sub insert_cust_pay_cash {
1004 shift->insert_cust_pay('CASH', @_);
1007 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1009 Inserts a Western Union payment in the specified amount for this customer. An
1010 optional second argument can specify the prepayment identifier for tracking
1011 purposes. If there is an error, returns the error, otherwise returns false.
1015 sub insert_cust_pay_west {
1016 shift->insert_cust_pay('WEST', @_);
1019 sub insert_cust_pay {
1020 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1021 my $payinfo = scalar(@_) ? shift : '';
1023 my $cust_pay = new FS::cust_pay {
1024 'custnum' => $self->custnum,
1025 'paid' => sprintf('%.2f', $amount),
1026 #'_date' => #date the prepaid card was purchased???
1028 'payinfo' => $payinfo,
1036 This method is deprecated. See the I<depend_jobnum> option to the insert and
1037 order_pkgs methods for a better way to defer provisioning.
1039 Re-schedules all exports by calling the B<reexport> method of all associated
1040 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1041 otherwise returns false.
1048 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1049 "use the depend_jobnum option to insert or order_pkgs to delay export";
1051 local $SIG{HUP} = 'IGNORE';
1052 local $SIG{INT} = 'IGNORE';
1053 local $SIG{QUIT} = 'IGNORE';
1054 local $SIG{TERM} = 'IGNORE';
1055 local $SIG{TSTP} = 'IGNORE';
1056 local $SIG{PIPE} = 'IGNORE';
1058 my $oldAutoCommit = $FS::UID::AutoCommit;
1059 local $FS::UID::AutoCommit = 0;
1062 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1063 my $error = $cust_pkg->reexport;
1065 $dbh->rollback if $oldAutoCommit;
1070 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1075 =item delete NEW_CUSTNUM
1077 This deletes the customer. If there is an error, returns the error, otherwise
1080 This will completely remove all traces of the customer record. This is not
1081 what you want when a customer cancels service; for that, cancel all of the
1082 customer's packages (see L</cancel>).
1084 If the customer has any uncancelled packages, you need to pass a new (valid)
1085 customer number for those packages to be transferred to. Cancelled packages
1086 will be deleted. Did I mention that this is NOT what you want when a customer
1087 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1089 You can't delete a customer with invoices (see L<FS::cust_bill>),
1090 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1091 refunds (see L<FS::cust_refund>).
1098 local $SIG{HUP} = 'IGNORE';
1099 local $SIG{INT} = 'IGNORE';
1100 local $SIG{QUIT} = 'IGNORE';
1101 local $SIG{TERM} = 'IGNORE';
1102 local $SIG{TSTP} = 'IGNORE';
1103 local $SIG{PIPE} = 'IGNORE';
1105 my $oldAutoCommit = $FS::UID::AutoCommit;
1106 local $FS::UID::AutoCommit = 0;
1109 if ( $self->cust_bill ) {
1110 $dbh->rollback if $oldAutoCommit;
1111 return "Can't delete a customer with invoices";
1113 if ( $self->cust_credit ) {
1114 $dbh->rollback if $oldAutoCommit;
1115 return "Can't delete a customer with credits";
1117 if ( $self->cust_pay ) {
1118 $dbh->rollback if $oldAutoCommit;
1119 return "Can't delete a customer with payments";
1121 if ( $self->cust_refund ) {
1122 $dbh->rollback if $oldAutoCommit;
1123 return "Can't delete a customer with refunds";
1126 my @cust_pkg = $self->ncancelled_pkgs;
1128 my $new_custnum = shift;
1129 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1130 $dbh->rollback if $oldAutoCommit;
1131 return "Invalid new customer number: $new_custnum";
1133 foreach my $cust_pkg ( @cust_pkg ) {
1134 my %hash = $cust_pkg->hash;
1135 $hash{'custnum'} = $new_custnum;
1136 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1137 my $error = $new_cust_pkg->replace($cust_pkg,
1138 options => { $cust_pkg->options },
1141 $dbh->rollback if $oldAutoCommit;
1146 my @cancelled_cust_pkg = $self->all_pkgs;
1147 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1148 my $error = $cust_pkg->delete;
1150 $dbh->rollback if $oldAutoCommit;
1155 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1156 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1158 my $error = $cust_main_invoice->delete;
1160 $dbh->rollback if $oldAutoCommit;
1165 my $error = $self->SUPER::delete;
1167 $dbh->rollback if $oldAutoCommit;
1171 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1176 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ]
1178 Replaces the OLD_RECORD with this one in the database. If there is an error,
1179 returns the error, otherwise returns false.
1181 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1182 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1183 expected and rollback the entire transaction; it is not necessary to call
1184 check_invoicing_list first. Here's an example:
1186 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1193 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1195 : $self->replace_old;
1199 warn "$me replace called\n"
1202 my $curuser = $FS::CurrentUser::CurrentUser;
1203 if ( $self->payby eq 'COMP'
1204 && $self->payby ne $old->payby
1205 && ! $curuser->access_right('Complimentary customer')
1208 return "You are not permitted to create complimentary accounts.";
1211 local($ignore_expired_card) = 1
1212 if $old->payby =~ /^(CARD|DCRD)$/
1213 && $self->payby =~ /^(CARD|DCRD)$/
1214 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1216 local $SIG{HUP} = 'IGNORE';
1217 local $SIG{INT} = 'IGNORE';
1218 local $SIG{QUIT} = 'IGNORE';
1219 local $SIG{TERM} = 'IGNORE';
1220 local $SIG{TSTP} = 'IGNORE';
1221 local $SIG{PIPE} = 'IGNORE';
1223 my $oldAutoCommit = $FS::UID::AutoCommit;
1224 local $FS::UID::AutoCommit = 0;
1227 my $error = $self->SUPER::replace($old);
1230 $dbh->rollback if $oldAutoCommit;
1234 if ( @param ) { # INVOICING_LIST_ARYREF
1235 my $invoicing_list = shift @param;
1236 $error = $self->check_invoicing_list( $invoicing_list );
1238 $dbh->rollback if $oldAutoCommit;
1241 $self->invoicing_list( $invoicing_list );
1244 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1245 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1246 # card/check/lec info has changed, want to retry realtime_ invoice events
1247 my $error = $self->retry_realtime;
1249 $dbh->rollback if $oldAutoCommit;
1254 unless ( $import || $skip_fuzzyfiles ) {
1255 $error = $self->queue_fuzzyfiles_update;
1257 $dbh->rollback if $oldAutoCommit;
1258 return "updating fuzzy search cache: $error";
1262 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1267 =item queue_fuzzyfiles_update
1269 Used by insert & replace to update the fuzzy search cache
1273 sub queue_fuzzyfiles_update {
1276 local $SIG{HUP} = 'IGNORE';
1277 local $SIG{INT} = 'IGNORE';
1278 local $SIG{QUIT} = 'IGNORE';
1279 local $SIG{TERM} = 'IGNORE';
1280 local $SIG{TSTP} = 'IGNORE';
1281 local $SIG{PIPE} = 'IGNORE';
1283 my $oldAutoCommit = $FS::UID::AutoCommit;
1284 local $FS::UID::AutoCommit = 0;
1287 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1288 my $error = $queue->insert( map $self->getfield($_),
1289 qw(first last company)
1292 $dbh->rollback if $oldAutoCommit;
1293 return "queueing job (transaction rolled back): $error";
1296 if ( $self->ship_last ) {
1297 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1298 $error = $queue->insert( map $self->getfield("ship_$_"),
1299 qw(first last company)
1302 $dbh->rollback if $oldAutoCommit;
1303 return "queueing job (transaction rolled back): $error";
1307 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1314 Checks all fields to make sure this is a valid customer record. If there is
1315 an error, returns the error, otherwise returns false. Called by the insert
1316 and replace methods.
1323 warn "$me check BEFORE: \n". $self->_dump
1327 $self->ut_numbern('custnum')
1328 || $self->ut_number('agentnum')
1329 || $self->ut_textn('agent_custid')
1330 || $self->ut_number('refnum')
1331 || $self->ut_textn('custbatch')
1332 || $self->ut_name('last')
1333 || $self->ut_name('first')
1334 || $self->ut_snumbern('birthdate')
1335 || $self->ut_snumbern('signupdate')
1336 || $self->ut_textn('company')
1337 || $self->ut_text('address1')
1338 || $self->ut_textn('address2')
1339 || $self->ut_text('city')
1340 || $self->ut_textn('county')
1341 || $self->ut_textn('state')
1342 || $self->ut_country('country')
1343 || $self->ut_anything('comments')
1344 || $self->ut_numbern('referral_custnum')
1345 || $self->ut_textn('stateid')
1346 || $self->ut_textn('stateid_state')
1347 || $self->ut_textn('invoice_terms')
1348 || $self->ut_alphan('geocode')
1351 #barf. need message catalogs. i18n. etc.
1352 $error .= "Please select an advertising source."
1353 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1354 return $error if $error;
1356 return "Unknown agent"
1357 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1359 return "Unknown refnum"
1360 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1362 return "Unknown referring custnum: ". $self->referral_custnum
1363 unless ! $self->referral_custnum
1364 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1366 if ( $self->ss eq '' ) {
1371 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1372 or return "Illegal social security number: ". $self->ss;
1373 $self->ss("$1-$2-$3");
1377 # bad idea to disable, causes billing to fail because of no tax rates later
1378 # unless ( $import ) {
1379 unless ( qsearch('cust_main_county', {
1380 'country' => $self->country,
1383 return "Unknown state/county/country: ".
1384 $self->state. "/". $self->county. "/". $self->country
1385 unless qsearch('cust_main_county',{
1386 'state' => $self->state,
1387 'county' => $self->county,
1388 'country' => $self->country,
1394 $self->ut_phonen('daytime', $self->country)
1395 || $self->ut_phonen('night', $self->country)
1396 || $self->ut_phonen('fax', $self->country)
1397 || $self->ut_zip('zip', $self->country)
1399 return $error if $error;
1401 if ( $conf->exists('cust_main-require_phone')
1402 && ! length($self->daytime) && ! length($self->night)
1405 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1407 : FS::Msgcat::_gettext('daytime');
1408 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1410 : FS::Msgcat::_gettext('night');
1412 return "$daytime_label or $night_label is required"
1416 if ( $self->has_ship_address
1417 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1418 $self->addr_fields )
1422 $self->ut_name('ship_last')
1423 || $self->ut_name('ship_first')
1424 || $self->ut_textn('ship_company')
1425 || $self->ut_text('ship_address1')
1426 || $self->ut_textn('ship_address2')
1427 || $self->ut_text('ship_city')
1428 || $self->ut_textn('ship_county')
1429 || $self->ut_textn('ship_state')
1430 || $self->ut_country('ship_country')
1432 return $error if $error;
1434 #false laziness with above
1435 unless ( qsearchs('cust_main_county', {
1436 'country' => $self->ship_country,
1439 return "Unknown ship_state/ship_county/ship_country: ".
1440 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1441 unless qsearch('cust_main_county',{
1442 'state' => $self->ship_state,
1443 'county' => $self->ship_county,
1444 'country' => $self->ship_country,
1450 $self->ut_phonen('ship_daytime', $self->ship_country)
1451 || $self->ut_phonen('ship_night', $self->ship_country)
1452 || $self->ut_phonen('ship_fax', $self->ship_country)
1453 || $self->ut_zip('ship_zip', $self->ship_country)
1455 return $error if $error;
1457 return "Unit # is required."
1458 if $self->ship_address2 =~ /^\s*$/
1459 && $conf->exists('cust_main-require_address2');
1461 } else { # ship_ info eq billing info, so don't store dup info in database
1463 $self->setfield("ship_$_", '')
1464 foreach $self->addr_fields;
1466 return "Unit # is required."
1467 if $self->address2 =~ /^\s*$/
1468 && $conf->exists('cust_main-require_address2');
1472 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1473 # or return "Illegal payby: ". $self->payby;
1475 FS::payby->can_payby($self->table, $self->payby)
1476 or return "Illegal payby: ". $self->payby;
1478 $error = $self->ut_numbern('paystart_month')
1479 || $self->ut_numbern('paystart_year')
1480 || $self->ut_numbern('payissue')
1481 || $self->ut_textn('paytype')
1483 return $error if $error;
1485 if ( $self->payip eq '' ) {
1488 $error = $self->ut_ip('payip');
1489 return $error if $error;
1492 # If it is encrypted and the private key is not availaible then we can't
1493 # check the credit card.
1495 my $check_payinfo = 1;
1497 if ($self->is_encrypted($self->payinfo)) {
1501 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1503 my $payinfo = $self->payinfo;
1504 $payinfo =~ s/\D//g;
1505 $payinfo =~ /^(\d{13,16})$/
1506 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1508 $self->payinfo($payinfo);
1510 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1512 return gettext('unknown_card_type')
1513 if cardtype($self->payinfo) eq "Unknown";
1515 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1517 return 'Banned credit card: banned on '.
1518 time2str('%a %h %o at %r', $ban->_date).
1519 ' by '. $ban->otaker.
1520 ' (ban# '. $ban->bannum. ')';
1523 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1524 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1525 $self->paycvv =~ /^(\d{4})$/
1526 or return "CVV2 (CID) for American Express cards is four digits.";
1529 $self->paycvv =~ /^(\d{3})$/
1530 or return "CVV2 (CVC2/CID) is three digits.";
1537 my $cardtype = cardtype($payinfo);
1538 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1540 return "Start date or issue number is required for $cardtype cards"
1541 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1543 return "Start month must be between 1 and 12"
1544 if $self->paystart_month
1545 and $self->paystart_month < 1 || $self->paystart_month > 12;
1547 return "Start year must be 1990 or later"
1548 if $self->paystart_year
1549 and $self->paystart_year < 1990;
1551 return "Issue number must be beween 1 and 99"
1553 and $self->payissue < 1 || $self->payissue > 99;
1556 $self->paystart_month('');
1557 $self->paystart_year('');
1558 $self->payissue('');
1561 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1563 my $payinfo = $self->payinfo;
1564 $payinfo =~ s/[^\d\@]//g;
1565 if ( $conf->exists('echeck-nonus') ) {
1566 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1567 $payinfo = "$1\@$2";
1569 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1570 $payinfo = "$1\@$2";
1572 $self->payinfo($payinfo);
1575 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1577 return 'Banned ACH account: banned on '.
1578 time2str('%a %h %o at %r', $ban->_date).
1579 ' by '. $ban->otaker.
1580 ' (ban# '. $ban->bannum. ')';
1583 } elsif ( $self->payby eq 'LECB' ) {
1585 my $payinfo = $self->payinfo;
1586 $payinfo =~ s/\D//g;
1587 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1589 $self->payinfo($payinfo);
1592 } elsif ( $self->payby eq 'BILL' ) {
1594 $error = $self->ut_textn('payinfo');
1595 return "Illegal P.O. number: ". $self->payinfo if $error;
1598 } elsif ( $self->payby eq 'COMP' ) {
1600 my $curuser = $FS::CurrentUser::CurrentUser;
1601 if ( ! $self->custnum
1602 && ! $curuser->access_right('Complimentary customer')
1605 return "You are not permitted to create complimentary accounts."
1608 $error = $self->ut_textn('payinfo');
1609 return "Illegal comp account issuer: ". $self->payinfo if $error;
1612 } elsif ( $self->payby eq 'PREPAY' ) {
1614 my $payinfo = $self->payinfo;
1615 $payinfo =~ s/\W//g; #anything else would just confuse things
1616 $self->payinfo($payinfo);
1617 $error = $self->ut_alpha('payinfo');
1618 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1619 return "Unknown prepayment identifier"
1620 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1625 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1626 return "Expiration date required"
1627 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1631 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1632 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1633 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1634 ( $m, $y ) = ( $3, "20$2" );
1636 return "Illegal expiration date: ". $self->paydate;
1638 $self->paydate("$y-$m-01");
1639 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1640 return gettext('expired_card')
1642 && !$ignore_expired_card
1643 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1646 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1647 ( ! $conf->exists('require_cardname')
1648 || $self->payby !~ /^(CARD|DCRD)$/ )
1650 $self->payname( $self->first. " ". $self->getfield('last') );
1652 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1653 or return gettext('illegal_name'). " payname: ". $self->payname;
1657 foreach my $flag (qw( tax spool_cdr squelch_cdr )) {
1658 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1662 $self->otaker(getotaker) unless $self->otaker;
1664 warn "$me check AFTER: \n". $self->_dump
1667 $self->SUPER::check;
1672 Returns a list of fields which have ship_ duplicates.
1677 qw( last first company
1678 address1 address2 city county state zip country
1683 =item has_ship_address
1685 Returns true if this customer record has a separate shipping address.
1689 sub has_ship_address {
1691 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1696 Returns all packages (see L<FS::cust_pkg>) for this customer.
1703 return $self->num_pkgs unless wantarray;
1706 if ( $self->{'_pkgnum'} ) {
1707 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1709 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1712 sort sort_packages @cust_pkg;
1717 Synonym for B<all_pkgs>.
1722 shift->all_pkgs(@_);
1727 Returns all locations (see L<FS::cust_location>) for this customer.
1733 qsearch('cust_location', { 'custnum' => $self->custnum } );
1736 =item ncancelled_pkgs
1738 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1742 sub ncancelled_pkgs {
1745 return $self->num_ncancelled_pkgs unless wantarray;
1748 if ( $self->{'_pkgnum'} ) {
1750 warn "$me ncancelled_pkgs: returning cached objects"
1753 @cust_pkg = grep { ! $_->getfield('cancel') }
1754 values %{ $self->{'_pkgnum'}->cache };
1758 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1759 $self->custnum. "\n"
1763 qsearch( 'cust_pkg', {
1764 'custnum' => $self->custnum,
1768 qsearch( 'cust_pkg', {
1769 'custnum' => $self->custnum,
1774 sort sort_packages @cust_pkg;
1778 # This should be generalized to use config options to determine order.
1780 if ( $a->get('cancel') and $b->get('cancel') ) {
1781 $a->pkgnum <=> $b->pkgnum;
1782 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1783 return -1 if $b->get('cancel');
1784 return 1 if $a->get('cancel');
1787 $a->pkgnum <=> $b->pkgnum;
1791 =item suspended_pkgs
1793 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1797 sub suspended_pkgs {
1799 grep { $_->susp } $self->ncancelled_pkgs;
1802 =item unflagged_suspended_pkgs
1804 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1805 customer (thouse packages without the `manual_flag' set).
1809 sub unflagged_suspended_pkgs {
1811 return $self->suspended_pkgs
1812 unless dbdef->table('cust_pkg')->column('manual_flag');
1813 grep { ! $_->manual_flag } $self->suspended_pkgs;
1816 =item unsuspended_pkgs
1818 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1823 sub unsuspended_pkgs {
1825 grep { ! $_->susp } $self->ncancelled_pkgs;
1828 =item num_cancelled_pkgs
1830 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1835 sub num_cancelled_pkgs {
1836 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1839 sub num_ncancelled_pkgs {
1840 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1844 my( $self ) = shift;
1845 my $sql = scalar(@_) ? shift : '';
1846 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1847 my $sth = dbh->prepare(
1848 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1849 ) or die dbh->errstr;
1850 $sth->execute($self->custnum) or die $sth->errstr;
1851 $sth->fetchrow_arrayref->[0];
1856 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1857 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1858 on success or a list of errors.
1864 grep { $_->unsuspend } $self->suspended_pkgs;
1869 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1871 Returns a list: an empty list on success or a list of errors.
1877 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1880 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1882 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1883 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1884 of a list of pkgparts; the hashref has the following keys:
1888 =item pkgparts - listref of pkgparts
1890 =item (other options are passed to the suspend method)
1895 Returns a list: an empty list on success or a list of errors.
1899 sub suspend_if_pkgpart {
1901 my (@pkgparts, %opt);
1902 if (ref($_[0]) eq 'HASH'){
1903 @pkgparts = @{$_[0]{pkgparts}};
1908 grep { $_->suspend(%opt) }
1909 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1910 $self->unsuspended_pkgs;
1913 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1915 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1916 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1917 instead of a list of pkgparts; the hashref has the following keys:
1921 =item pkgparts - listref of pkgparts
1923 =item (other options are passed to the suspend method)
1927 Returns a list: an empty list on success or a list of errors.
1931 sub suspend_unless_pkgpart {
1933 my (@pkgparts, %opt);
1934 if (ref($_[0]) eq 'HASH'){
1935 @pkgparts = @{$_[0]{pkgparts}};
1940 grep { $_->suspend(%opt) }
1941 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1942 $self->unsuspended_pkgs;
1945 =item cancel [ OPTION => VALUE ... ]
1947 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1949 Available options are:
1953 =item quiet - can be set true to supress email cancellation notices.
1955 =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.
1957 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1961 Always returns a list: an empty list on success or a list of errors.
1966 my( $self, %opt ) = @_;
1968 warn "$me cancel called on customer ". $self->custnum. " with options ".
1969 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1972 return ( 'access denied' )
1973 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1975 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1977 #should try decryption (we might have the private key)
1978 # and if not maybe queue a job for the server that does?
1979 return ( "Can't (yet) ban encrypted credit cards" )
1980 if $self->is_encrypted($self->payinfo);
1982 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1983 my $error = $ban->insert;
1984 return ( $error ) if $error;
1988 my @pkgs = $self->ncancelled_pkgs;
1990 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1991 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1994 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1997 sub _banned_pay_hashref {
2008 'payby' => $payby2ban{$self->payby},
2009 'payinfo' => md5_base64($self->payinfo),
2010 #don't ever *search* on reason! #'reason' =>
2016 Returns all notes (see L<FS::cust_main_note>) for this customer.
2023 qsearch( 'cust_main_note',
2024 { 'custnum' => $self->custnum },
2026 'ORDER BY _DATE DESC'
2032 Returns the agent (see L<FS::agent>) for this customer.
2038 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2041 =item bill_and_collect
2043 Cancels and suspends any packages due, generates bills, applies payments and
2046 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
2048 Options are passed as name-value pairs. Currently available options are:
2054 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:
2058 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2062 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.
2066 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2070 If set true, re-charges setup fees.
2074 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)
2080 sub bill_and_collect {
2081 my( $self, %options ) = @_;
2087 #$options{actual_time} not $options{time} because freeside-daily -d is for
2088 #pre-printing invoices
2089 my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
2090 $self->ncancelled_pkgs;
2092 foreach my $cust_pkg ( @cancel_pkgs ) {
2093 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2094 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2095 'reason_otaker' => $cpr->otaker
2099 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
2100 " for custnum ". $self->custnum. ": $error"
2108 #$options{actual_time} not $options{time} because freeside-daily -d is for
2109 #pre-printing invoices
2112 && ( ( $_->part_pkg->is_prepaid
2114 && $_->bill < $options{actual_time}
2117 && $_->adjourn <= $options{actual_time}
2121 $self->ncancelled_pkgs;
2123 foreach my $cust_pkg ( @susp_pkgs ) {
2124 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2125 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2126 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2127 'reason_otaker' => $cpr->otaker
2132 warn "Error suspending package ". $cust_pkg->pkgnum.
2133 " for custnum ". $self->custnum. ": $error"
2141 my $error = $self->bill( %options );
2142 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
2144 $self->apply_payments_and_credits;
2146 $error = $self->collect( %options );
2147 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2153 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2154 conjunction with the collect method by calling B<bill_and_collect>.
2156 If there is an error, returns the error, otherwise returns false.
2158 Options are passed as name-value pairs. Currently available options are:
2164 If set true, re-charges setup fees.
2168 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:
2172 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2176 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2178 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2182 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.
2189 my( $self, %options ) = @_;
2190 return '' if $self->payby eq 'COMP';
2191 warn "$me bill customer ". $self->custnum. "\n"
2194 my $time = $options{'time'} || time;
2195 my $invoice_time = $options{'invoice_time'} || $time;
2198 local $SIG{HUP} = 'IGNORE';
2199 local $SIG{INT} = 'IGNORE';
2200 local $SIG{QUIT} = 'IGNORE';
2201 local $SIG{TERM} = 'IGNORE';
2202 local $SIG{TSTP} = 'IGNORE';
2203 local $SIG{PIPE} = 'IGNORE';
2205 my $oldAutoCommit = $FS::UID::AutoCommit;
2206 local $FS::UID::AutoCommit = 0;
2209 $self->select_for_update; #mutex
2211 my @cust_bill_pkg = ();
2214 # find the packages which are due for billing, find out how much they are
2215 # & generate invoice database.
2218 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2222 my @precommit_hooks = ();
2224 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2225 foreach my $cust_pkg (@cust_pkgs) {
2227 #NO!! next if $cust_pkg->cancel;
2228 next if $cust_pkg->getfield('cancel');
2230 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2232 #? to avoid use of uninitialized value errors... ?
2233 $cust_pkg->setfield('bill', '')
2234 unless defined($cust_pkg->bill);
2236 #my $part_pkg = $cust_pkg->part_pkg;
2238 my $real_pkgpart = $cust_pkg->pkgpart;
2239 my %hash = $cust_pkg->hash;
2241 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2243 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2246 $self->_make_lines( 'part_pkg' => $part_pkg,
2247 'cust_pkg' => $cust_pkg,
2248 'precommit_hooks' => \@precommit_hooks,
2249 'line_items' => \@cust_bill_pkg,
2250 'setup' => \$total_setup,
2251 'recur' => \$total_recur,
2252 'tax_matrix' => \%taxlisthash,
2254 'options' => \%options,
2257 $dbh->rollback if $oldAutoCommit;
2261 } #foreach my $part_pkg
2263 } #foreach my $cust_pkg
2265 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2266 #but do commit any package date cycling that happened
2267 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2271 my $postal_pkg = $self->charge_postal_fee();
2272 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2273 $dbh->rollback if $oldAutoCommit;
2274 return "can't charge postal invoice fee for customer ".
2275 $self->custnum. ": $postal_pkg";
2278 ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2279 !$conf->exists('postal_invoice-recurring_only')
2283 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2285 $self->_make_lines( 'part_pkg' => $part_pkg,
2286 'cust_pkg' => $postal_pkg,
2287 'precommit_hooks' => \@precommit_hooks,
2288 'line_items' => \@cust_bill_pkg,
2289 'setup' => \$total_setup,
2290 'recur' => \$total_recur,
2291 'tax_matrix' => \%taxlisthash,
2293 'options' => \%options,
2296 $dbh->rollback if $oldAutoCommit;
2302 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2303 foreach my $tax ( keys %taxlisthash ) {
2304 my $tax_object = shift @{ $taxlisthash{$tax} };
2305 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2306 my $listref_or_error =
2307 $tax_object->taxline( $taxlisthash{$tax},
2308 'custnum' => $self->custnum,
2309 'invoice_time' => $invoice_time
2311 unless (ref($listref_or_error)) {
2312 $dbh->rollback if $oldAutoCommit;
2313 return $listref_or_error;
2315 unshift @{ $taxlisthash{$tax} }, $tax_object;
2317 warn "adding ". $listref_or_error->[1].
2318 " as ". $listref_or_error->[0]. "\n"
2320 $tax{ $tax } += $listref_or_error->[1];
2321 if ( $taxname{ $listref_or_error->[0] } ) {
2322 push @{ $taxname{ $listref_or_error->[0] } }, $tax;
2324 $taxname{ $listref_or_error->[0] } = [ $tax ];
2329 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
2330 my %packagemap = map { $_->pkgnum => $_ } @cust_bill_pkg;
2331 foreach my $tax ( keys %taxlisthash ) {
2332 foreach ( @{ $taxlisthash{$tax} }[1 ... scalar(@{ $taxlisthash{$tax} })] ) {
2333 next unless ref($_) eq 'FS::cust_bill_pkg'; # shouldn't happen
2335 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
2336 splice( @{ $_->_cust_tax_exempt_pkg } );
2340 #some taxes are taxed
2343 warn "finding taxed taxes...\n" if $DEBUG > 2;
2344 foreach my $tax ( keys %taxlisthash ) {
2345 my $tax_object = shift @{ $taxlisthash{$tax} };
2346 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2348 next unless $tax_object->can('tax_on_tax');
2350 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2351 my $totname = ref( $tot ). ' '. $tot->taxnum;
2353 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2355 next unless exists( $taxlisthash{ $totname } ); # only increase
2357 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2358 if ( exists( $totlisthash{ $totname } ) ) {
2359 push @{ $totlisthash{ $totname } }, $tax{ $tax };
2361 $totlisthash{ $totname } = [ $tot, $tax{ $tax } ];
2366 warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2367 foreach my $tax ( keys %totlisthash ) {
2368 my $tax_object = shift @{ $totlisthash{$tax} };
2369 warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2371 my $listref_or_error =
2372 $tax_object->taxline( $totlisthash{$tax},
2373 'custnum' => $self->custnum,
2374 'invoice_time' => $invoice_time
2376 unless (ref($listref_or_error)) {
2377 $dbh->rollback if $oldAutoCommit;
2378 return $listref_or_error;
2381 warn "adding taxed tax amount ". $listref_or_error->[1].
2382 " as ". $tax_object->taxname. "\n"
2384 $tax{ $tax } += $listref_or_error->[1];
2387 #consolidate and create tax line items
2388 warn "consolidating and generating...\n" if $DEBUG > 2;
2389 foreach my $taxname ( keys %taxname ) {
2392 warn "adding $taxname\n" if $DEBUG > 1;
2393 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2394 $tax += $tax{$taxitem} unless $seen{$taxitem};
2395 $seen{$taxitem} = 1;
2396 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2400 $tax = sprintf('%.2f', $tax );
2401 $total_setup = sprintf('%.2f', $total_setup+$tax );
2403 push @cust_bill_pkg, new FS::cust_bill_pkg {
2409 'itemdesc' => $taxname,
2414 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2416 #create the new invoice
2417 my $cust_bill = new FS::cust_bill ( {
2418 'custnum' => $self->custnum,
2419 '_date' => ( $invoice_time ),
2420 'charged' => $charged,
2422 my $error = $cust_bill->insert;
2424 $dbh->rollback if $oldAutoCommit;
2425 return "can't create invoice for customer #". $self->custnum. ": $error";
2428 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2429 $cust_bill_pkg->invnum($cust_bill->invnum);
2430 my $error = $cust_bill_pkg->insert;
2432 $dbh->rollback if $oldAutoCommit;
2433 return "can't create invoice line item: $error";
2438 foreach my $hook ( @precommit_hooks ) {
2440 &{$hook}; #($self) ?
2443 $dbh->rollback if $oldAutoCommit;
2444 return "$@ running precommit hook $hook\n";
2448 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2454 my ($self, %params) = @_;
2456 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2457 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2458 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2459 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2460 my $total_setup = $params{setup} or die "no setup accumulator specified";
2461 my $total_recur = $params{recur} or die "no recur accumulator specified";
2462 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2463 my $time = $params{'time'} or die "no time specified";
2464 my (%options) = %{$params{options}}; #hmmm only for 'resetup'
2467 my $real_pkgpart = $cust_pkg->pkgpart;
2468 my %hash = $cust_pkg->hash;
2469 my $old_cust_pkg = new FS::cust_pkg \%hash;
2475 $cust_pkg->pkgpart($part_pkg->pkgpart);
2483 if ( ! $cust_pkg->setup &&
2485 ( $conf->exists('disable_setup_suspended_pkgs') &&
2486 ! $cust_pkg->getfield('susp')
2487 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2489 || $options{'resetup'}
2492 warn " bill setup\n" if $DEBUG > 1;
2495 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2496 return "$@ running calc_setup for $cust_pkg\n"
2499 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2501 $cust_pkg->setfield('setup', $time)
2502 unless $cust_pkg->setup;
2503 #do need it, but it won't get written to the db
2504 #|| $cust_pkg->pkgpart != $real_pkgpart;
2509 # bill recurring fee
2512 #XXX unit stuff here too
2516 if ( ! $cust_pkg->getfield('susp') and
2517 ( $part_pkg->getfield('freq') ne '0' &&
2518 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2520 || ( $part_pkg->plan eq 'voip_cdr'
2521 && $part_pkg->option('bill_every_call')
2525 # XXX should this be a package event? probably. events are called
2526 # at collection time at the moment, though...
2527 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2528 if $part_pkg->can('reset_usage');
2529 #don't want to reset usage just cause we want a line item??
2530 #&& $part_pkg->pkgpart == $real_pkgpart;
2532 warn " bill recur\n" if $DEBUG > 1;
2535 # XXX shared with $recur_prog
2536 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2538 #over two params! lets at least switch to a hashref for the rest...
2539 my $increment_next_bill = ( $part_pkg->freq ne '0'
2540 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
2542 my %param = ( 'precommit_hooks' => $precommit_hooks,
2543 'increment_next_bill' => $increment_next_bill,
2546 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2547 return "$@ running calc_recur for $cust_pkg\n"
2550 if ( $increment_next_bill ) {
2552 #change this bit to use Date::Manip? CAREFUL with timezones (see
2553 # mailing list archive)
2554 my ($sec,$min,$hour,$mday,$mon,$year) =
2555 (localtime($sdate) )[0,1,2,3,4,5];
2557 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2558 # only for figuring next bill date, nothing else, so, reset $sdate again
2560 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2561 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2562 $cust_pkg->last_bill($sdate);
2564 if ( $part_pkg->freq =~ /^\d+$/ ) {
2565 $mon += $part_pkg->freq;
2566 until ( $mon < 12 ) { $mon -= 12; $year++; }
2567 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2569 $mday += $weeks * 7;
2570 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2573 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2577 return "unparsable frequency: ". $part_pkg->freq;
2579 $cust_pkg->setfield('bill',
2580 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2586 warn "\$setup is undefined" unless defined($setup);
2587 warn "\$recur is undefined" unless defined($recur);
2588 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2591 # If there's line items, create em cust_bill_pkg records
2592 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2597 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2598 # hmm.. and if just the options are modified in some weird price plan?
2600 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2603 my $error = $cust_pkg->replace( $old_cust_pkg,
2604 'options' => { $cust_pkg->options },
2606 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2607 if $error; #just in case
2610 $setup = sprintf( "%.2f", $setup );
2611 $recur = sprintf( "%.2f", $recur );
2612 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2613 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2615 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2616 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2619 if ( $setup != 0 || $recur != 0 ) {
2621 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2624 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2626 warn " adding customer package invoice detail: $_\n"
2627 foreach @cust_pkg_detail;
2629 push @details, @cust_pkg_detail;
2631 my $cust_bill_pkg = new FS::cust_bill_pkg {
2632 'pkgnum' => $cust_pkg->pkgnum,
2634 'unitsetup' => $unitsetup,
2636 'unitrecur' => $unitrecur,
2637 'quantity' => $cust_pkg->quantity,
2638 'details' => \@details,
2641 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
2642 $cust_bill_pkg->sdate( $hash{last_bill} );
2643 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2644 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
2645 $cust_bill_pkg->sdate( $sdate );
2646 $cust_bill_pkg->edate( $cust_pkg->bill );
2649 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2650 unless $part_pkg->pkgpart == $real_pkgpart;
2652 $$total_setup += $setup;
2653 $$total_recur += $recur;
2660 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg);
2661 return $error if $error;
2663 push @$cust_bill_pkgs, $cust_bill_pkg;
2665 } #if $setup != 0 || $recur != 0
2675 my $part_pkg = shift;
2676 my $taxlisthash = shift;
2677 my $cust_bill_pkg = shift;
2678 my $cust_pkg = shift;
2680 my %cust_bill_pkg = ();
2684 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2689 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
2690 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
2691 push @classes, 'setup' if $cust_bill_pkg->setup;
2692 push @classes, 'recur' if $cust_bill_pkg->recur;
2694 if ( $conf->exists('enable_taxproducts')
2695 && (scalar($part_pkg->part_pkg_taxoverride) || $part_pkg->has_taxproduct)
2696 && ( $self->tax !~ /Y/i && $self->payby ne 'COMP' )
2700 foreach my $class (@classes) {
2701 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $prefix );
2702 return $err_or_ref unless ref($err_or_ref);
2703 $taxes{$class} = $err_or_ref;
2706 unless (exists $taxes{''}) {
2707 my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $prefix );
2708 return $err_or_ref unless ref($err_or_ref);
2709 $taxes{''} = $err_or_ref;
2712 } elsif ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
2714 my %taxhash = map { $_ => $self->get("$prefix$_") }
2715 qw( state county country );
2717 $taxhash{'taxclass'} = $part_pkg->taxclass;
2719 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2722 $taxhash{'taxclass'} = '';
2723 @taxes = qsearch( 'cust_main_county', \%taxhash );
2726 #one more try at a whole-country tax rate
2728 $taxhash{$_} = '' foreach qw( state county );
2729 @taxes = qsearch( 'cust_main_county', \%taxhash );
2732 $taxes{''} = [ @taxes ];
2733 $taxes{'setup'} = [ @taxes ];
2734 $taxes{'recur'} = [ @taxes ];
2735 $taxes{$_} = [ @taxes ] foreach (@classes);
2737 # maybe eliminate this entirely, along with all the 0% records
2740 "fatal: can't find tax rate for state/county/country/taxclass ".
2741 join('/', ( map $self->get("$prefix$_"),
2742 qw(state county country)
2744 $part_pkg->taxclass ). "\n";
2747 } #if $conf->exists('enable_taxproducts') ...
2750 if ( $conf->exists('separate_usage') ) {
2751 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
2752 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
2753 push @display, new FS::cust_bill_pkg_display { type => 'S' };
2754 push @display, new FS::cust_bill_pkg_display { type => 'R' };
2755 push @display, new FS::cust_bill_pkg_display { type => 'U',
2758 if ($section && $summary) {
2759 $display[2]->post_total('Y');
2760 push @display, new FS::cust_bill_pkg_display { type => 'U',
2765 $cust_bill_pkg->set('display', \@display);
2767 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
2768 foreach my $key (keys %tax_cust_bill_pkg) {
2769 my @taxes = @{ $taxes{$key} || [] };
2770 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
2772 foreach my $tax ( @taxes ) {
2773 my $taxname = ref( $tax ). ' '. $tax->taxnum;
2774 if ( exists( $taxlisthash->{ $taxname } ) ) {
2775 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
2777 $taxlisthash->{ $taxname } = [ $tax, $tax_cust_bill_pkg ];
2787 my $part_pkg = shift;
2792 my $geocode = $self->geocode('cch');
2794 my @taxclassnums = map { $_->taxclassnum }
2795 $part_pkg->part_pkg_taxoverride($class);
2797 unless (@taxclassnums) {
2798 @taxclassnums = map { $_->taxclassnum }
2799 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
2801 warn "Found taxclassnum values of ". join(',', @taxclassnums)
2806 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2808 @taxes = qsearch({ 'table' => 'tax_rate',
2809 'hashref' => { 'geocode' => $geocode, },
2810 'extra_sql' => $extra_sql,
2812 if scalar(@taxclassnums);
2814 # maybe eliminate this entirely, along with all the 0% records
2817 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2818 join('/', ( map $self->get("$prefix$_"),
2821 $part_pkg->taxproduct_description,
2822 $part_pkg->pkgpart ). "\n";
2825 warn "Found taxes ".
2826 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
2833 =item collect OPTIONS
2835 (Attempt to) collect money for this customer's outstanding invoices (see
2836 L<FS::cust_bill>). Usually used after the bill method.
2838 Actions are now triggered by billing events; see L<FS::part_event> and the
2839 billing events web interface. Old-style invoice events (see
2840 L<FS::part_bill_event>) have been deprecated.
2842 If there is an error, returns the error, otherwise returns false.
2844 Options are passed as name-value pairs.
2846 Currently available options are:
2852 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.
2856 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2860 set true to surpress email card/ACH decline notices.
2864 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2868 allows for one time override of normal customer billing method
2872 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)
2880 my( $self, %options ) = @_;
2881 my $invoice_time = $options{'invoice_time'} || time;
2884 local $SIG{HUP} = 'IGNORE';
2885 local $SIG{INT} = 'IGNORE';
2886 local $SIG{QUIT} = 'IGNORE';
2887 local $SIG{TERM} = 'IGNORE';
2888 local $SIG{TSTP} = 'IGNORE';
2889 local $SIG{PIPE} = 'IGNORE';
2891 my $oldAutoCommit = $FS::UID::AutoCommit;
2892 local $FS::UID::AutoCommit = 0;
2895 $self->select_for_update; #mutex
2898 my $balance = $self->balance;
2899 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2902 if ( exists($options{'retry_card'}) ) {
2903 carp 'retry_card option passed to collect is deprecated; use retry';
2904 $options{'retry'} ||= $options{'retry_card'};
2906 if ( exists($options{'retry'}) && $options{'retry'} ) {
2907 my $error = $self->retry_realtime;
2909 $dbh->rollback if $oldAutoCommit;
2914 # false laziness w/pay_batch::import_results
2916 my $due_cust_event = $self->due_cust_event(
2917 'debug' => ( $options{'debug'} || 0 ),
2918 'time' => $invoice_time,
2919 'check_freq' => $options{'check_freq'},
2921 unless( ref($due_cust_event) ) {
2922 $dbh->rollback if $oldAutoCommit;
2923 return $due_cust_event;
2926 foreach my $cust_event ( @$due_cust_event ) {
2930 #re-eval event conditions (a previous event could have changed things)
2931 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2932 #don't leave stray "new/locked" records around
2933 my $error = $cust_event->delete;
2935 #gah, even with transactions
2936 $dbh->commit if $oldAutoCommit; #well.
2943 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2944 warn " running cust_event ". $cust_event->eventnum. "\n"
2948 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2949 if ( my $error = $cust_event->do_event() ) {
2950 #XXX wtf is this? figure out a proper dealio with return value
2952 # gah, even with transactions.
2953 $dbh->commit if $oldAutoCommit; #well.
2960 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2965 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2967 Inserts database records for and returns an ordered listref of new events due
2968 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2969 events are due, an empty listref is returned. If there is an error, returns a
2970 scalar error message.
2972 To actually run the events, call each event's test_condition method, and if
2973 still true, call the event's do_event method.
2975 Options are passed as a hashref or as a list of name-value pairs. Available
2982 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.
2986 "Current time" for the events.
2990 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)
2994 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2998 Explicitly pass the objects to be tested (typically used with eventtable).
3002 Set to true to return the objects, but not actually insert them into the
3009 sub due_cust_event {
3011 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
3014 #my $DEBUG = $opt{'debug'}
3015 local($DEBUG) = $opt{'debug'}
3016 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
3018 warn "$me due_cust_event called with options ".
3019 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
3022 $opt{'time'} ||= time;
3024 local $SIG{HUP} = 'IGNORE';
3025 local $SIG{INT} = 'IGNORE';
3026 local $SIG{QUIT} = 'IGNORE';
3027 local $SIG{TERM} = 'IGNORE';
3028 local $SIG{TSTP} = 'IGNORE';
3029 local $SIG{PIPE} = 'IGNORE';
3031 my $oldAutoCommit = $FS::UID::AutoCommit;
3032 local $FS::UID::AutoCommit = 0;
3035 $self->select_for_update #mutex
3036 unless $opt{testonly};
3039 # 1: find possible events (initial search)
3042 my @cust_event = ();
3044 my @eventtable = $opt{'eventtable'}
3045 ? ( $opt{'eventtable'} )
3046 : FS::part_event->eventtables_runorder;
3048 foreach my $eventtable ( @eventtable ) {
3051 if ( $opt{'objects'} ) {
3053 @objects = @{ $opt{'objects'} };
3057 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
3058 @objects = ( $eventtable eq 'cust_main' )
3060 : ( $self->$eventtable() );
3064 my @e_cust_event = ();
3066 my $cross = "CROSS JOIN $eventtable";
3067 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
3068 unless $eventtable eq 'cust_main';
3070 foreach my $object ( @objects ) {
3072 #this first search uses the condition_sql magic for optimization.
3073 #the more possible events we can eliminate in this step the better
3075 my $cross_where = '';
3076 my $pkey = $object->primary_key;
3077 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
3079 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
3081 FS::part_event_condition->where_conditions_sql( $eventtable,
3082 'time'=>$opt{'time'}
3084 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
3086 $extra_sql = "AND $extra_sql" if $extra_sql;
3088 #here is the agent virtualization
3089 $extra_sql .= " AND ( part_event.agentnum IS NULL
3090 OR part_event.agentnum = ". $self->agentnum. ' )';
3092 $extra_sql .= " $order";
3094 warn "searching for events for $eventtable ". $object->$pkey. "\n"
3095 if $opt{'debug'} > 2;
3096 my @part_event = qsearch( {
3097 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
3098 'select' => 'part_event.*',
3099 'table' => 'part_event',
3100 'addl_from' => "$cross $join",
3101 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
3102 'eventtable' => $eventtable,
3105 'extra_sql' => "AND $cross_where $extra_sql",
3109 my $pkey = $object->primary_key;
3110 warn " ". scalar(@part_event).
3111 " possible events found for $eventtable ". $object->$pkey(). "\n";
3114 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
3118 warn " ". scalar(@e_cust_event).
3119 " subtotal possible cust events found for $eventtable\n"
3122 push @cust_event, @e_cust_event;
3126 warn " ". scalar(@cust_event).
3127 " total possible cust events found in initial search\n"
3131 # 2: test conditions
3136 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
3137 'stats_hashref' => \%unsat ),
3140 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
3143 warn " invalid conditions not eliminated with condition_sql:\n".
3144 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
3151 unless( $opt{testonly} ) {
3152 foreach my $cust_event ( @cust_event ) {
3154 my $error = $cust_event->insert();
3156 $dbh->rollback if $oldAutoCommit;
3163 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3169 warn " returning events: ". Dumper(@cust_event). "\n"
3176 =item retry_realtime
3178 Schedules realtime / batch credit card / electronic check / LEC billing
3179 events for for retry. Useful if card information has changed or manual
3180 retry is desired. The 'collect' method must be called to actually retry
3183 Implementation details: For either this customer, or for each of this
3184 customer's open invoices, changes the status of the first "done" (with
3185 statustext error) realtime processing event to "failed".
3189 sub retry_realtime {
3192 local $SIG{HUP} = 'IGNORE';
3193 local $SIG{INT} = 'IGNORE';
3194 local $SIG{QUIT} = 'IGNORE';
3195 local $SIG{TERM} = 'IGNORE';
3196 local $SIG{TSTP} = 'IGNORE';
3197 local $SIG{PIPE} = 'IGNORE';
3199 my $oldAutoCommit = $FS::UID::AutoCommit;
3200 local $FS::UID::AutoCommit = 0;
3203 #a little false laziness w/due_cust_event (not too bad, really)
3205 my $join = FS::part_event_condition->join_conditions_sql;
3206 my $order = FS::part_event_condition->order_conditions_sql;
3209 . join ( ' OR ' , map {
3210 "( part_event.eventtable = " . dbh->quote($_)
3211 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3212 } FS::part_event->eventtables)
3215 #here is the agent virtualization
3216 my $agent_virt = " ( part_event.agentnum IS NULL
3217 OR part_event.agentnum = ". $self->agentnum. ' )';
3219 #XXX this shouldn't be hardcoded, actions should declare it...
3220 my @realtime_events = qw(
3221 cust_bill_realtime_card
3222 cust_bill_realtime_check
3223 cust_bill_realtime_lec
3227 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3232 my @cust_event = qsearchs({
3233 'table' => 'cust_event',
3234 'select' => 'cust_event.*',
3235 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3236 'hashref' => { 'status' => 'done' },
3237 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3238 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3241 my %seen_invnum = ();
3242 foreach my $cust_event (@cust_event) {
3244 #max one for the customer, one for each open invoice
3245 my $cust_X = $cust_event->cust_X;
3246 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3250 or $cust_event->part_event->eventtable eq 'cust_bill'
3253 my $error = $cust_event->retry;
3255 $dbh->rollback if $oldAutoCommit;
3256 return "error scheduling event for retry: $error";
3261 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3266 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3268 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3269 via a Business::OnlinePayment realtime gateway. See
3270 L<http://420.am/business-onlinepayment> for supported gateways.
3272 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3274 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3276 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3277 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3278 if set, will override the value from the customer record.
3280 I<description> is a free-text field passed to the gateway. It defaults to
3281 "Internet services".
3283 If an I<invnum> is specified, this payment (if successful) is applied to the
3284 specified invoice. If you don't specify an I<invnum> you might want to
3285 call the B<apply_payments> method.
3287 I<quiet> can be set true to surpress email decline notices.
3289 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3290 resulting paynum, if any.
3292 I<payunique> is a unique identifier for this payment.
3294 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3299 my( $self, $method, $amount, %options ) = @_;
3301 warn "$me realtime_bop: $method $amount\n";
3302 warn " $_ => $options{$_}\n" foreach keys %options;
3305 $options{'description'} ||= 'Internet services';
3307 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3309 eval "use Business::OnlinePayment";
3312 my $payinfo = exists($options{'payinfo'})
3313 ? $options{'payinfo'}
3316 my %method2payby = (
3323 # check for banned credit card/ACH
3326 my $ban = qsearchs('banned_pay', {
3327 'payby' => $method2payby{$method},
3328 'payinfo' => md5_base64($payinfo),
3330 return "Banned credit card" if $ban;
3337 if ( $options{'invnum'} ) {
3338 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3339 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3341 map { $_->part_pkg->taxclass }
3343 map { $_->cust_pkg }
3344 $cust_bill->cust_bill_pkg;
3345 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3346 #different taxclasses
3347 $taxclass = $taxclasses[0];
3351 #look for an agent gateway override first
3353 if ( $method eq 'CC' ) {
3354 $cardtype = cardtype($payinfo);
3355 } elsif ( $method eq 'ECHECK' ) {
3358 $cardtype = $method;
3362 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3363 cardtype => $cardtype,
3364 taxclass => $taxclass, } )
3365 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3367 taxclass => $taxclass, } )
3368 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3369 cardtype => $cardtype,
3371 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3373 taxclass => '', } );
3375 my $payment_gateway = '';
3376 my( $processor, $login, $password, $action, @bop_options );
3377 if ( $override ) { #use a payment gateway override
3379 $payment_gateway = $override->payment_gateway;
3381 $processor = $payment_gateway->gateway_module;
3382 $login = $payment_gateway->gateway_username;
3383 $password = $payment_gateway->gateway_password;
3384 $action = $payment_gateway->gateway_action;
3385 @bop_options = $payment_gateway->options;
3387 } else { #use the standard settings from the config
3389 ( $processor, $login, $password, $action, @bop_options ) =
3390 $self->default_payment_gateway($method);
3398 my $address = exists($options{'address1'})
3399 ? $options{'address1'}
3401 my $address2 = exists($options{'address2'})
3402 ? $options{'address2'}
3404 $address .= ", ". $address2 if length($address2);
3406 my $o_payname = exists($options{'payname'})
3407 ? $options{'payname'}
3409 my($payname, $payfirst, $paylast);
3410 if ( $o_payname && $method ne 'ECHECK' ) {
3411 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3412 or return "Illegal payname $payname";
3413 ($payfirst, $paylast) = ($1, $2);
3415 $payfirst = $self->getfield('first');
3416 $paylast = $self->getfield('last');
3417 $payname = "$payfirst $paylast";
3420 my @invoicing_list = $self->invoicing_list_emailonly;
3421 if ( $conf->exists('emailinvoiceautoalways')
3422 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3423 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3424 push @invoicing_list, $self->all_emails;
3427 my $email = ($conf->exists('business-onlinepayment-email-override'))
3428 ? $conf->config('business-onlinepayment-email-override')
3429 : $invoicing_list[0];
3433 my $payip = exists($options{'payip'})
3436 $content{customer_ip} = $payip
3439 $content{invoice_number} = $options{'invnum'}
3440 if exists($options{'invnum'}) && length($options{'invnum'});
3442 $content{email_customer} =
3443 ( $conf->exists('business-onlinepayment-email_customer')
3444 || $conf->exists('business-onlinepayment-email-override') );
3447 if ( $method eq 'CC' ) {
3449 $content{card_number} = $payinfo;
3450 $paydate = exists($options{'paydate'})
3451 ? $options{'paydate'}
3453 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3454 $content{expiration} = "$2/$1";
3456 my $paycvv = exists($options{'paycvv'})
3457 ? $options{'paycvv'}
3459 $content{cvv2} = $paycvv
3462 my $paystart_month = exists($options{'paystart_month'})
3463 ? $options{'paystart_month'}
3464 : $self->paystart_month;
3466 my $paystart_year = exists($options{'paystart_year'})
3467 ? $options{'paystart_year'}
3468 : $self->paystart_year;
3470 $content{card_start} = "$paystart_month/$paystart_year"
3471 if $paystart_month && $paystart_year;
3473 my $payissue = exists($options{'payissue'})
3474 ? $options{'payissue'}
3476 $content{issue_number} = $payissue if $payissue;
3478 $content{recurring_billing} = 'YES'
3479 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3481 'payinfo' => $payinfo,
3483 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3485 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3489 } elsif ( $method eq 'ECHECK' ) {
3490 ( $content{account_number}, $content{routing_code} ) =
3491 split('@', $payinfo);
3492 $content{bank_name} = $o_payname;
3493 $content{bank_state} = exists($options{'paystate'})
3494 ? $options{'paystate'}
3495 : $self->getfield('paystate');
3496 $content{account_type} = exists($options{'paytype'})
3497 ? uc($options{'paytype'}) || 'CHECKING'
3498 : uc($self->getfield('paytype')) || 'CHECKING';
3499 $content{account_name} = $payname;
3500 $content{customer_org} = $self->company ? 'B' : 'I';
3501 $content{state_id} = exists($options{'stateid'})
3502 ? $options{'stateid'}
3503 : $self->getfield('stateid');
3504 $content{state_id_state} = exists($options{'stateid_state'})
3505 ? $options{'stateid_state'}
3506 : $self->getfield('stateid_state');
3507 $content{customer_ssn} = exists($options{'ss'})
3510 } elsif ( $method eq 'LEC' ) {
3511 $content{phone} = $payinfo;
3515 # run transaction(s)
3518 my $balance = exists( $options{'balance'} )
3519 ? $options{'balance'}
3522 $self->select_for_update; #mutex ... just until we get our pending record in
3524 #the checks here are intended to catch concurrent payments
3525 #double-form-submission prevention is taken care of in cust_pay_pending::check
3528 return "The customer's balance has changed; $method transaction aborted."
3529 if $self->balance < $balance;
3530 #&& $self->balance < $amount; #might as well anyway?
3532 #also check and make sure there aren't *other* pending payments for this cust
3534 my @pending = qsearch('cust_pay_pending', {
3535 'custnum' => $self->custnum,
3536 'status' => { op=>'!=', value=>'done' }
3538 return "A payment is already being processed for this customer (".
3539 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3540 "); $method transaction aborted."
3541 if scalar(@pending);
3543 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3545 my $cust_pay_pending = new FS::cust_pay_pending {
3546 'custnum' => $self->custnum,
3547 #'invnum' => $options{'invnum'},
3550 'payby' => $method2payby{$method},
3551 'payinfo' => $payinfo,
3552 'paydate' => $paydate,
3554 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3556 $cust_pay_pending->payunique( $options{payunique} )
3557 if defined($options{payunique}) && length($options{payunique});
3558 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3559 return $cpp_new_err if $cpp_new_err;
3561 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3563 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3564 $transaction->content(
3567 'password' => $password,
3568 'action' => $action1,
3569 'description' => $options{'description'},
3570 'amount' => $amount,
3571 #'invoice_number' => $options{'invnum'},
3572 'customer_id' => $self->custnum,
3573 'last_name' => $paylast,
3574 'first_name' => $payfirst,
3576 'address' => $address,
3577 'city' => ( exists($options{'city'})
3580 'state' => ( exists($options{'state'})
3583 'zip' => ( exists($options{'zip'})
3586 'country' => ( exists($options{'country'})
3587 ? $options{'country'}
3589 'referer' => 'http://cleanwhisker.420.am/',
3591 'phone' => $self->daytime || $self->night,
3595 $cust_pay_pending->status('pending');
3596 my $cpp_pending_err = $cust_pay_pending->replace;
3597 return $cpp_pending_err if $cpp_pending_err;
3600 my $BOP_TESTING = 0;
3601 my $BOP_TESTING_SUCCESS = 1;
3603 unless ( $BOP_TESTING ) {
3604 $transaction->submit();
3606 if ( $BOP_TESTING_SUCCESS ) {
3607 $transaction->is_success(1);
3608 $transaction->authorization('fake auth');
3610 $transaction->is_success(0);
3611 $transaction->error_message('fake failure');
3615 if ( $transaction->is_success() && $action2 ) {
3617 $cust_pay_pending->status('authorized');
3618 my $cpp_authorized_err = $cust_pay_pending->replace;
3619 return $cpp_authorized_err if $cpp_authorized_err;
3621 my $auth = $transaction->authorization;
3622 my $ordernum = $transaction->can('order_number')
3623 ? $transaction->order_number
3627 new Business::OnlinePayment( $processor, @bop_options );
3634 password => $password,
3635 order_number => $ordernum,
3637 authorization => $auth,
3638 description => $options{'description'},
3641 foreach my $field (qw( authorization_source_code returned_ACI
3642 transaction_identifier validation_code
3643 transaction_sequence_num local_transaction_date
3644 local_transaction_time AVS_result_code )) {
3645 $capture{$field} = $transaction->$field() if $transaction->can($field);
3648 $capture->content( %capture );
3652 unless ( $capture->is_success ) {
3653 my $e = "Authorization successful but capture failed, custnum #".
3654 $self->custnum. ': '. $capture->result_code.
3655 ": ". $capture->error_message;
3662 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3663 my $cpp_captured_err = $cust_pay_pending->replace;
3664 return $cpp_captured_err if $cpp_captured_err;
3667 # remove paycvv after initial transaction
3670 #false laziness w/misc/process/payment.cgi - check both to make sure working
3672 if ( defined $self->dbdef_table->column('paycvv')
3673 && length($self->paycvv)
3674 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3676 my $error = $self->remove_cvv;
3678 warn "WARNING: error removing cvv: $error\n";
3686 if ( $transaction->is_success() ) {
3689 if ( $payment_gateway ) { # agent override
3690 $paybatch = $payment_gateway->gatewaynum. '-';
3693 $paybatch .= "$processor:". $transaction->authorization;
3695 $paybatch .= ':'. $transaction->order_number
3696 if $transaction->can('order_number')
3697 && length($transaction->order_number);
3699 my $cust_pay = new FS::cust_pay ( {
3700 'custnum' => $self->custnum,
3701 'invnum' => $options{'invnum'},
3704 'payby' => $method2payby{$method},
3705 'payinfo' => $payinfo,
3706 'paybatch' => $paybatch,
3707 'paydate' => $paydate,
3709 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3710 $cust_pay->payunique( $options{payunique} )
3711 if defined($options{payunique}) && length($options{payunique});
3713 my $oldAutoCommit = $FS::UID::AutoCommit;
3714 local $FS::UID::AutoCommit = 0;
3717 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3719 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3722 $cust_pay->invnum(''); #try again with no specific invnum
3723 my $error2 = $cust_pay->insert( $options{'manual'} ?
3724 ( 'manual' => 1 ) : ()
3727 # gah. but at least we have a record of the state we had to abort in
3728 # from cust_pay_pending now.
3729 my $e = "WARNING: $method captured but payment not recorded - ".
3730 "error inserting payment ($processor): $error2".
3731 " (previously tried insert with invnum #$options{'invnum'}" .
3732 ": $error ) - pending payment saved as paypendingnum ".
3733 $cust_pay_pending->paypendingnum. "\n";
3739 if ( $options{'paynum_ref'} ) {
3740 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3743 $cust_pay_pending->status('done');
3744 $cust_pay_pending->statustext('captured');
3745 my $cpp_done_err = $cust_pay_pending->replace;
3747 if ( $cpp_done_err ) {
3749 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3750 my $e = "WARNING: $method captured but payment not recorded - ".
3751 "error updating status for paypendingnum ".
3752 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3758 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3759 return ''; #no error
3765 my $perror = "$processor error: ". $transaction->error_message;
3767 unless ( $transaction->error_message ) {
3770 if ( $transaction->can('response_page') ) {
3772 'page' => ( $transaction->can('response_page')
3773 ? $transaction->response_page
3776 'code' => ( $transaction->can('response_code')
3777 ? $transaction->response_code
3780 'headers' => ( $transaction->can('response_headers')
3781 ? $transaction->response_headers
3787 "No additional debugging information available for $processor";
3790 $perror .= "No error_message returned from $processor -- ".
3791 ( ref($t_response) ? Dumper($t_response) : $t_response );
3795 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3796 && $conf->exists('emaildecline')
3797 && grep { $_ ne 'POST' } $self->invoicing_list
3798 && ! grep { $transaction->error_message =~ /$_/ }
3799 $conf->config('emaildecline-exclude')
3801 my @templ = $conf->config('declinetemplate');
3802 my $template = new Text::Template (
3804 SOURCE => [ map "$_\n", @templ ],
3805 ) or return "($perror) can't create template: $Text::Template::ERROR";
3806 $template->compile()
3807 or return "($perror) can't compile template: $Text::Template::ERROR";
3809 my $templ_hash = { error => $transaction->error_message };
3811 my $error = send_email(
3812 'from' => $conf->config('invoice_from'),
3813 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3814 'subject' => 'Your payment could not be processed',
3815 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3818 $perror .= " (also received error sending decline notification: $error)"
3823 $cust_pay_pending->status('done');
3824 $cust_pay_pending->statustext("declined: $perror");
3825 my $cpp_done_err = $cust_pay_pending->replace;
3826 if ( $cpp_done_err ) {
3827 my $e = "WARNING: $method declined but pending payment not resolved - ".
3828 "error updating status for paypendingnum ".
3829 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3831 $perror = "$e ($perror)";
3844 my( $self, $method, $amount, %options ) = @_;
3846 if ( $options{'fake_failure'} ) {
3847 return "Error: No error; test failure requested with fake_failure";
3850 my %method2payby = (
3857 #if ( $payment_gateway ) { # agent override
3858 # $paybatch = $payment_gateway->gatewaynum. '-';
3861 #$paybatch .= "$processor:". $transaction->authorization;
3863 #$paybatch .= ':'. $transaction->order_number
3864 # if $transaction->can('order_number')
3865 # && length($transaction->order_number);
3867 my $paybatch = 'FakeProcessor:54:32';
3869 my $cust_pay = new FS::cust_pay ( {
3870 'custnum' => $self->custnum,
3871 'invnum' => $options{'invnum'},
3874 'payby' => $method2payby{$method},
3875 #'payinfo' => $payinfo,
3876 'payinfo' => '4111111111111111',
3877 'paybatch' => $paybatch,
3878 #'paydate' => $paydate,
3879 'paydate' => '2012-05-01',
3881 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3883 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3886 $cust_pay->invnum(''); #try again with no specific invnum
3887 my $error2 = $cust_pay->insert( $options{'manual'} ?
3888 ( 'manual' => 1 ) : ()
3891 # gah, even with transactions.
3892 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3893 "error inserting (fake!) payment: $error2".
3894 " (previously tried insert with invnum #$options{'invnum'}" .
3901 if ( $options{'paynum_ref'} ) {
3902 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3905 return ''; #no error
3909 =item default_payment_gateway
3913 sub default_payment_gateway {
3914 my( $self, $method ) = @_;
3916 die "Real-time processing not enabled\n"
3917 unless $conf->exists('business-onlinepayment');
3920 my $bop_config = 'business-onlinepayment';
3921 $bop_config .= '-ach'
3922 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3923 my ( $processor, $login, $password, $action, @bop_options ) =
3924 $conf->config($bop_config);
3925 $action ||= 'normal authorization';
3926 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3927 die "No real-time processor is enabled - ".
3928 "did you set the business-onlinepayment configuration value?\n"
3931 ( $processor, $login, $password, $action, @bop_options )
3936 Removes the I<paycvv> field from the database directly.
3938 If there is an error, returns the error, otherwise returns false.
3944 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3945 or return dbh->errstr;
3946 $sth->execute($self->custnum)
3947 or return $sth->errstr;
3952 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3954 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3955 via a Business::OnlinePayment realtime gateway. See
3956 L<http://420.am/business-onlinepayment> for supported gateways.
3958 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3960 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3962 Most gateways require a reference to an original payment transaction to refund,
3963 so you probably need to specify a I<paynum>.
3965 I<amount> defaults to the original amount of the payment if not specified.
3967 I<reason> specifies a reason for the refund.
3969 I<paydate> specifies the expiration date for a credit card overriding the
3970 value from the customer record or the payment record. Specified as yyyy-mm-dd
3972 Implementation note: If I<amount> is unspecified or equal to the amount of the
3973 orignal payment, first an attempt is made to "void" the transaction via
3974 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3975 the normal attempt is made to "refund" ("credit") the transaction via the
3976 gateway is attempted.
3978 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3979 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3980 #if set, will override the value from the customer record.
3982 #If an I<invnum> is specified, this payment (if successful) is applied to the
3983 #specified invoice. If you don't specify an I<invnum> you might want to
3984 #call the B<apply_payments> method.
3988 #some false laziness w/realtime_bop, not enough to make it worth merging
3989 #but some useful small subs should be pulled out
3990 sub realtime_refund_bop {
3991 my( $self, $method, %options ) = @_;
3993 warn "$me realtime_refund_bop: $method refund\n";
3994 warn " $_ => $options{$_}\n" foreach keys %options;
3997 eval "use Business::OnlinePayment";
4001 # look up the original payment and optionally a gateway for that payment
4005 my $amount = $options{'amount'};
4007 my( $processor, $login, $password, @bop_options ) ;
4008 my( $auth, $order_number ) = ( '', '', '' );
4010 if ( $options{'paynum'} ) {
4012 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
4013 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
4014 or return "Unknown paynum $options{'paynum'}";
4015 $amount ||= $cust_pay->paid;
4017 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
4018 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
4019 $cust_pay->paybatch;
4020 my $gatewaynum = '';
4021 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
4023 if ( $gatewaynum ) { #gateway for the payment to be refunded
4025 my $payment_gateway =
4026 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
4027 die "payment gateway $gatewaynum not found"
4028 unless $payment_gateway;
4030 $processor = $payment_gateway->gateway_module;
4031 $login = $payment_gateway->gateway_username;
4032 $password = $payment_gateway->gateway_password;
4033 @bop_options = $payment_gateway->options;
4035 } else { #try the default gateway
4037 my( $conf_processor, $unused_action );
4038 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
4039 $self->default_payment_gateway($method);
4041 return "processor of payment $options{'paynum'} $processor does not".
4042 " match default processor $conf_processor"
4043 unless $processor eq $conf_processor;
4048 } else { # didn't specify a paynum, so look for agent gateway overrides
4049 # like a normal transaction
4052 if ( $method eq 'CC' ) {
4053 $cardtype = cardtype($self->payinfo);
4054 } elsif ( $method eq 'ECHECK' ) {
4057 $cardtype = $method;
4060 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
4061 cardtype => $cardtype,
4063 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
4065 taxclass => '', } );
4067 if ( $override ) { #use a payment gateway override
4069 my $payment_gateway = $override->payment_gateway;
4071 $processor = $payment_gateway->gateway_module;
4072 $login = $payment_gateway->gateway_username;
4073 $password = $payment_gateway->gateway_password;
4074 #$action = $payment_gateway->gateway_action;
4075 @bop_options = $payment_gateway->options;
4077 } else { #use the standard settings from the config
4080 ( $processor, $login, $password, $unused_action, @bop_options ) =
4081 $self->default_payment_gateway($method);
4086 return "neither amount nor paynum specified" unless $amount;
4091 'password' => $password,
4092 'order_number' => $order_number,
4093 'amount' => $amount,
4094 'referer' => 'http://cleanwhisker.420.am/',
4096 $content{authorization} = $auth
4097 if length($auth); #echeck/ACH transactions have an order # but no auth
4098 #(at least with authorize.net)
4100 my $disable_void_after;
4101 if ($conf->exists('disable_void_after')
4102 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
4103 $disable_void_after = $1;
4106 #first try void if applicable
4107 if ( $cust_pay && $cust_pay->paid == $amount
4109 ( not defined($disable_void_after) )
4110 || ( time < ($cust_pay->_date + $disable_void_after ) )
4113 warn " attempting void\n" if $DEBUG > 1;
4114 my $void = new Business::OnlinePayment( $processor, @bop_options );
4115 $void->content( 'action' => 'void', %content );
4117 if ( $void->is_success ) {
4118 my $error = $cust_pay->void($options{'reason'});
4120 # gah, even with transactions.
4121 my $e = 'WARNING: Card/ACH voided but database not updated - '.
4122 "error voiding payment: $error";
4126 warn " void successful\n" if $DEBUG > 1;
4131 warn " void unsuccessful, trying refund\n"
4135 my $address = $self->address1;
4136 $address .= ", ". $self->address2 if $self->address2;
4138 my($payname, $payfirst, $paylast);
4139 if ( $self->payname && $method ne 'ECHECK' ) {
4140 $payname = $self->payname;
4141 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4142 or return "Illegal payname $payname";
4143 ($payfirst, $paylast) = ($1, $2);
4145 $payfirst = $self->getfield('first');
4146 $paylast = $self->getfield('last');
4147 $payname = "$payfirst $paylast";
4150 my @invoicing_list = $self->invoicing_list_emailonly;
4151 if ( $conf->exists('emailinvoiceautoalways')
4152 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4153 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4154 push @invoicing_list, $self->all_emails;
4157 my $email = ($conf->exists('business-onlinepayment-email-override'))
4158 ? $conf->config('business-onlinepayment-email-override')
4159 : $invoicing_list[0];
4161 my $payip = exists($options{'payip'})
4164 $content{customer_ip} = $payip
4168 if ( $method eq 'CC' ) {
4171 $content{card_number} = $payinfo = $cust_pay->payinfo;
4172 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
4173 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
4174 ($content{expiration} = "$2/$1"); # where available
4176 $content{card_number} = $payinfo = $self->payinfo;
4177 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
4178 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4179 $content{expiration} = "$2/$1";
4182 } elsif ( $method eq 'ECHECK' ) {
4185 $payinfo = $cust_pay->payinfo;
4187 $payinfo = $self->payinfo;
4189 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
4190 $content{bank_name} = $self->payname;
4191 $content{account_type} = 'CHECKING';
4192 $content{account_name} = $payname;
4193 $content{customer_org} = $self->company ? 'B' : 'I';
4194 $content{customer_ssn} = $self->ss;
4195 } elsif ( $method eq 'LEC' ) {
4196 $content{phone} = $payinfo = $self->payinfo;
4200 my $refund = new Business::OnlinePayment( $processor, @bop_options );
4201 my %sub_content = $refund->content(
4202 'action' => 'credit',
4203 'customer_id' => $self->custnum,
4204 'last_name' => $paylast,
4205 'first_name' => $payfirst,
4207 'address' => $address,
4208 'city' => $self->city,
4209 'state' => $self->state,
4210 'zip' => $self->zip,
4211 'country' => $self->country,
4213 'phone' => $self->daytime || $self->night,
4216 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
4220 return "$processor error: ". $refund->error_message
4221 unless $refund->is_success();
4223 my %method2payby = (
4229 my $paybatch = "$processor:". $refund->authorization;
4230 $paybatch .= ':'. $refund->order_number
4231 if $refund->can('order_number') && $refund->order_number;
4233 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4234 my @cust_bill_pay = $cust_pay->cust_bill_pay;
4235 last unless @cust_bill_pay;
4236 my $cust_bill_pay = pop @cust_bill_pay;
4237 my $error = $cust_bill_pay->delete;
4241 my $cust_refund = new FS::cust_refund ( {
4242 'custnum' => $self->custnum,
4243 'paynum' => $options{'paynum'},
4244 'refund' => $amount,
4246 'payby' => $method2payby{$method},
4247 'payinfo' => $payinfo,
4248 'paybatch' => $paybatch,
4249 'reason' => $options{'reason'} || 'card or ACH refund',
4251 my $error = $cust_refund->insert;
4253 $cust_refund->paynum(''); #try again with no specific paynum
4254 my $error2 = $cust_refund->insert;
4256 # gah, even with transactions.
4257 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4258 "error inserting refund ($processor): $error2".
4259 " (previously tried insert with paynum #$options{'paynum'}" .
4270 =item batch_card OPTION => VALUE...
4272 Adds a payment for this invoice to the pending credit card batch (see
4273 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4274 runs the payment using a realtime gateway.
4279 my ($self, %options) = @_;
4282 if (exists($options{amount})) {
4283 $amount = $options{amount};
4285 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4287 return '' unless $amount > 0;
4289 my $invnum = delete $options{invnum};
4290 my $payby = $options{invnum} || $self->payby; #dubious
4292 if ($options{'realtime'}) {
4293 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4299 my $oldAutoCommit = $FS::UID::AutoCommit;
4300 local $FS::UID::AutoCommit = 0;
4303 #this needs to handle mysql as well as Pg, like svc_acct.pm
4304 #(make it into a common function if folks need to do batching with mysql)
4305 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4306 or return "Cannot lock pay_batch: " . $dbh->errstr;
4310 'payby' => FS::payby->payby2payment($payby),
4313 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4315 unless ( $pay_batch ) {
4316 $pay_batch = new FS::pay_batch \%pay_batch;
4317 my $error = $pay_batch->insert;
4319 $dbh->rollback if $oldAutoCommit;
4320 die "error creating new batch: $error\n";
4324 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4325 'batchnum' => $pay_batch->batchnum,
4326 'custnum' => $self->custnum,
4329 foreach (qw( address1 address2 city state zip country payby payinfo paydate
4331 $options{$_} = '' unless exists($options{$_});
4334 my $cust_pay_batch = new FS::cust_pay_batch ( {
4335 'batchnum' => $pay_batch->batchnum,
4336 'invnum' => $invnum || 0, # is there a better value?
4337 # this field should be
4339 # cust_bill_pay_batch now
4340 'custnum' => $self->custnum,
4341 'last' => $self->getfield('last'),
4342 'first' => $self->getfield('first'),
4343 'address1' => $options{address1} || $self->address1,
4344 'address2' => $options{address2} || $self->address2,
4345 'city' => $options{city} || $self->city,
4346 'state' => $options{state} || $self->state,
4347 'zip' => $options{zip} || $self->zip,
4348 'country' => $options{country} || $self->country,
4349 'payby' => $options{payby} || $self->payby,
4350 'payinfo' => $options{payinfo} || $self->payinfo,
4351 'exp' => $options{paydate} || $self->paydate,
4352 'payname' => $options{payname} || $self->payname,
4353 'amount' => $amount, # consolidating
4356 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4357 if $old_cust_pay_batch;
4360 if ($old_cust_pay_batch) {
4361 $error = $cust_pay_batch->replace($old_cust_pay_batch)
4363 $error = $cust_pay_batch->insert;
4367 $dbh->rollback if $oldAutoCommit;
4371 my $unapplied = $self->total_unapplied_credits
4372 + $self->total_unapplied_payments
4373 + $self->in_transit_payments;
4374 foreach my $cust_bill ($self->open_cust_bill) {
4375 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4376 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4377 'invnum' => $cust_bill->invnum,
4378 'paybatchnum' => $cust_pay_batch->paybatchnum,
4379 'amount' => $cust_bill->owed,
4382 if ($unapplied >= $cust_bill_pay_batch->amount){
4383 $unapplied -= $cust_bill_pay_batch->amount;
4386 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4387 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4389 $error = $cust_bill_pay_batch->insert;
4391 $dbh->rollback if $oldAutoCommit;
4396 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4400 =item apply_payments_and_credits
4402 Applies unapplied payments and credits.
4404 In most cases, this new method should be used in place of sequential
4405 apply_payments and apply_credits methods.
4407 If there is an error, returns the error, otherwise returns false.
4411 sub apply_payments_and_credits {
4414 local $SIG{HUP} = 'IGNORE';
4415 local $SIG{INT} = 'IGNORE';
4416 local $SIG{QUIT} = 'IGNORE';
4417 local $SIG{TERM} = 'IGNORE';
4418 local $SIG{TSTP} = 'IGNORE';
4419 local $SIG{PIPE} = 'IGNORE';
4421 my $oldAutoCommit = $FS::UID::AutoCommit;
4422 local $FS::UID::AutoCommit = 0;
4425 $self->select_for_update; #mutex
4427 foreach my $cust_bill ( $self->open_cust_bill ) {
4428 my $error = $cust_bill->apply_payments_and_credits;
4430 $dbh->rollback if $oldAutoCommit;
4431 return "Error applying: $error";
4435 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4440 =item apply_credits OPTION => VALUE ...
4442 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4443 to outstanding invoice balances in chronological order (or reverse
4444 chronological order if the I<order> option is set to B<newest>) and returns the
4445 value of any remaining unapplied credits available for refund (see
4446 L<FS::cust_refund>).
4448 Dies if there is an error.
4456 local $SIG{HUP} = 'IGNORE';
4457 local $SIG{INT} = 'IGNORE';
4458 local $SIG{QUIT} = 'IGNORE';
4459 local $SIG{TERM} = 'IGNORE';
4460 local $SIG{TSTP} = 'IGNORE';
4461 local $SIG{PIPE} = 'IGNORE';
4463 my $oldAutoCommit = $FS::UID::AutoCommit;
4464 local $FS::UID::AutoCommit = 0;
4467 $self->select_for_update; #mutex
4469 unless ( $self->total_unapplied_credits ) {
4470 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4474 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4475 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4477 my @invoices = $self->open_cust_bill;
4478 @invoices = sort { $b->_date <=> $a->_date } @invoices
4479 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4482 foreach my $cust_bill ( @invoices ) {
4485 if ( !defined($credit) || $credit->credited == 0) {
4486 $credit = pop @credits or last;
4489 if ($cust_bill->owed >= $credit->credited) {
4490 $amount=$credit->credited;
4492 $amount=$cust_bill->owed;
4495 my $cust_credit_bill = new FS::cust_credit_bill ( {
4496 'crednum' => $credit->crednum,
4497 'invnum' => $cust_bill->invnum,
4498 'amount' => $amount,
4500 my $error = $cust_credit_bill->insert;
4502 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4506 redo if ($cust_bill->owed > 0);
4510 my $total_unapplied_credits = $self->total_unapplied_credits;
4512 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4514 return $total_unapplied_credits;
4517 =item apply_payments
4519 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4520 to outstanding invoice balances in chronological order.
4522 #and returns the value of any remaining unapplied payments.
4524 Dies if there is an error.
4528 sub apply_payments {
4531 local $SIG{HUP} = 'IGNORE';
4532 local $SIG{INT} = 'IGNORE';
4533 local $SIG{QUIT} = 'IGNORE';
4534 local $SIG{TERM} = 'IGNORE';
4535 local $SIG{TSTP} = 'IGNORE';
4536 local $SIG{PIPE} = 'IGNORE';
4538 my $oldAutoCommit = $FS::UID::AutoCommit;
4539 local $FS::UID::AutoCommit = 0;
4542 $self->select_for_update; #mutex
4546 my @payments = sort { $b->_date <=> $a->_date }
4547 grep { $_->unapplied > 0 }
4550 my @invoices = sort { $a->_date <=> $b->_date}
4551 grep { $_->owed > 0 }
4556 foreach my $cust_bill ( @invoices ) {
4559 if ( !defined($payment) || $payment->unapplied == 0 ) {
4560 $payment = pop @payments or last;
4563 if ( $cust_bill->owed >= $payment->unapplied ) {
4564 $amount = $payment->unapplied;
4566 $amount = $cust_bill->owed;
4569 my $cust_bill_pay = new FS::cust_bill_pay ( {
4570 'paynum' => $payment->paynum,
4571 'invnum' => $cust_bill->invnum,
4572 'amount' => $amount,
4574 my $error = $cust_bill_pay->insert;
4576 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4580 redo if ( $cust_bill->owed > 0);
4584 my $total_unapplied_payments = $self->total_unapplied_payments;
4586 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4588 return $total_unapplied_payments;
4593 Returns the total owed for this customer on all invoices
4594 (see L<FS::cust_bill/owed>).
4600 $self->total_owed_date(2145859200); #12/31/2037
4603 =item total_owed_date TIME
4605 Returns the total owed for this customer on all invoices with date earlier than
4606 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4607 see L<Time::Local> and L<Date::Parse> for conversion functions.
4611 sub total_owed_date {
4615 foreach my $cust_bill (
4616 grep { $_->_date <= $time }
4617 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4619 $total_bill += $cust_bill->owed;
4621 sprintf( "%.2f", $total_bill );
4626 Returns the total amount of all payments.
4633 $total += $_->paid foreach $self->cust_pay;
4634 sprintf( "%.2f", $total );
4637 =item total_unapplied_credits
4639 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4640 customer. See L<FS::cust_credit/credited>.
4642 =item total_credited
4644 Old name for total_unapplied_credits. Don't use.
4648 sub total_credited {
4649 #carp "total_credited deprecated, use total_unapplied_credits";
4650 shift->total_unapplied_credits(@_);
4653 sub total_unapplied_credits {
4655 my $total_credit = 0;
4656 $total_credit += $_->credited foreach $self->cust_credit;
4657 sprintf( "%.2f", $total_credit );
4660 =item total_unapplied_payments
4662 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4663 See L<FS::cust_pay/unapplied>.
4667 sub total_unapplied_payments {
4669 my $total_unapplied = 0;
4670 $total_unapplied += $_->unapplied foreach $self->cust_pay;
4671 sprintf( "%.2f", $total_unapplied );
4674 =item total_unapplied_refunds
4676 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4677 customer. See L<FS::cust_refund/unapplied>.
4681 sub total_unapplied_refunds {
4683 my $total_unapplied = 0;
4684 $total_unapplied += $_->unapplied foreach $self->cust_refund;
4685 sprintf( "%.2f", $total_unapplied );
4690 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4691 total_unapplied_credits minus total_unapplied_payments).
4699 + $self->total_unapplied_refunds
4700 - $self->total_unapplied_credits
4701 - $self->total_unapplied_payments
4705 =item balance_date TIME
4707 Returns the balance for this customer, only considering invoices with date
4708 earlier than TIME (total_owed_date minus total_credited minus
4709 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4710 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4719 $self->total_owed_date($time)
4720 + $self->total_unapplied_refunds
4721 - $self->total_unapplied_credits
4722 - $self->total_unapplied_payments
4726 =item in_transit_payments
4728 Returns the total of requests for payments for this customer pending in
4729 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4733 sub in_transit_payments {
4735 my $in_transit_payments = 0;
4736 foreach my $pay_batch ( qsearch('pay_batch', {
4739 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4740 'batchnum' => $pay_batch->batchnum,
4741 'custnum' => $self->custnum,
4743 $in_transit_payments += $cust_pay_batch->amount;
4746 sprintf( "%.2f", $in_transit_payments );
4749 =item paydate_monthyear
4751 Returns a two-element list consisting of the month and year of this customer's
4752 paydate (credit card expiration date for CARD customers)
4756 sub paydate_monthyear {
4758 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4760 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4767 =item invoicing_list [ ARRAYREF ]
4769 If an arguement is given, sets these email addresses as invoice recipients
4770 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4771 (except as warnings), so use check_invoicing_list first.
4773 Returns a list of email addresses (with svcnum entries expanded).
4775 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4776 check it without disturbing anything by passing nothing.
4778 This interface may change in the future.
4782 sub invoicing_list {
4783 my( $self, $arrayref ) = @_;
4786 my @cust_main_invoice;
4787 if ( $self->custnum ) {
4788 @cust_main_invoice =
4789 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4791 @cust_main_invoice = ();
4793 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4794 #warn $cust_main_invoice->destnum;
4795 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4796 #warn $cust_main_invoice->destnum;
4797 my $error = $cust_main_invoice->delete;
4798 warn $error if $error;
4801 if ( $self->custnum ) {
4802 @cust_main_invoice =
4803 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4805 @cust_main_invoice = ();
4807 my %seen = map { $_->address => 1 } @cust_main_invoice;
4808 foreach my $address ( @{$arrayref} ) {
4809 next if exists $seen{$address} && $seen{$address};
4810 $seen{$address} = 1;
4811 my $cust_main_invoice = new FS::cust_main_invoice ( {
4812 'custnum' => $self->custnum,
4815 my $error = $cust_main_invoice->insert;
4816 warn $error if $error;
4820 if ( $self->custnum ) {
4822 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4829 =item check_invoicing_list ARRAYREF
4831 Checks these arguements as valid input for the invoicing_list method. If there
4832 is an error, returns the error, otherwise returns false.
4836 sub check_invoicing_list {
4837 my( $self, $arrayref ) = @_;
4839 foreach my $address ( @$arrayref ) {
4841 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4842 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4845 my $cust_main_invoice = new FS::cust_main_invoice ( {
4846 'custnum' => $self->custnum,
4849 my $error = $self->custnum
4850 ? $cust_main_invoice->check
4851 : $cust_main_invoice->checkdest
4853 return $error if $error;
4857 return "Email address required"
4858 if $conf->exists('cust_main-require_invoicing_list_email')
4859 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4864 =item set_default_invoicing_list
4866 Sets the invoicing list to all accounts associated with this customer,
4867 overwriting any previous invoicing list.
4871 sub set_default_invoicing_list {
4873 $self->invoicing_list($self->all_emails);
4878 Returns the email addresses of all accounts provisioned for this customer.
4885 foreach my $cust_pkg ( $self->all_pkgs ) {
4886 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4888 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4889 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4891 $list{$_}=1 foreach map { $_->email } @svc_acct;
4896 =item invoicing_list_addpost
4898 Adds postal invoicing to this customer. If this customer is already configured
4899 to receive postal invoices, does nothing.
4903 sub invoicing_list_addpost {
4905 return if grep { $_ eq 'POST' } $self->invoicing_list;
4906 my @invoicing_list = $self->invoicing_list;
4907 push @invoicing_list, 'POST';
4908 $self->invoicing_list(\@invoicing_list);
4911 =item invoicing_list_emailonly
4913 Returns the list of email invoice recipients (invoicing_list without non-email
4914 destinations such as POST and FAX).
4918 sub invoicing_list_emailonly {
4920 warn "$me invoicing_list_emailonly called"
4922 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4925 =item invoicing_list_emailonly_scalar
4927 Returns the list of email invoice recipients (invoicing_list without non-email
4928 destinations such as POST and FAX) as a comma-separated scalar.
4932 sub invoicing_list_emailonly_scalar {
4934 warn "$me invoicing_list_emailonly_scalar called"
4936 join(', ', $self->invoicing_list_emailonly);
4939 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4941 Returns an array of customers referred by this customer (referral_custnum set
4942 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4943 customers referred by customers referred by this customer and so on, inclusive.
4944 The default behavior is DEPTH 1 (no recursion).
4948 sub referral_cust_main {
4950 my $depth = @_ ? shift : 1;
4951 my $exclude = @_ ? shift : {};
4954 map { $exclude->{$_->custnum}++; $_; }
4955 grep { ! $exclude->{ $_->custnum } }
4956 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4960 map { $_->referral_cust_main($depth-1, $exclude) }
4967 =item referral_cust_main_ncancelled
4969 Same as referral_cust_main, except only returns customers with uncancelled
4974 sub referral_cust_main_ncancelled {
4976 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4979 =item referral_cust_pkg [ DEPTH ]
4981 Like referral_cust_main, except returns a flat list of all unsuspended (and
4982 uncancelled) packages for each customer. The number of items in this list may
4983 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4987 sub referral_cust_pkg {
4989 my $depth = @_ ? shift : 1;
4991 map { $_->unsuspended_pkgs }
4992 grep { $_->unsuspended_pkgs }
4993 $self->referral_cust_main($depth);
4996 =item referring_cust_main
4998 Returns the single cust_main record for the customer who referred this customer
4999 (referral_custnum), or false.
5003 sub referring_cust_main {
5005 return '' unless $self->referral_custnum;
5006 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
5009 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
5011 Applies a credit to this customer. If there is an error, returns the error,
5012 otherwise returns false.
5014 REASON can be a text string, an FS::reason object, or a scalar reference to
5015 a reasonnum. If a text string, it will be automatically inserted as a new
5016 reason, and a 'reason_type' option must be passed to indicate the
5017 FS::reason_type for the new reason.
5019 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
5021 Any other options are passed to FS::cust_credit::insert.
5026 my( $self, $amount, $reason, %options ) = @_;
5028 my $cust_credit = new FS::cust_credit {
5029 'custnum' => $self->custnum,
5030 'amount' => $amount,
5033 if ( ref($reason) ) {
5035 if ( ref($reason) eq 'SCALAR' ) {
5036 $cust_credit->reasonnum( $$reason );
5038 $cust_credit->reasonnum( $reason->reasonnum );
5042 $cust_credit->set('reason', $reason)
5045 $cust_credit->addlinfo( delete $options{'addlinfo'} )
5046 if exists($options{'addlinfo'});
5048 $cust_credit->insert(%options);
5052 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
5054 Creates a one-time charge for this customer. If there is an error, returns
5055 the error, otherwise returns false.
5061 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
5062 my ( $taxproduct, $override );
5063 if ( ref( $_[0] ) ) {
5064 $amount = $_[0]->{amount};
5065 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
5066 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
5067 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
5068 : '$'. sprintf("%.2f",$amount);
5069 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
5070 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
5071 $additional = $_[0]->{additional};
5072 $taxproduct = $_[0]->{taxproductnum};
5073 $override = { '' => $_[0]->{tax_override} };
5077 $pkg = @_ ? shift : 'One-time charge';
5078 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
5079 $taxclass = @_ ? shift : '';
5083 local $SIG{HUP} = 'IGNORE';
5084 local $SIG{INT} = 'IGNORE';
5085 local $SIG{QUIT} = 'IGNORE';
5086 local $SIG{TERM} = 'IGNORE';
5087 local $SIG{TSTP} = 'IGNORE';
5088 local $SIG{PIPE} = 'IGNORE';
5090 my $oldAutoCommit = $FS::UID::AutoCommit;
5091 local $FS::UID::AutoCommit = 0;
5094 my $part_pkg = new FS::part_pkg ( {
5096 'comment' => $comment,
5100 'classnum' => $classnum ? $classnum : '',
5101 'taxclass' => $taxclass,
5102 'taxproductnum' => $taxproduct,
5105 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
5106 ( 0 .. @$additional - 1 )
5108 'additional_count' => scalar(@$additional),
5109 'setup_fee' => $amount,
5112 my $error = $part_pkg->insert( options => \%options,
5113 tax_overrides => $override,
5116 $dbh->rollback if $oldAutoCommit;
5120 my $pkgpart = $part_pkg->pkgpart;
5121 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
5122 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
5123 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
5124 $error = $type_pkgs->insert;
5126 $dbh->rollback if $oldAutoCommit;
5131 my $cust_pkg = new FS::cust_pkg ( {
5132 'custnum' => $self->custnum,
5133 'pkgpart' => $pkgpart,
5134 'quantity' => $quantity,
5137 $error = $cust_pkg->insert;
5139 $dbh->rollback if $oldAutoCommit;
5143 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5148 #=item charge_postal_fee
5150 #Applies a one time charge this customer. If there is an error,
5151 #returns the error, returns the cust_pkg charge object or false
5152 #if there was no charge.
5156 # This should be a customer event. For that to work requires that bill
5157 # also be a customer event.
5159 sub charge_postal_fee {
5162 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
5163 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
5165 my $cust_pkg = new FS::cust_pkg ( {
5166 'custnum' => $self->custnum,
5167 'pkgpart' => $pkgpart,
5171 my $error = $cust_pkg->insert;
5172 $error ? $error : $cust_pkg;
5177 Returns all the invoices (see L<FS::cust_bill>) for this customer.
5183 sort { $a->_date <=> $b->_date }
5184 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
5187 =item open_cust_bill
5189 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
5194 sub open_cust_bill {
5196 grep { $_->owed > 0 } $self->cust_bill;
5201 Returns all the credits (see L<FS::cust_credit>) for this customer.
5207 sort { $a->_date <=> $b->_date }
5208 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
5213 Returns all the payments (see L<FS::cust_pay>) for this customer.
5219 sort { $a->_date <=> $b->_date }
5220 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
5225 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
5231 sort { $a->_date <=> $b->_date }
5232 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
5235 =item cust_pay_batch
5237 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
5241 sub cust_pay_batch {
5243 sort { $a->_date <=> $b->_date }
5244 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
5249 Returns all the refunds (see L<FS::cust_refund>) for this customer.
5255 sort { $a->_date <=> $b->_date }
5256 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
5259 =item display_custnum
5261 Returns the displayed customer number for this customer: agent_custid if
5262 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
5266 sub display_custnum {
5268 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
5269 return $self->agent_custid;
5271 return $self->custnum;
5277 Returns a name string for this customer, either "Company (Last, First)" or
5284 my $name = $self->contact;
5285 $name = $self->company. " ($name)" if $self->company;
5291 Returns a name string for this (service/shipping) contact, either
5292 "Company (Last, First)" or "Last, First".
5298 if ( $self->get('ship_last') ) {
5299 my $name = $self->ship_contact;
5300 $name = $self->ship_company. " ($name)" if $self->ship_company;
5309 Returns this customer's full (billing) contact name only, "Last, First"
5315 $self->get('last'). ', '. $self->first;
5320 Returns this customer's full (shipping) contact name only, "Last, First"
5326 $self->get('ship_last')
5327 ? $self->get('ship_last'). ', '. $self->ship_first
5333 Returns this customer's full country name
5339 code2country($self->country);
5342 =item geocode DATA_VENDOR
5344 Returns a value for the customer location as encoded by DATA_VENDOR.
5345 Currently this only makes sense for "CCH" as DATA_VENDOR.
5350 my ($self, $data_vendor) = (shift, shift); #always cch for now
5352 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
5353 return $geocode if $geocode;
5355 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5359 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5360 if $self->country eq 'US';
5362 #CCH specific location stuff
5363 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5365 my @cust_tax_location =
5367 'table' => 'cust_tax_location',
5368 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5369 'extra_sql' => $extra_sql,
5370 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
5373 $geocode = $cust_tax_location[0]->geocode
5374 if scalar(@cust_tax_location);
5383 Returns a status string for this customer, currently:
5387 =item prospect - No packages have ever been ordered
5389 =item active - One or more recurring packages is active
5391 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5393 =item suspended - All non-cancelled recurring packages are suspended
5395 =item cancelled - All recurring packages are cancelled
5401 sub status { shift->cust_status(@_); }
5405 for my $status (qw( prospect active inactive suspended cancelled )) {
5406 my $method = $status.'_sql';
5407 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5408 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5409 $sth->execute( ($self->custnum) x $numnum )
5410 or die "Error executing 'SELECT $sql': ". $sth->errstr;
5411 return $status if $sth->fetchrow_arrayref->[0];
5415 =item ucfirst_cust_status
5417 =item ucfirst_status
5419 Returns the status with the first character capitalized.
5423 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5425 sub ucfirst_cust_status {
5427 ucfirst($self->cust_status);
5432 Returns a hex triplet color string for this customer's status.
5436 use vars qw(%statuscolor);
5437 tie %statuscolor, 'Tie::IxHash',
5438 'prospect' => '7e0079', #'000000', #black? naw, purple
5439 'active' => '00CC00', #green
5440 'inactive' => '0000CC', #blue
5441 'suspended' => 'FF9900', #yellow
5442 'cancelled' => 'FF0000', #red
5445 sub statuscolor { shift->cust_statuscolor(@_); }
5447 sub cust_statuscolor {
5449 $statuscolor{$self->cust_status};
5454 Returns an array of hashes representing the customer's RT tickets.
5461 my $num = $conf->config('cust_main-max_tickets') || 10;
5464 unless ( $conf->config('ticket_system-custom_priority_field') ) {
5466 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5470 foreach my $priority (
5471 $conf->config('ticket_system-custom_priority_field-values'), ''
5473 last if scalar(@tickets) >= $num;
5475 @{ FS::TicketSystem->customer_tickets( $self->custnum,
5476 $num - scalar(@tickets),
5485 # Return services representing svc_accts in customer support packages
5486 sub support_services {
5488 my %packages = map { $_ => 1 } $conf->config('support_packages');
5490 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5491 grep { $_->part_svc->svcdb eq 'svc_acct' }
5492 map { $_->cust_svc }
5493 grep { exists $packages{ $_->pkgpart } }
5494 $self->ncancelled_pkgs;
5500 =head1 CLASS METHODS
5506 Class method that returns the list of possible status strings for customers
5507 (see L<the status method|/status>). For example:
5509 @statuses = FS::cust_main->statuses();
5514 #my $self = shift; #could be class...
5520 Returns an SQL expression identifying prospective cust_main records (customers
5521 with no packages ever ordered)
5525 use vars qw($select_count_pkgs);
5526 $select_count_pkgs =
5527 "SELECT COUNT(*) FROM cust_pkg
5528 WHERE cust_pkg.custnum = cust_main.custnum";
5530 sub select_count_pkgs_sql {
5534 sub prospect_sql { "
5535 0 = ( $select_count_pkgs )
5540 Returns an SQL expression identifying active cust_main records (customers with
5541 active recurring packages).
5546 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5552 Returns an SQL expression identifying inactive cust_main records (customers with
5553 no active recurring packages, but otherwise unsuspended/uncancelled).
5557 sub inactive_sql { "
5558 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5560 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5566 Returns an SQL expression identifying suspended cust_main records.
5571 sub suspended_sql { susp_sql(@_); }
5573 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5575 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5581 Returns an SQL expression identifying cancelled cust_main records.
5585 sub cancelled_sql { cancel_sql(@_); }
5588 my $recurring_sql = FS::cust_pkg->recurring_sql;
5589 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5592 0 < ( $select_count_pkgs )
5593 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
5594 AND 0 = ( $select_count_pkgs AND $recurring_sql
5595 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5597 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5603 =item uncancelled_sql
5605 Returns an SQL expression identifying un-cancelled cust_main records.
5609 sub uncancelled_sql { uncancel_sql(@_); }
5610 sub uncancel_sql { "
5611 ( 0 < ( $select_count_pkgs
5612 AND ( cust_pkg.cancel IS NULL
5613 OR cust_pkg.cancel = 0
5616 OR 0 = ( $select_count_pkgs )
5622 Returns an SQL fragment to retreive the balance.
5627 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5628 WHERE cust_bill.custnum = cust_main.custnum )
5629 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5630 WHERE cust_pay.custnum = cust_main.custnum )
5631 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5632 WHERE cust_credit.custnum = cust_main.custnum )
5633 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5634 WHERE cust_refund.custnum = cust_main.custnum )
5637 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5639 Returns an SQL fragment to retreive the balance for this customer, only
5640 considering invoices with date earlier than START_TIME, and optionally not
5641 later than END_TIME (total_owed_date minus total_unapplied_credits minus
5642 total_unapplied_payments).
5644 Times are specified as SQL fragments or numeric
5645 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5646 L<Date::Parse> for conversion functions. The empty string can be passed
5647 to disable that time constraint completely.
5649 Available options are:
5653 =item unapplied_date
5655 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)
5660 set to true to remove all customer comparison clauses, for totals
5665 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5670 JOIN clause (typically used with the total option)
5676 sub balance_date_sql {
5677 my( $class, $start, $end, %opt ) = @_;
5679 my $owed = FS::cust_bill->owed_sql;
5680 my $unapp_refund = FS::cust_refund->unapplied_sql;
5681 my $unapp_credit = FS::cust_credit->unapplied_sql;
5682 my $unapp_pay = FS::cust_pay->unapplied_sql;
5684 my $j = $opt{'join'} || '';
5686 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5687 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5688 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5689 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5691 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5692 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5693 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5694 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5699 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5701 Helper method for balance_date_sql; name (and usage) subject to change
5702 (suggestions welcome).
5704 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5705 cust_refund, cust_credit or cust_pay).
5707 If TABLE is "cust_bill" or the unapplied_date option is true, only
5708 considers records with date earlier than START_TIME, and optionally not
5709 later than END_TIME .
5713 sub _money_table_where {
5714 my( $class, $table, $start, $end, %opt ) = @_;
5717 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5718 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5719 push @where, "$table._date <= $start" if defined($start) && length($start);
5720 push @where, "$table._date > $end" if defined($end) && length($end);
5722 push @where, @{$opt{'where'}} if $opt{'where'};
5723 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5729 =item search_sql HASHREF
5733 Returns a qsearch hash expression to search for parameters specified in HREF.
5734 Valid parameters are
5742 =item cancelled_pkgs
5748 listref of start date, end date
5754 =item current_balance
5756 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5760 =item flattened_pkgs
5769 my ($class, $params) = @_;
5780 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5782 "cust_main.agentnum = $1";
5789 #prospect active inactive suspended cancelled
5790 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5791 my $method = $params->{'status'}. '_sql';
5792 #push @where, $class->$method();
5793 push @where, FS::cust_main->$method();
5797 # parse cancelled package checkbox
5802 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5803 unless $params->{'cancelled_pkgs'};
5809 foreach my $field (qw( signupdate )) {
5811 next unless exists($params->{$field});
5813 my($beginning, $ending) = @{$params->{$field}};
5816 "cust_main.$field IS NOT NULL",
5817 "cust_main.$field >= $beginning",
5818 "cust_main.$field <= $ending";
5820 $orderby ||= "ORDER BY cust_main.$field";
5828 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5830 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5837 #my $balance_sql = $class->balance_sql();
5838 my $balance_sql = FS::cust_main->balance_sql();
5840 push @where, map { s/current_balance/$balance_sql/; $_ }
5841 @{ $params->{'current_balance'} };
5847 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
5849 "cust_main.custbatch = '$1'";
5853 # setup queries, subs, etc. for the search
5856 $orderby ||= 'ORDER BY custnum';
5858 # here is the agent virtualization
5859 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5861 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5863 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5865 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5867 my $select = join(', ',
5868 'cust_main.custnum',
5869 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5872 my(@extra_headers) = ();
5873 my(@extra_fields) = ();
5875 if ($params->{'flattened_pkgs'}) {
5877 if ($dbh->{Driver}->{Name} eq 'Pg') {
5879 $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";
5881 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5882 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5883 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5885 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5886 "omitting packing information from report.";
5889 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";
5891 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5892 $sth->execute() or die $sth->errstr;
5893 my $headerrow = $sth->fetchrow_arrayref;
5894 my $headercount = $headerrow ? $headerrow->[0] : 0;
5895 while($headercount) {
5896 unshift @extra_headers, "Package ". $headercount;
5897 unshift @extra_fields, eval q!sub {my $c = shift;
5898 my @a = split '\|', $c->magic;
5899 my $p = $a[!.--$headercount. q!];
5907 'table' => 'cust_main',
5908 'select' => $select,
5910 'extra_sql' => $extra_sql,
5911 'order_by' => $orderby,
5912 'count_query' => $count_query,
5913 'extra_headers' => \@extra_headers,
5914 'extra_fields' => \@extra_fields,
5919 =item email_search_sql HASHREF
5923 Emails a notice to the specified customers.
5925 Valid parameters are those of the L<search_sql> method, plus the following:
5947 Optional job queue job for status updates.
5951 Returns an error message, or false for success.
5953 If an error occurs during any email, stops the enture send and returns that
5954 error. Presumably if you're getting SMTP errors aborting is better than
5955 retrying everything.
5959 sub email_search_sql {
5960 my($class, $params) = @_;
5962 my $from = delete $params->{from};
5963 my $subject = delete $params->{subject};
5964 my $html_body = delete $params->{html_body};
5965 my $text_body = delete $params->{text_body};
5967 my $job = delete $params->{'job'};
5969 my $sql_query = $class->search_sql($params);
5971 my $count_query = delete($sql_query->{'count_query'});
5972 my $count_sth = dbh->prepare($count_query)
5973 or die "Error preparing $count_query: ". dbh->errstr;
5975 or die "Error executing $count_query: ". $count_sth->errstr;
5976 my $count_arrayref = $count_sth->fetchrow_arrayref;
5977 my $num_cust = $count_arrayref->[0];
5979 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5980 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5983 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5985 #eventually order+limit magic to reduce memory use?
5986 foreach my $cust_main ( qsearch($sql_query) ) {
5988 my $to = $cust_main->invoicing_list_emailonly_scalar;
5991 my $error = send_email(
5995 'subject' => $subject,
5996 'html_body' => $html_body,
5997 'text_body' => $text_body,
6000 return $error if $error;
6002 if ( $job ) { #progressbar foo
6004 if ( time - $min_sec > $last ) {
6005 my $error = $job->update_statustext(
6006 int( 100 * $num / $num_cust )
6008 die $error if $error;
6018 use Storable qw(thaw);
6021 sub process_email_search_sql {
6023 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
6025 my $param = thaw(decode_base64(shift));
6026 warn Dumper($param) if $DEBUG;
6028 $param->{'job'} = $job;
6030 my $error = FS::cust_main->email_search_sql( $param );
6031 die $error if $error;
6035 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
6037 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
6038 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
6039 appropriate ship_ field is also searched).
6041 Additional options are the same as FS::Record::qsearch
6046 my( $self, $fuzzy, $hash, @opt) = @_;
6051 check_and_rebuild_fuzzyfiles();
6052 foreach my $field ( keys %$fuzzy ) {
6054 my $all = $self->all_X($field);
6055 next unless scalar(@$all);
6058 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
6061 foreach ( keys %match ) {
6062 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
6063 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
6066 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
6069 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
6071 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
6079 Returns a masked version of the named field
6084 my ($self,$field) = @_;
6088 'x'x(length($self->getfield($field))-4).
6089 substr($self->getfield($field), (length($self->getfield($field))-4));
6099 =item smart_search OPTION => VALUE ...
6101 Accepts the following options: I<search>, the string to search for. The string
6102 will be searched for as a customer number, phone number, name or company name,
6103 as an exact, or, in some cases, a substring or fuzzy match (see the source code
6104 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
6105 skip fuzzy matching when an exact match is found.
6107 Any additional options are treated as an additional qualifier on the search
6110 Returns a (possibly empty) array of FS::cust_main objects.
6117 #here is the agent virtualization
6118 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6122 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
6123 my $search = delete $options{'search'};
6124 ( my $alphanum_search = $search ) =~ s/\W//g;
6126 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
6128 #false laziness w/Record::ut_phone
6129 my $phonen = "$1-$2-$3";
6130 $phonen .= " x$4" if $4;
6132 push @cust_main, qsearch( {
6133 'table' => 'cust_main',
6134 'hashref' => { %options },
6135 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
6137 join(' OR ', map "$_ = '$phonen'",
6138 qw( daytime night fax
6139 ship_daytime ship_night ship_fax )
6142 " AND $agentnums_sql", #agent virtualization
6145 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
6146 #try looking for matches with extensions unless one was specified
6148 push @cust_main, qsearch( {
6149 'table' => 'cust_main',
6150 'hashref' => { %options },
6151 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
6153 join(' OR ', map "$_ LIKE '$phonen\%'",
6155 ship_daytime ship_night )
6158 " AND $agentnums_sql", #agent virtualization
6163 # custnum search (also try agent_custid), with some tweaking options if your
6164 # legacy cust "numbers" have letters
6167 if ( $search =~ /^\s*(\d+)\s*$/
6168 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
6169 && $search =~ /^\s*(\w\w?\d+)\s*$/
6176 if ( $num <= 2147483647 ) { #need a bigint custnum? wow.
6177 push @cust_main, qsearch( {
6178 'table' => 'cust_main',
6179 'hashref' => { 'custnum' => $num, %options },
6180 'extra_sql' => " AND $agentnums_sql", #agent virtualization
6184 push @cust_main, qsearch( {
6185 'table' => 'cust_main',
6186 'hashref' => { 'agent_custid' => $num, %options },
6187 'extra_sql' => " AND $agentnums_sql", #agent virtualization
6190 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
6192 my($company, $last, $first) = ( $1, $2, $3 );
6194 # "Company (Last, First)"
6195 #this is probably something a browser remembered,
6196 #so just do an exact search
6198 foreach my $prefix ( '', 'ship_' ) {
6199 push @cust_main, qsearch( {
6200 'table' => 'cust_main',
6201 'hashref' => { $prefix.'first' => $first,
6202 $prefix.'last' => $last,
6203 $prefix.'company' => $company,
6206 'extra_sql' => " AND $agentnums_sql",
6210 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
6211 # try (ship_){last,company}
6215 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
6216 # # full strings the browser remembers won't work
6217 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
6219 use Lingua::EN::NameParse;
6220 my $NameParse = new Lingua::EN::NameParse(
6222 allow_reversed => 1,
6225 my($last, $first) = ( '', '' );
6226 #maybe disable this too and just rely on NameParse?
6227 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
6229 ($last, $first) = ( $1, $2 );
6231 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
6232 } elsif ( ! $NameParse->parse($value) ) {
6234 my %name = $NameParse->components;
6235 $first = $name{'given_name_1'};
6236 $last = $name{'surname_1'};
6240 if ( $first && $last ) {
6242 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
6245 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6247 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
6248 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
6251 push @cust_main, qsearch( {
6252 'table' => 'cust_main',
6253 'hashref' => \%options,
6254 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6257 # or it just be something that was typed in... (try that in a sec)
6261 my $q_value = dbh->quote($value);
6264 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6265 $sql .= " ( LOWER(last) = $q_value
6266 OR LOWER(company) = $q_value
6267 OR LOWER(ship_last) = $q_value
6268 OR LOWER(ship_company) = $q_value
6271 push @cust_main, qsearch( {
6272 'table' => 'cust_main',
6273 'hashref' => \%options,
6274 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6277 #no exact match, trying substring/fuzzy
6278 #always do substring & fuzzy (unless they're explicity config'ed off)
6279 #getting complaints searches are not returning enough
6280 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
6282 #still some false laziness w/search_sql (was search/cust_main.cgi)
6287 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
6288 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
6291 if ( $first && $last ) {
6294 { 'first' => { op=>'ILIKE', value=>"%$first%" },
6295 'last' => { op=>'ILIKE', value=>"%$last%" },
6297 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
6298 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
6305 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
6306 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
6310 foreach my $hashref ( @hashrefs ) {
6312 push @cust_main, qsearch( {
6313 'table' => 'cust_main',
6314 'hashref' => { %$hashref,
6317 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6326 " AND $agentnums_sql", #extra_sql #agent virtualization
6329 if ( $first && $last ) {
6330 push @cust_main, FS::cust_main->fuzzy_search(
6331 { 'last' => $last, #fuzzy hashref
6332 'first' => $first }, #
6336 foreach my $field ( 'last', 'company' ) {
6338 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6343 #eliminate duplicates
6345 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6355 Accepts the following options: I<email>, the email address to search for. The
6356 email address will be searched for as an email invoice destination and as an
6359 #Any additional options are treated as an additional qualifier on the search
6360 #(i.e. I<agentnum>).
6362 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6372 my $email = delete $options{'email'};
6374 #we're only being used by RT at the moment... no agent virtualization yet
6375 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6379 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6381 my ( $user, $domain ) = ( $1, $2 );
6383 warn "$me smart_search: searching for $user in domain $domain"
6389 'table' => 'cust_main_invoice',
6390 'hashref' => { 'dest' => $email },
6397 map $_->cust_svc->cust_pkg,
6399 'table' => 'svc_acct',
6400 'hashref' => { 'username' => $user, },
6402 'AND ( SELECT domain FROM svc_domain
6403 WHERE svc_acct.domsvc = svc_domain.svcnum
6404 ) = '. dbh->quote($domain),
6410 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6412 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6419 =item check_and_rebuild_fuzzyfiles
6423 use vars qw(@fuzzyfields);
6424 @fuzzyfields = ( 'last', 'first', 'company' );
6426 sub check_and_rebuild_fuzzyfiles {
6427 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6428 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6431 =item rebuild_fuzzyfiles
6435 sub rebuild_fuzzyfiles {
6437 use Fcntl qw(:flock);
6439 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6440 mkdir $dir, 0700 unless -d $dir;
6442 foreach my $fuzzy ( @fuzzyfields ) {
6444 open(LOCK,">>$dir/cust_main.$fuzzy")
6445 or die "can't open $dir/cust_main.$fuzzy: $!";
6447 or die "can't lock $dir/cust_main.$fuzzy: $!";
6449 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6450 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6452 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6453 my $sth = dbh->prepare("SELECT $field FROM cust_main".
6454 " WHERE $field != '' AND $field IS NOT NULL");
6455 $sth->execute or die $sth->errstr;
6457 while ( my $row = $sth->fetchrow_arrayref ) {
6458 print CACHE $row->[0]. "\n";
6463 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6465 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6476 my( $self, $field ) = @_;
6477 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6478 open(CACHE,"<$dir/cust_main.$field")
6479 or die "can't open $dir/cust_main.$field: $!";
6480 my @array = map { chomp; $_; } <CACHE>;
6485 =item append_fuzzyfiles LASTNAME COMPANY
6489 sub append_fuzzyfiles {
6490 #my( $first, $last, $company ) = @_;
6492 &check_and_rebuild_fuzzyfiles;
6494 use Fcntl qw(:flock);
6496 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6498 foreach my $field (qw( first last company )) {
6503 open(CACHE,">>$dir/cust_main.$field")
6504 or die "can't open $dir/cust_main.$field: $!";
6505 flock(CACHE,LOCK_EX)
6506 or die "can't lock $dir/cust_main.$field: $!";
6508 print CACHE "$value\n";
6510 flock(CACHE,LOCK_UN)
6511 or die "can't unlock $dir/cust_main.$field: $!";
6526 #warn join('-',keys %$param);
6527 my $fh = $param->{filehandle};
6528 my @fields = @{$param->{fields}};
6530 eval "use Text::CSV_XS;";
6533 my $csv = new Text::CSV_XS;
6540 local $SIG{HUP} = 'IGNORE';
6541 local $SIG{INT} = 'IGNORE';
6542 local $SIG{QUIT} = 'IGNORE';
6543 local $SIG{TERM} = 'IGNORE';
6544 local $SIG{TSTP} = 'IGNORE';
6545 local $SIG{PIPE} = 'IGNORE';
6547 my $oldAutoCommit = $FS::UID::AutoCommit;
6548 local $FS::UID::AutoCommit = 0;
6551 #while ( $columns = $csv->getline($fh) ) {
6553 while ( defined($line=<$fh>) ) {
6555 $csv->parse($line) or do {
6556 $dbh->rollback if $oldAutoCommit;
6557 return "can't parse: ". $csv->error_input();
6560 my @columns = $csv->fields();
6561 #warn join('-',@columns);
6564 foreach my $field ( @fields ) {
6565 $row{$field} = shift @columns;
6568 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6569 unless ( $cust_main ) {
6570 $dbh->rollback if $oldAutoCommit;
6571 return "unknown custnum $row{'custnum'}";
6574 if ( $row{'amount'} > 0 ) {
6575 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6577 $dbh->rollback if $oldAutoCommit;
6581 } elsif ( $row{'amount'} < 0 ) {
6582 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6585 $dbh->rollback if $oldAutoCommit;
6595 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6597 return "Empty file!" unless $imported;
6603 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6605 Sends a templated email notification to the customer (see L<Text::Template>).
6607 OPTIONS is a hash and may include
6609 I<from> - the email sender (default is invoice_from)
6611 I<to> - comma-separated scalar or arrayref of recipients
6612 (default is invoicing_list)
6614 I<subject> - The subject line of the sent email notification
6615 (default is "Notice from company_name")
6617 I<extra_fields> - a hashref of name/value pairs which will be substituted
6620 The following variables are vavailable in the template.
6622 I<$first> - the customer first name
6623 I<$last> - the customer last name
6624 I<$company> - the customer company
6625 I<$payby> - a description of the method of payment for the customer
6626 # would be nice to use FS::payby::shortname
6627 I<$payinfo> - the account information used to collect for this customer
6628 I<$expdate> - the expiration of the customer payment in seconds from epoch
6633 my ($customer, $template, %options) = @_;
6635 return unless $conf->exists($template);
6637 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6638 $from = $options{from} if exists($options{from});
6640 my $to = join(',', $customer->invoicing_list_emailonly);
6641 $to = $options{to} if exists($options{to});
6643 my $subject = "Notice from " . $conf->config('company_name')
6644 if $conf->exists('company_name');
6645 $subject = $options{subject} if exists($options{subject});
6647 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6648 SOURCE => [ map "$_\n",
6649 $conf->config($template)]
6651 or die "can't create new Text::Template object: Text::Template::ERROR";
6652 $notify_template->compile()
6653 or die "can't compile template: Text::Template::ERROR";
6655 $FS::notify_template::_template::company_name = $conf->config('company_name');
6656 $FS::notify_template::_template::company_address =
6657 join("\n", $conf->config('company_address') ). "\n";
6659 my $paydate = $customer->paydate || '2037-12-31';
6660 $FS::notify_template::_template::first = $customer->first;
6661 $FS::notify_template::_template::last = $customer->last;
6662 $FS::notify_template::_template::company = $customer->company;
6663 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6664 my $payby = $customer->payby;
6665 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6666 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6668 #credit cards expire at the end of the month/year of their exp date
6669 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6670 $FS::notify_template::_template::payby = 'credit card';
6671 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6672 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6674 }elsif ($payby eq 'COMP') {
6675 $FS::notify_template::_template::payby = 'complimentary account';
6677 $FS::notify_template::_template::payby = 'current method';
6679 $FS::notify_template::_template::expdate = $expire_time;
6681 for (keys %{$options{extra_fields}}){
6683 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6686 send_email(from => $from,
6688 subject => $subject,
6689 body => $notify_template->fill_in( PACKAGE =>
6690 'FS::notify_template::_template' ),
6695 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6697 Generates a templated notification to the customer (see L<Text::Template>).
6699 OPTIONS is a hash and may include
6701 I<extra_fields> - a hashref of name/value pairs which will be substituted
6702 into the template. These values may override values mentioned below
6703 and those from the customer record.
6705 The following variables are available in the template instead of or in addition
6706 to the fields of the customer record.
6708 I<$payby> - a description of the method of payment for the customer
6709 # would be nice to use FS::payby::shortname
6710 I<$payinfo> - the masked account information used to collect for this customer
6711 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6712 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6716 sub generate_letter {
6717 my ($self, $template, %options) = @_;
6719 return unless $conf->exists($template);
6721 my $letter_template = new Text::Template
6723 SOURCE => [ map "$_\n", $conf->config($template)],
6724 DELIMITERS => [ '[@--', '--@]' ],
6726 or die "can't create new Text::Template object: Text::Template::ERROR";
6728 $letter_template->compile()
6729 or die "can't compile template: Text::Template::ERROR";
6731 my %letter_data = map { $_ => $self->$_ } $self->fields;
6732 $letter_data{payinfo} = $self->mask_payinfo;
6734 #my $paydate = $self->paydate || '2037-12-31';
6735 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6737 my $payby = $self->payby;
6738 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6739 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6741 #credit cards expire at the end of the month/year of their exp date
6742 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6743 $letter_data{payby} = 'credit card';
6744 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6745 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6747 }elsif ($payby eq 'COMP') {
6748 $letter_data{payby} = 'complimentary account';
6750 $letter_data{payby} = 'current method';
6752 $letter_data{expdate} = $expire_time;
6754 for (keys %{$options{extra_fields}}){
6755 $letter_data{$_} = $options{extra_fields}->{$_};
6758 unless(exists($letter_data{returnaddress})){
6759 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6760 $self->agent_template)
6762 if ( length($retadd) ) {
6763 $letter_data{returnaddress} = $retadd;
6764 } elsif ( grep /\S/, $conf->config('company_address') ) {
6765 $letter_data{returnaddress} =
6766 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6767 $conf->config('company_address')
6770 $letter_data{returnaddress} = '~';
6774 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6776 $letter_data{company_name} = $conf->config('company_name');
6778 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
6779 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6783 ) or die "can't open temp file: $!\n";
6785 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6787 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6791 =item print_ps TEMPLATE
6793 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6799 my $file = $self->generate_letter(@_);
6800 FS::Misc::generate_ps($file);
6803 =item print TEMPLATE
6805 Prints the filled in template.
6807 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6811 sub queueable_print {
6814 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6815 or die "invalid customer number: " . $opt{custvnum};
6817 my $error = $self->print( $opt{template} );
6818 die $error if $error;
6822 my ($self, $template) = (shift, shift);
6823 do_print [ $self->print_ps($template) ];
6826 sub agent_template {
6828 $self->_agent_plandata('agent_templatename');
6831 sub agent_invoice_from {
6833 $self->_agent_plandata('agent_invoice_from');
6836 sub _agent_plandata {
6837 my( $self, $option ) = @_;
6839 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6840 #agent-specific Conf
6842 use FS::part_event::Condition;
6844 my $agentnum = $self->agentnum;
6847 if ( driver_name =~ /^Pg/i ) {
6849 } elsif ( driver_name =~ /^mysql/i ) {
6852 die "don't know how to use regular expressions in ". driver_name. " databases";
6855 my $part_event_option =
6857 'select' => 'part_event_option.*',
6858 'table' => 'part_event_option',
6860 LEFT JOIN part_event USING ( eventpart )
6861 LEFT JOIN part_event_option AS peo_agentnum
6862 ON ( part_event.eventpart = peo_agentnum.eventpart
6863 AND peo_agentnum.optionname = 'agentnum'
6864 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6866 LEFT JOIN part_event_option AS peo_cust_bill_age
6867 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6868 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6871 #'hashref' => { 'optionname' => $option },
6872 #'hashref' => { 'part_event_option.optionname' => $option },
6874 " WHERE part_event_option.optionname = ". dbh->quote($option).
6875 " AND action = 'cust_bill_send_agent' ".
6876 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6877 " AND peo_agentnum.optionname = 'agentnum' ".
6878 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
6880 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6882 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6884 , part_event.weight".
6888 unless ( $part_event_option ) {
6889 return $self->agent->invoice_template || ''
6890 if $option eq 'agent_templatename';
6894 $part_event_option->optionvalue;
6899 ## actual sub, not a method, designed to be called from the queue.
6900 ## sets up the customer, and calls the bill_and_collect
6901 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6902 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6903 $cust_main->bill_and_collect(
6914 The delete method should possibly take an FS::cust_main object reference
6915 instead of a scalar customer number.
6917 Bill and collect options should probably be passed as references instead of a
6920 There should probably be a configuration file with a list of allowed credit
6923 No multiple currency support (probably a larger project than just this module).
6925 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6927 Birthdates rely on negative epoch values.
6929 The payby for card/check batches is broken. With mixed batching, bad
6932 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
6936 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6937 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6938 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.