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_nocheck);
15 use Digest::MD5 qw(md5_base64);
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;
31 use FS::cust_pay_pending;
32 use FS::cust_pay_void;
33 use FS::cust_pay_batch;
36 use FS::part_referral;
37 use FS::cust_main_county;
39 use FS::cust_main_invoice;
40 use FS::cust_credit_bill;
41 use FS::cust_bill_pay;
42 use FS::prepay_credit;
46 use FS::part_event_condition;
49 use FS::payment_gateway;
50 use FS::agent_payment_gateway;
52 use FS::payinfo_Mixin;
55 @ISA = qw( FS::payinfo_Mixin FS::Record );
57 @EXPORT_OK = qw( smart_search );
59 $realtime_bop_decline_quiet = 0;
61 # 1 is mostly method/subroutine entry and options
62 # 2 traces progress of some operations
63 # 3 is even more information including possibly sensitive data
65 $me = '[FS::cust_main]';
69 $ignore_expired_card = 0;
71 @encrypted_fields = ('payinfo', 'paycvv');
72 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
74 #ask FS::UID to run this stuff for us later
75 #$FS::UID::callback{'FS::cust_main'} = sub {
76 install_callback FS::UID sub {
78 #yes, need it for stuff below (prolly should be cached)
83 my ( $hashref, $cache ) = @_;
84 if ( exists $hashref->{'pkgnum'} ) {
85 #@{ $self->{'_pkgnum'} } = ();
86 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
87 $self->{'_pkgnum'} = $subcache;
88 #push @{ $self->{'_pkgnum'} },
89 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
95 FS::cust_main - Object methods for cust_main records
101 $record = new FS::cust_main \%hash;
102 $record = new FS::cust_main { 'column' => 'value' };
104 $error = $record->insert;
106 $error = $new_record->replace($old_record);
108 $error = $record->delete;
110 $error = $record->check;
112 @cust_pkg = $record->all_pkgs;
114 @cust_pkg = $record->ncancelled_pkgs;
116 @cust_pkg = $record->suspended_pkgs;
118 $error = $record->bill;
119 $error = $record->bill %options;
120 $error = $record->bill 'time' => $time;
122 $error = $record->collect;
123 $error = $record->collect %options;
124 $error = $record->collect 'invoice_time' => $time,
129 An FS::cust_main object represents a customer. FS::cust_main inherits from
130 FS::Record. The following fields are currently supported:
134 =item custnum - primary key (assigned automatically for new customers)
136 =item agentnum - agent (see L<FS::agent>)
138 =item refnum - Advertising source (see L<FS::part_referral>)
144 =item ss - social security number (optional)
146 =item company - (optional)
150 =item address2 - (optional)
154 =item county - (optional, see L<FS::cust_main_county>)
156 =item state - (see L<FS::cust_main_county>)
160 =item country - (see L<FS::cust_main_county>)
162 =item daytime - phone (optional)
164 =item night - phone (optional)
166 =item fax - phone (optional)
168 =item ship_first - name
170 =item ship_last - name
172 =item ship_company - (optional)
176 =item ship_address2 - (optional)
180 =item ship_county - (optional, see L<FS::cust_main_county>)
182 =item ship_state - (see L<FS::cust_main_county>)
186 =item ship_country - (see L<FS::cust_main_county>)
188 =item ship_daytime - phone (optional)
190 =item ship_night - phone (optional)
192 =item ship_fax - phone (optional)
194 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
196 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
198 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
202 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
204 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
206 =item paystart_month - start date month (maestro/solo cards only)
208 =item paystart_year - start date year (maestro/solo cards only)
210 =item payissue - issue number (maestro/solo cards only)
212 =item payname - name on card or billing name
214 =item payip - IP address from which payment information was received
216 =item tax - tax exempt, empty or `Y'
218 =item otaker - order taker (assigned automatically, see L<FS::UID>)
220 =item comments - comments (optional)
222 =item referral_custnum - referring customer number
224 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
234 Creates a new customer. To add the customer to the database, see L<"insert">.
236 Note that this stores the hash reference, not a distinct copy of the hash it
237 points to. You can ask the object for a copy with the I<hash> method.
241 sub table { 'cust_main'; }
243 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
245 Adds this customer to the database. If there is an error, returns the error,
246 otherwise returns false.
248 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
249 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
250 are inserted atomicly, or the transaction is rolled back. Passing an empty
251 hash reference is equivalent to not supplying this parameter. There should be
252 a better explanation of this, but until then, here's an example:
255 tie %hash, 'Tie::RefHash'; #this part is important
257 $cust_pkg => [ $svc_acct ],
260 $cust_main->insert( \%hash );
262 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
263 be set as the invoicing list (see L<"invoicing_list">). Errors return as
264 expected and rollback the entire transaction; it is not necessary to call
265 check_invoicing_list first. The invoicing_list is set after the records in the
266 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
267 invoicing_list destination to the newly-created svc_acct. Here's an example:
269 $cust_main->insert( {}, [ $email, 'POST' ] );
271 Currently available options are: I<depend_jobnum> and I<noexport>.
273 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
274 on the supplied jobnum (they will not run until the specific job completes).
275 This can be used to defer provisioning until some action completes (such
276 as running the customer's credit card successfully).
278 The I<noexport> option is deprecated. If I<noexport> is set true, no
279 provisioning jobs (exports) are scheduled. (You can schedule them later with
280 the B<reexport> method.)
286 my $cust_pkgs = @_ ? shift : {};
287 my $invoicing_list = @_ ? shift : '';
289 warn "$me insert called with options ".
290 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
293 local $SIG{HUP} = 'IGNORE';
294 local $SIG{INT} = 'IGNORE';
295 local $SIG{QUIT} = 'IGNORE';
296 local $SIG{TERM} = 'IGNORE';
297 local $SIG{TSTP} = 'IGNORE';
298 local $SIG{PIPE} = 'IGNORE';
300 my $oldAutoCommit = $FS::UID::AutoCommit;
301 local $FS::UID::AutoCommit = 0;
304 my $prepay_identifier = '';
305 my( $amount, $seconds ) = ( 0, 0 );
307 if ( $self->payby eq 'PREPAY' ) {
309 $self->payby('BILL');
310 $prepay_identifier = $self->payinfo;
313 warn " looking up prepaid card $prepay_identifier\n"
316 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
318 $dbh->rollback if $oldAutoCommit;
319 #return "error applying prepaid card (transaction rolled back): $error";
323 $payby = 'PREP' if $amount;
325 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
328 $self->payby('BILL');
329 $amount = $self->paid;
333 warn " inserting $self\n"
336 $self->signupdate(time) unless $self->signupdate;
338 my $error = $self->SUPER::insert;
340 $dbh->rollback if $oldAutoCommit;
341 #return "inserting cust_main record (transaction rolled back): $error";
345 warn " setting invoicing list\n"
348 if ( $invoicing_list ) {
349 $error = $self->check_invoicing_list( $invoicing_list );
351 $dbh->rollback if $oldAutoCommit;
352 #return "checking invoicing_list (transaction rolled back): $error";
355 $self->invoicing_list( $invoicing_list );
358 if ( $conf->config('cust_main-skeleton_tables')
359 && $conf->config('cust_main-skeleton_custnum') ) {
361 warn " inserting skeleton records\n"
364 my $error = $self->start_copy_skel;
366 $dbh->rollback if $oldAutoCommit;
372 warn " ordering packages\n"
375 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
377 $dbh->rollback if $oldAutoCommit;
382 $dbh->rollback if $oldAutoCommit;
383 return "No svc_acct record to apply pre-paid time";
387 warn " inserting initial $payby payment of $amount\n"
389 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
391 $dbh->rollback if $oldAutoCommit;
392 return "inserting payment (transaction rolled back): $error";
396 unless ( $import || $skip_fuzzyfiles ) {
397 warn " queueing fuzzyfiles update\n"
399 $error = $self->queue_fuzzyfiles_update;
401 $dbh->rollback if $oldAutoCommit;
402 return "updating fuzzy search cache: $error";
406 warn " insert complete; committing transaction\n"
409 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
414 sub start_copy_skel {
417 #'mg_user_preference' => {},
418 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
419 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
420 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
421 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
422 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
425 _copy_skel( 'cust_main', #tablename
426 $conf->config('cust_main-skeleton_custnum'), #sourceid
427 $self->custnum, #destid
428 @tables, #child tables
432 #recursive subroutine, not a method
434 my( $table, $sourceid, $destid, %child_tables ) = @_;
437 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
438 ( $table, $primary_key ) = ( $1, $2 );
440 my $dbdef_table = dbdef->table($table);
441 $primary_key = $dbdef_table->primary_key
442 or return "$table has no primary key".
443 " (or do you need to run dbdef-create?)";
446 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
447 join (', ', keys %child_tables). "\n"
450 foreach my $child_table_def ( keys %child_tables ) {
454 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
455 ( $child_table, $child_pkey ) = ( $1, $2 );
457 $child_table = $child_table_def;
459 $child_pkey = dbdef->table($child_table)->primary_key;
460 # or return "$table has no primary key".
461 # " (or do you need to run dbdef-create?)\n";
465 if ( keys %{ $child_tables{$child_table_def} } ) {
467 return "$child_table has no primary key".
468 " (run dbdef-create or try specifying it?)\n"
471 #false laziness w/Record::insert and only works on Pg
472 #refactor the proper last-inserted-id stuff out of Record::insert if this
473 # ever gets use for anything besides a quick kludge for one customer
474 my $default = dbdef->table($child_table)->column($child_pkey)->default;
475 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
476 or return "can't parse $child_table.$child_pkey default value ".
477 " for sequence name: $default";
482 my @sel_columns = grep { $_ ne $primary_key }
483 dbdef->table($child_table)->columns;
484 my $sel_columns = join(', ', @sel_columns );
486 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
487 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
488 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
490 my $sel_st = "SELECT $sel_columns FROM $child_table".
491 " WHERE $primary_key = $sourceid";
494 my $sel_sth = dbh->prepare( $sel_st )
495 or return dbh->errstr;
497 $sel_sth->execute or return $sel_sth->errstr;
499 while ( my $row = $sel_sth->fetchrow_hashref ) {
501 warn " selected row: ".
502 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
506 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
507 my $ins_sth =dbh->prepare($statement)
508 or return dbh->errstr;
509 my @param = ( $destid, map $row->{$_}, @ins_columns );
510 warn " $statement: [ ". join(', ', @param). " ]\n"
512 $ins_sth->execute( @param )
513 or return $ins_sth->errstr;
515 #next unless keys %{ $child_tables{$child_table} };
516 next unless $sequence;
518 #another section of that laziness
519 my $seq_sql = "SELECT currval('$sequence')";
520 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
521 $seq_sth->execute or return $seq_sth->errstr;
522 my $insertid = $seq_sth->fetchrow_arrayref->[0];
524 # don't drink soap! recurse! recurse! okay!
526 _copy_skel( $child_table_def,
527 $row->{$child_pkey}, #sourceid
529 %{ $child_tables{$child_table_def} },
531 return $error if $error;
541 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
543 Like the insert method on an existing record, this method orders a package
544 and included services atomicaly. Pass a Tie::RefHash data structure to this
545 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
546 be a better explanation of this, but until then, here's an example:
549 tie %hash, 'Tie::RefHash'; #this part is important
551 $cust_pkg => [ $svc_acct ],
554 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
556 Services can be new, in which case they are inserted, or existing unaudited
557 services, in which case they are linked to the newly-created package.
559 Currently available options are: I<depend_jobnum> and I<noexport>.
561 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
562 on the supplied jobnum (they will not run until the specific job completes).
563 This can be used to defer provisioning until some action completes (such
564 as running the customer's credit card successfully).
566 The I<noexport> option is deprecated. If I<noexport> is set true, no
567 provisioning jobs (exports) are scheduled. (You can schedule them later with
568 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
569 on the cust_main object is not recommended, as existing services will also be
576 my $cust_pkgs = shift;
579 my %svc_options = ();
580 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
581 if exists $options{'depend_jobnum'};
582 warn "$me order_pkgs called with options ".
583 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
586 local $SIG{HUP} = 'IGNORE';
587 local $SIG{INT} = 'IGNORE';
588 local $SIG{QUIT} = 'IGNORE';
589 local $SIG{TERM} = 'IGNORE';
590 local $SIG{TSTP} = 'IGNORE';
591 local $SIG{PIPE} = 'IGNORE';
593 my $oldAutoCommit = $FS::UID::AutoCommit;
594 local $FS::UID::AutoCommit = 0;
597 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
599 foreach my $cust_pkg ( keys %$cust_pkgs ) {
600 $cust_pkg->custnum( $self->custnum );
601 my $error = $cust_pkg->insert;
603 $dbh->rollback if $oldAutoCommit;
604 return "inserting cust_pkg (transaction rolled back): $error";
606 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
607 if ( $svc_something->svcnum ) {
608 my $old_cust_svc = $svc_something->cust_svc;
609 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
610 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
611 $error = $new_cust_svc->replace($old_cust_svc);
613 $svc_something->pkgnum( $cust_pkg->pkgnum );
614 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
615 $svc_something->seconds( $svc_something->seconds + $$seconds );
618 $error = $svc_something->insert(%svc_options);
621 $dbh->rollback if $oldAutoCommit;
622 #return "inserting svc_ (transaction rolled back): $error";
628 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
632 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
634 Recharges this (existing) customer with the specified prepaid card (see
635 L<FS::prepay_credit>), specified either by I<identifier> or as an
636 FS::prepay_credit object. If there is an error, returns the error, otherwise
639 Optionally, four scalar references can be passed as well. They will have their
640 values filled in with the amount, number of seconds, and number of upload and
641 download bytes applied by this prepaid
646 sub recharge_prepay {
647 my( $self, $prepay_credit, $amountref, $secondsref,
648 $upbytesref, $downbytesref, $totalbytesref ) = @_;
650 local $SIG{HUP} = 'IGNORE';
651 local $SIG{INT} = 'IGNORE';
652 local $SIG{QUIT} = 'IGNORE';
653 local $SIG{TERM} = 'IGNORE';
654 local $SIG{TSTP} = 'IGNORE';
655 local $SIG{PIPE} = 'IGNORE';
657 my $oldAutoCommit = $FS::UID::AutoCommit;
658 local $FS::UID::AutoCommit = 0;
661 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
663 my $error = $self->get_prepay($prepay_credit, \$amount,
664 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
665 || $self->increment_seconds($seconds)
666 || $self->increment_upbytes($upbytes)
667 || $self->increment_downbytes($downbytes)
668 || $self->increment_totalbytes($totalbytes)
669 || $self->insert_cust_pay_prepay( $amount,
671 ? $prepay_credit->identifier
676 $dbh->rollback if $oldAutoCommit;
680 if ( defined($amountref) ) { $$amountref = $amount; }
681 if ( defined($secondsref) ) { $$secondsref = $seconds; }
682 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
683 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
684 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
686 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
691 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
693 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
694 specified either by I<identifier> or as an FS::prepay_credit object.
696 References to I<amount> and I<seconds> scalars should be passed as arguments
697 and will be incremented by the values of the prepaid card.
699 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
700 check or set this customer's I<agentnum>.
702 If there is an error, returns the error, otherwise returns false.
708 my( $self, $prepay_credit, $amountref, $secondsref,
709 $upref, $downref, $totalref) = @_;
711 local $SIG{HUP} = 'IGNORE';
712 local $SIG{INT} = 'IGNORE';
713 local $SIG{QUIT} = 'IGNORE';
714 local $SIG{TERM} = 'IGNORE';
715 local $SIG{TSTP} = 'IGNORE';
716 local $SIG{PIPE} = 'IGNORE';
718 my $oldAutoCommit = $FS::UID::AutoCommit;
719 local $FS::UID::AutoCommit = 0;
722 unless ( ref($prepay_credit) ) {
724 my $identifier = $prepay_credit;
726 $prepay_credit = qsearchs(
728 { 'identifier' => $prepay_credit },
733 unless ( $prepay_credit ) {
734 $dbh->rollback if $oldAutoCommit;
735 return "Invalid prepaid card: ". $identifier;
740 if ( $prepay_credit->agentnum ) {
741 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
742 $dbh->rollback if $oldAutoCommit;
743 return "prepaid card not valid for agent ". $self->agentnum;
745 $self->agentnum($prepay_credit->agentnum);
748 my $error = $prepay_credit->delete;
750 $dbh->rollback if $oldAutoCommit;
751 return "removing prepay_credit (transaction rolled back): $error";
754 $$amountref += $prepay_credit->amount;
755 $$secondsref += $prepay_credit->seconds;
756 $$upref += $prepay_credit->upbytes;
757 $$downref += $prepay_credit->downbytes;
758 $$totalref += $prepay_credit->totalbytes;
760 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
765 =item increment_upbytes SECONDS
767 Updates this customer's single or primary account (see L<FS::svc_acct>) by
768 the specified number of upbytes. If there is an error, returns the error,
769 otherwise returns false.
773 sub increment_upbytes {
774 _increment_column( shift, 'upbytes', @_);
777 =item increment_downbytes SECONDS
779 Updates this customer's single or primary account (see L<FS::svc_acct>) by
780 the specified number of downbytes. If there is an error, returns the error,
781 otherwise returns false.
785 sub increment_downbytes {
786 _increment_column( shift, 'downbytes', @_);
789 =item increment_totalbytes SECONDS
791 Updates this customer's single or primary account (see L<FS::svc_acct>) by
792 the specified number of totalbytes. If there is an error, returns the error,
793 otherwise returns false.
797 sub increment_totalbytes {
798 _increment_column( shift, 'totalbytes', @_);
801 =item increment_seconds SECONDS
803 Updates this customer's single or primary account (see L<FS::svc_acct>) by
804 the specified number of seconds. If there is an error, returns the error,
805 otherwise returns false.
809 sub increment_seconds {
810 _increment_column( shift, 'seconds', @_);
813 =item _increment_column AMOUNT
815 Updates this customer's single or primary account (see L<FS::svc_acct>) by
816 the specified number of seconds or bytes. If there is an error, returns
817 the error, otherwise returns false.
821 sub _increment_column {
822 my( $self, $column, $amount ) = @_;
823 warn "$me increment_column called: $column, $amount\n"
826 return '' unless $amount;
828 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
829 $self->ncancelled_pkgs;
832 return 'No packages with primary or single services found'.
833 ' to apply pre-paid time';
834 } elsif ( scalar(@cust_pkg) > 1 ) {
835 #maybe have a way to specify the package/account?
836 return 'Multiple packages found to apply pre-paid time';
839 my $cust_pkg = $cust_pkg[0];
840 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
844 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
847 return 'No account found to apply pre-paid time';
848 } elsif ( scalar(@cust_svc) > 1 ) {
849 return 'Multiple accounts found to apply pre-paid time';
852 my $svc_acct = $cust_svc[0]->svc_x;
853 warn " found service svcnum ". $svc_acct->pkgnum.
854 ' ('. $svc_acct->email. ")\n"
857 $column = "increment_$column";
858 $svc_acct->$column($amount);
862 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
864 Inserts a prepayment in the specified amount for this customer. An optional
865 second argument can specify the prepayment identifier for tracking purposes.
866 If there is an error, returns the error, otherwise returns false.
870 sub insert_cust_pay_prepay {
871 shift->insert_cust_pay('PREP', @_);
874 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
876 Inserts a cash payment in the specified amount for this customer. An optional
877 second argument can specify the payment identifier for tracking purposes.
878 If there is an error, returns the error, otherwise returns false.
882 sub insert_cust_pay_cash {
883 shift->insert_cust_pay('CASH', @_);
886 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
888 Inserts a Western Union payment in the specified amount for this customer. An
889 optional second argument can specify the prepayment identifier for tracking
890 purposes. If there is an error, returns the error, otherwise returns false.
894 sub insert_cust_pay_west {
895 shift->insert_cust_pay('WEST', @_);
898 sub insert_cust_pay {
899 my( $self, $payby, $amount ) = splice(@_, 0, 3);
900 my $payinfo = scalar(@_) ? shift : '';
902 my $cust_pay = new FS::cust_pay {
903 'custnum' => $self->custnum,
904 'paid' => sprintf('%.2f', $amount),
905 #'_date' => #date the prepaid card was purchased???
907 'payinfo' => $payinfo,
915 This method is deprecated. See the I<depend_jobnum> option to the insert and
916 order_pkgs methods for a better way to defer provisioning.
918 Re-schedules all exports by calling the B<reexport> method of all associated
919 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
920 otherwise returns false.
927 carp "WARNING: FS::cust_main::reexport is deprectated; ".
928 "use the depend_jobnum option to insert or order_pkgs to delay export";
930 local $SIG{HUP} = 'IGNORE';
931 local $SIG{INT} = 'IGNORE';
932 local $SIG{QUIT} = 'IGNORE';
933 local $SIG{TERM} = 'IGNORE';
934 local $SIG{TSTP} = 'IGNORE';
935 local $SIG{PIPE} = 'IGNORE';
937 my $oldAutoCommit = $FS::UID::AutoCommit;
938 local $FS::UID::AutoCommit = 0;
941 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
942 my $error = $cust_pkg->reexport;
944 $dbh->rollback if $oldAutoCommit;
949 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
954 =item delete NEW_CUSTNUM
956 This deletes the customer. If there is an error, returns the error, otherwise
959 This will completely remove all traces of the customer record. This is not
960 what you want when a customer cancels service; for that, cancel all of the
961 customer's packages (see L</cancel>).
963 If the customer has any uncancelled packages, you need to pass a new (valid)
964 customer number for those packages to be transferred to. Cancelled packages
965 will be deleted. Did I mention that this is NOT what you want when a customer
966 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
968 You can't delete a customer with invoices (see L<FS::cust_bill>),
969 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
970 refunds (see L<FS::cust_refund>).
977 local $SIG{HUP} = 'IGNORE';
978 local $SIG{INT} = 'IGNORE';
979 local $SIG{QUIT} = 'IGNORE';
980 local $SIG{TERM} = 'IGNORE';
981 local $SIG{TSTP} = 'IGNORE';
982 local $SIG{PIPE} = 'IGNORE';
984 my $oldAutoCommit = $FS::UID::AutoCommit;
985 local $FS::UID::AutoCommit = 0;
988 if ( $self->cust_bill ) {
989 $dbh->rollback if $oldAutoCommit;
990 return "Can't delete a customer with invoices";
992 if ( $self->cust_credit ) {
993 $dbh->rollback if $oldAutoCommit;
994 return "Can't delete a customer with credits";
996 if ( $self->cust_pay ) {
997 $dbh->rollback if $oldAutoCommit;
998 return "Can't delete a customer with payments";
1000 if ( $self->cust_refund ) {
1001 $dbh->rollback if $oldAutoCommit;
1002 return "Can't delete a customer with refunds";
1005 my @cust_pkg = $self->ncancelled_pkgs;
1007 my $new_custnum = shift;
1008 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1009 $dbh->rollback if $oldAutoCommit;
1010 return "Invalid new customer number: $new_custnum";
1012 foreach my $cust_pkg ( @cust_pkg ) {
1013 my %hash = $cust_pkg->hash;
1014 $hash{'custnum'} = $new_custnum;
1015 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1016 my $error = $new_cust_pkg->replace($cust_pkg,
1017 options => { $cust_pkg->options },
1020 $dbh->rollback if $oldAutoCommit;
1025 my @cancelled_cust_pkg = $self->all_pkgs;
1026 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1027 my $error = $cust_pkg->delete;
1029 $dbh->rollback if $oldAutoCommit;
1034 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1035 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1037 my $error = $cust_main_invoice->delete;
1039 $dbh->rollback if $oldAutoCommit;
1044 my $error = $self->SUPER::delete;
1046 $dbh->rollback if $oldAutoCommit;
1050 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1055 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ]
1057 Replaces the OLD_RECORD with this one in the database. If there is an error,
1058 returns the error, otherwise returns false.
1060 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1061 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1062 expected and rollback the entire transaction; it is not necessary to call
1063 check_invoicing_list first. Here's an example:
1065 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1072 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1074 : $self->replace_old;
1078 warn "$me replace called\n"
1081 my $curuser = $FS::CurrentUser::CurrentUser;
1082 if ( $self->payby eq 'COMP'
1083 && $self->payby ne $old->payby
1084 && ! $curuser->access_right('Complimentary customer')
1087 return "You are not permitted to create complimentary accounts.";
1090 local($ignore_expired_card) = 1
1091 if $old->payby =~ /^(CARD|DCRD)$/
1092 && $self->payby =~ /^(CARD|DCRD)$/
1093 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1095 local $SIG{HUP} = 'IGNORE';
1096 local $SIG{INT} = 'IGNORE';
1097 local $SIG{QUIT} = 'IGNORE';
1098 local $SIG{TERM} = 'IGNORE';
1099 local $SIG{TSTP} = 'IGNORE';
1100 local $SIG{PIPE} = 'IGNORE';
1102 my $oldAutoCommit = $FS::UID::AutoCommit;
1103 local $FS::UID::AutoCommit = 0;
1106 my $error = $self->SUPER::replace($old);
1109 $dbh->rollback if $oldAutoCommit;
1113 if ( @param ) { # INVOICING_LIST_ARYREF
1114 my $invoicing_list = shift @param;
1115 $error = $self->check_invoicing_list( $invoicing_list );
1117 $dbh->rollback if $oldAutoCommit;
1120 $self->invoicing_list( $invoicing_list );
1123 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1124 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1125 # card/check/lec info has changed, want to retry realtime_ invoice events
1126 my $error = $self->retry_realtime;
1128 $dbh->rollback if $oldAutoCommit;
1133 unless ( $import || $skip_fuzzyfiles ) {
1134 $error = $self->queue_fuzzyfiles_update;
1136 $dbh->rollback if $oldAutoCommit;
1137 return "updating fuzzy search cache: $error";
1141 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1146 =item queue_fuzzyfiles_update
1148 Used by insert & replace to update the fuzzy search cache
1152 sub queue_fuzzyfiles_update {
1155 local $SIG{HUP} = 'IGNORE';
1156 local $SIG{INT} = 'IGNORE';
1157 local $SIG{QUIT} = 'IGNORE';
1158 local $SIG{TERM} = 'IGNORE';
1159 local $SIG{TSTP} = 'IGNORE';
1160 local $SIG{PIPE} = 'IGNORE';
1162 my $oldAutoCommit = $FS::UID::AutoCommit;
1163 local $FS::UID::AutoCommit = 0;
1166 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1167 my $error = $queue->insert( map $self->getfield($_),
1168 qw(first last company)
1171 $dbh->rollback if $oldAutoCommit;
1172 return "queueing job (transaction rolled back): $error";
1175 if ( $self->ship_last ) {
1176 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1177 $error = $queue->insert( map $self->getfield("ship_$_"),
1178 qw(first last company)
1181 $dbh->rollback if $oldAutoCommit;
1182 return "queueing job (transaction rolled back): $error";
1186 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1193 Checks all fields to make sure this is a valid customer record. If there is
1194 an error, returns the error, otherwise returns false. Called by the insert
1195 and replace methods.
1202 warn "$me check BEFORE: \n". $self->_dump
1206 $self->ut_numbern('custnum')
1207 || $self->ut_number('agentnum')
1208 || $self->ut_textn('agent_custid')
1209 || $self->ut_number('refnum')
1210 || $self->ut_name('last')
1211 || $self->ut_name('first')
1212 || $self->ut_snumbern('birthdate')
1213 || $self->ut_snumbern('signupdate')
1214 || $self->ut_textn('company')
1215 || $self->ut_text('address1')
1216 || $self->ut_textn('address2')
1217 || $self->ut_text('city')
1218 || $self->ut_textn('county')
1219 || $self->ut_textn('state')
1220 || $self->ut_country('country')
1221 || $self->ut_anything('comments')
1222 || $self->ut_numbern('referral_custnum')
1223 || $self->ut_textn('stateid')
1224 || $self->ut_textn('stateid_state')
1225 || $self->ut_textn('invoice_terms')
1227 #barf. need message catalogs. i18n. etc.
1228 $error .= "Please select an advertising source."
1229 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1230 return $error if $error;
1232 return "Unknown agent"
1233 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1235 return "Unknown refnum"
1236 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1238 return "Unknown referring custnum: ". $self->referral_custnum
1239 unless ! $self->referral_custnum
1240 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1242 if ( $self->ss eq '' ) {
1247 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1248 or return "Illegal social security number: ". $self->ss;
1249 $self->ss("$1-$2-$3");
1253 # bad idea to disable, causes billing to fail because of no tax rates later
1254 # unless ( $import ) {
1255 unless ( qsearch('cust_main_county', {
1256 'country' => $self->country,
1259 return "Unknown state/county/country: ".
1260 $self->state. "/". $self->county. "/". $self->country
1261 unless qsearch('cust_main_county',{
1262 'state' => $self->state,
1263 'county' => $self->county,
1264 'country' => $self->country,
1270 $self->ut_phonen('daytime', $self->country)
1271 || $self->ut_phonen('night', $self->country)
1272 || $self->ut_phonen('fax', $self->country)
1273 || $self->ut_zip('zip', $self->country)
1275 return $error if $error;
1277 if ( $conf->exists('cust_main-require_phone')
1278 && ! length($self->daytime) && ! length($self->night)
1281 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1283 : FS::Msgcat::_gettext('daytime');
1284 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1286 : FS::Msgcat::_gettext('night');
1288 return "$daytime_label or $night_label is required"
1292 if ( $self->has_ship_address
1293 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1294 $self->addr_fields )
1298 $self->ut_name('ship_last')
1299 || $self->ut_name('ship_first')
1300 || $self->ut_textn('ship_company')
1301 || $self->ut_text('ship_address1')
1302 || $self->ut_textn('ship_address2')
1303 || $self->ut_text('ship_city')
1304 || $self->ut_textn('ship_county')
1305 || $self->ut_textn('ship_state')
1306 || $self->ut_country('ship_country')
1308 return $error if $error;
1310 #false laziness with above
1311 unless ( qsearchs('cust_main_county', {
1312 'country' => $self->ship_country,
1315 return "Unknown ship_state/ship_county/ship_country: ".
1316 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1317 unless qsearch('cust_main_county',{
1318 'state' => $self->ship_state,
1319 'county' => $self->ship_county,
1320 'country' => $self->ship_country,
1326 $self->ut_phonen('ship_daytime', $self->ship_country)
1327 || $self->ut_phonen('ship_night', $self->ship_country)
1328 || $self->ut_phonen('ship_fax', $self->ship_country)
1329 || $self->ut_zip('ship_zip', $self->ship_country)
1331 return $error if $error;
1333 return "Unit # is required."
1334 if $self->ship_address2 =~ /^\s*$/
1335 && $conf->exists('cust_main-require_address2');
1337 } else { # ship_ info eq billing info, so don't store dup info in database
1339 $self->setfield("ship_$_", '')
1340 foreach $self->addr_fields;
1342 return "Unit # is required."
1343 if $self->address2 =~ /^\s*$/
1344 && $conf->exists('cust_main-require_address2');
1348 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1349 # or return "Illegal payby: ". $self->payby;
1351 FS::payby->can_payby($self->table, $self->payby)
1352 or return "Illegal payby: ". $self->payby;
1354 $error = $self->ut_numbern('paystart_month')
1355 || $self->ut_numbern('paystart_year')
1356 || $self->ut_numbern('payissue')
1357 || $self->ut_textn('paytype')
1359 return $error if $error;
1361 if ( $self->payip eq '' ) {
1364 $error = $self->ut_ip('payip');
1365 return $error if $error;
1368 # If it is encrypted and the private key is not availaible then we can't
1369 # check the credit card.
1371 my $check_payinfo = 1;
1373 if ($self->is_encrypted($self->payinfo)) {
1377 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1379 my $payinfo = $self->payinfo;
1380 $payinfo =~ s/\D//g;
1381 $payinfo =~ /^(\d{13,16})$/
1382 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1384 $self->payinfo($payinfo);
1386 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1388 return gettext('unknown_card_type')
1389 if cardtype($self->payinfo) eq "Unknown";
1391 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1393 return 'Banned credit card: banned on '.
1394 time2str('%a %h %o at %r', $ban->_date).
1395 ' by '. $ban->otaker.
1396 ' (ban# '. $ban->bannum. ')';
1399 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1400 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1401 $self->paycvv =~ /^(\d{4})$/
1402 or return "CVV2 (CID) for American Express cards is four digits.";
1405 $self->paycvv =~ /^(\d{3})$/
1406 or return "CVV2 (CVC2/CID) is three digits.";
1413 my $cardtype = cardtype($payinfo);
1414 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1416 return "Start date or issue number is required for $cardtype cards"
1417 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1419 return "Start month must be between 1 and 12"
1420 if $self->paystart_month
1421 and $self->paystart_month < 1 || $self->paystart_month > 12;
1423 return "Start year must be 1990 or later"
1424 if $self->paystart_year
1425 and $self->paystart_year < 1990;
1427 return "Issue number must be beween 1 and 99"
1429 and $self->payissue < 1 || $self->payissue > 99;
1432 $self->paystart_month('');
1433 $self->paystart_year('');
1434 $self->payissue('');
1437 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1439 my $payinfo = $self->payinfo;
1440 $payinfo =~ s/[^\d\@]//g;
1441 if ( $conf->exists('echeck-nonus') ) {
1442 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1443 $payinfo = "$1\@$2";
1445 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1446 $payinfo = "$1\@$2";
1448 $self->payinfo($payinfo);
1451 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1453 return 'Banned ACH account: banned on '.
1454 time2str('%a %h %o at %r', $ban->_date).
1455 ' by '. $ban->otaker.
1456 ' (ban# '. $ban->bannum. ')';
1459 } elsif ( $self->payby eq 'LECB' ) {
1461 my $payinfo = $self->payinfo;
1462 $payinfo =~ s/\D//g;
1463 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1465 $self->payinfo($payinfo);
1468 } elsif ( $self->payby eq 'BILL' ) {
1470 $error = $self->ut_textn('payinfo');
1471 return "Illegal P.O. number: ". $self->payinfo if $error;
1474 } elsif ( $self->payby eq 'COMP' ) {
1476 my $curuser = $FS::CurrentUser::CurrentUser;
1477 if ( ! $self->custnum
1478 && ! $curuser->access_right('Complimentary customer')
1481 return "You are not permitted to create complimentary accounts."
1484 $error = $self->ut_textn('payinfo');
1485 return "Illegal comp account issuer: ". $self->payinfo if $error;
1488 } elsif ( $self->payby eq 'PREPAY' ) {
1490 my $payinfo = $self->payinfo;
1491 $payinfo =~ s/\W//g; #anything else would just confuse things
1492 $self->payinfo($payinfo);
1493 $error = $self->ut_alpha('payinfo');
1494 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1495 return "Unknown prepayment identifier"
1496 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1501 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1502 return "Expiration date required"
1503 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1507 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1508 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1509 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1510 ( $m, $y ) = ( $3, "20$2" );
1512 return "Illegal expiration date: ". $self->paydate;
1514 $self->paydate("$y-$m-01");
1515 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1516 return gettext('expired_card')
1518 && !$ignore_expired_card
1519 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1522 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1523 ( ! $conf->exists('require_cardname')
1524 || $self->payby !~ /^(CARD|DCRD)$/ )
1526 $self->payname( $self->first. " ". $self->getfield('last') );
1528 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1529 or return gettext('illegal_name'). " payname: ". $self->payname;
1533 foreach my $flag (qw( tax spool_cdr )) {
1534 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1538 $self->otaker(getotaker) unless $self->otaker;
1540 warn "$me check AFTER: \n". $self->_dump
1543 $self->SUPER::check;
1548 Returns a list of fields which have ship_ duplicates.
1553 qw( last first company
1554 address1 address2 city county state zip country
1559 =item has_ship_address
1561 Returns true if this customer record has a separate shipping address.
1565 sub has_ship_address {
1567 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1572 Returns all packages (see L<FS::cust_pkg>) for this customer.
1579 return $self->num_pkgs unless wantarray;
1582 if ( $self->{'_pkgnum'} ) {
1583 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1585 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1588 sort sort_packages @cust_pkg;
1593 Synonym for B<all_pkgs>.
1598 shift->all_pkgs(@_);
1601 =item ncancelled_pkgs
1603 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1607 sub ncancelled_pkgs {
1610 return $self->num_ncancelled_pkgs unless wantarray;
1613 if ( $self->{'_pkgnum'} ) {
1615 warn "$me ncancelled_pkgs: returning cached objects"
1618 @cust_pkg = grep { ! $_->getfield('cancel') }
1619 values %{ $self->{'_pkgnum'}->cache };
1623 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1624 $self->custnum. "\n"
1628 qsearch( 'cust_pkg', {
1629 'custnum' => $self->custnum,
1633 qsearch( 'cust_pkg', {
1634 'custnum' => $self->custnum,
1639 sort sort_packages @cust_pkg;
1643 # This should be generalized to use config options to determine order.
1645 if ( $a->get('cancel') and $b->get('cancel') ) {
1646 $a->pkgnum <=> $b->pkgnum;
1647 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1648 return -1 if $b->get('cancel');
1649 return 1 if $a->get('cancel');
1652 $a->pkgnum <=> $b->pkgnum;
1656 =item suspended_pkgs
1658 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1662 sub suspended_pkgs {
1664 grep { $_->susp } $self->ncancelled_pkgs;
1667 =item unflagged_suspended_pkgs
1669 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1670 customer (thouse packages without the `manual_flag' set).
1674 sub unflagged_suspended_pkgs {
1676 return $self->suspended_pkgs
1677 unless dbdef->table('cust_pkg')->column('manual_flag');
1678 grep { ! $_->manual_flag } $self->suspended_pkgs;
1681 =item unsuspended_pkgs
1683 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1688 sub unsuspended_pkgs {
1690 grep { ! $_->susp } $self->ncancelled_pkgs;
1693 =item num_cancelled_pkgs
1695 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1700 sub num_cancelled_pkgs {
1701 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1704 sub num_ncancelled_pkgs {
1705 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1709 my( $self ) = shift;
1710 my $sql = scalar(@_) ? shift : '';
1711 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1712 my $sth = dbh->prepare(
1713 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1714 ) or die dbh->errstr;
1715 $sth->execute($self->custnum) or die $sth->errstr;
1716 $sth->fetchrow_arrayref->[0];
1721 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1722 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1723 on success or a list of errors.
1729 grep { $_->unsuspend } $self->suspended_pkgs;
1734 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1736 Returns a list: an empty list on success or a list of errors.
1742 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1745 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1747 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1748 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1749 of a list of pkgparts; the hashref has the following keys:
1753 =item pkgparts - listref of pkgparts
1755 =item (other options are passed to the suspend method)
1760 Returns a list: an empty list on success or a list of errors.
1764 sub suspend_if_pkgpart {
1766 my (@pkgparts, %opt);
1767 if (ref($_[0]) eq 'HASH'){
1768 @pkgparts = @{$_[0]{pkgparts}};
1773 grep { $_->suspend(%opt) }
1774 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1775 $self->unsuspended_pkgs;
1778 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1780 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1781 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1782 instead of a list of pkgparts; the hashref has the following keys:
1786 =item pkgparts - listref of pkgparts
1788 =item (other options are passed to the suspend method)
1792 Returns a list: an empty list on success or a list of errors.
1796 sub suspend_unless_pkgpart {
1798 my (@pkgparts, %opt);
1799 if (ref($_[0]) eq 'HASH'){
1800 @pkgparts = @{$_[0]{pkgparts}};
1805 grep { $_->suspend(%opt) }
1806 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1807 $self->unsuspended_pkgs;
1810 =item cancel [ OPTION => VALUE ... ]
1812 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1814 Available options are:
1818 =item quiet - can be set true to supress email cancellation notices.
1820 =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.
1822 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1826 Always returns a list: an empty list on success or a list of errors.
1831 my( $self, %opt ) = @_;
1833 warn "$me cancel called on customer ". $self->custnum. " with options ".
1834 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1837 return ( 'access denied' )
1838 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1840 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1842 #should try decryption (we might have the private key)
1843 # and if not maybe queue a job for the server that does?
1844 return ( "Can't (yet) ban encrypted credit cards" )
1845 if $self->is_encrypted($self->payinfo);
1847 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1848 my $error = $ban->insert;
1849 return ( $error ) if $error;
1853 my @pkgs = $self->ncancelled_pkgs;
1855 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1856 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1859 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1862 sub _banned_pay_hashref {
1873 'payby' => $payby2ban{$self->payby},
1874 'payinfo' => md5_base64($self->payinfo),
1875 #don't ever *search* on reason! #'reason' =>
1881 Returns all notes (see L<FS::cust_main_note>) for this customer.
1888 qsearch( 'cust_main_note',
1889 { 'custnum' => $self->custnum },
1891 'ORDER BY _DATE DESC'
1897 Returns the agent (see L<FS::agent>) for this customer.
1903 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1906 =item bill_and_collect
1908 Cancels and suspends any packages due, generates bills, applies payments and
1911 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1913 Options are passed as name-value pairs. Currently available options are:
1919 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:
1923 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1927 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.
1931 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1935 If set true, re-charges setup fees.
1939 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)
1945 sub bill_and_collect {
1946 my( $self, %options ) = @_;
1952 #$options{actual_time} not $options{time} because freeside-daily -d is for
1953 #pre-printing invoices
1954 my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
1955 $self->ncancelled_pkgs;
1957 foreach my $cust_pkg ( @cancel_pkgs ) {
1958 my $error = $cust_pkg->cancel;
1959 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1960 " for custnum ". $self->custnum. ": $error"
1968 #$options{actual_time} not $options{time} because freeside-daily -d is for
1969 #pre-printing invoices
1972 && ( ( $_->part_pkg->is_prepaid
1974 && $_->bill < $options{actual_time}
1977 && $_->adjourn <= $options{actual_time}
1981 $self->ncancelled_pkgs;
1983 foreach my $cust_pkg ( @susp_pkgs ) {
1984 my $error = $cust_pkg->suspend;
1985 warn "Error suspending package ". $cust_pkg->pkgnum.
1986 " for custnum ". $self->custnum. ": $error"
1994 my $error = $self->bill( %options );
1995 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
1997 $self->apply_payments_and_credits;
1999 $error = $self->collect( %options );
2000 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2006 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2007 conjunction with the collect method by calling B<bill_and_collect>.
2009 If there is an error, returns the error, otherwise returns false.
2011 Options are passed as name-value pairs. Currently available options are:
2017 If set true, re-charges setup fees.
2021 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:
2025 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2029 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2031 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2035 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.
2042 my( $self, %options ) = @_;
2043 return '' if $self->payby eq 'COMP';
2044 warn "$me bill customer ". $self->custnum. "\n"
2047 my $time = $options{'time'} || time;
2050 local $SIG{HUP} = 'IGNORE';
2051 local $SIG{INT} = 'IGNORE';
2052 local $SIG{QUIT} = 'IGNORE';
2053 local $SIG{TERM} = 'IGNORE';
2054 local $SIG{TSTP} = 'IGNORE';
2055 local $SIG{PIPE} = 'IGNORE';
2057 my $oldAutoCommit = $FS::UID::AutoCommit;
2058 local $FS::UID::AutoCommit = 0;
2061 $self->select_for_update; #mutex
2063 my @cust_bill_pkg = ();
2064 my @appended_cust_bill_pkg = ();
2067 # find the packages which are due for billing, find out how much they are
2068 # & generate invoice database.
2071 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2075 my @precommit_hooks = ();
2077 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2078 foreach my $cust_pkg (@cust_pkgs) {
2080 #NO!! next if $cust_pkg->cancel;
2081 next if $cust_pkg->getfield('cancel');
2083 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2085 #? to avoid use of uninitialized value errors... ?
2086 $cust_pkg->setfield('bill', '')
2087 unless defined($cust_pkg->bill);
2089 #my $part_pkg = $cust_pkg->part_pkg;
2091 my $real_pkgpart = $cust_pkg->pkgpart;
2092 my %hash = $cust_pkg->hash;
2093 my $old_cust_pkg = new FS::cust_pkg \%hash;
2095 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2097 $self->_make_lines( 'part_pkg' => $part_pkg,
2098 'cust_pkg' => $cust_pkg,
2099 'precommit_hooks' => \@precommit_hooks,
2100 'line_items' => \@cust_bill_pkg,
2101 'appended_line_items' => \@appended_cust_bill_pkg,
2102 'setup' => \$total_setup,
2103 'recur' => \$total_recur,
2104 'tax_matrix' => \%taxlisthash,
2106 'options' => \%options,
2109 $dbh->rollback if $oldAutoCommit;
2113 } #foreach my $part_pkg
2115 } #foreach my $cust_pkg
2117 push @cust_bill_pkg, @appended_cust_bill_pkg;
2119 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2120 #but do commit any package date cycling that happened
2121 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2125 my $postal_pkg = $self->charge_postal_fee();
2126 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2127 $dbh->rollback if $oldAutoCommit;
2128 return "can't charge postal invoice fee for customer ".
2129 $self->custnum. ": $postal_pkg";
2131 if ( $postal_pkg ) {
2132 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2134 $self->_make_lines( 'part_pkg' => $part_pkg,
2135 'cust_pkg' => $postal_pkg,
2136 'precommit_hooks' => \@precommit_hooks,
2137 'line_items' => \@cust_bill_pkg,
2138 'appended_line_items' => \@appended_cust_bill_pkg,
2139 'setup' => \$total_setup,
2140 'recur' => \$total_recur,
2141 'tax_matrix' => \%taxlisthash,
2143 'options' => \%options,
2146 $dbh->rollback if $oldAutoCommit;
2152 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2153 foreach my $tax ( keys %taxlisthash ) {
2154 my $tax_object = shift @{ $taxlisthash{$tax} };
2155 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2156 my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2157 unless (ref($listref_or_error)) {
2158 $dbh->rollback if $oldAutoCommit;
2159 return $listref_or_error;
2161 unshift @{ $taxlisthash{$tax} }, $tax_object;
2163 warn "adding ". $listref_or_error->[1].
2164 " as ". $listref_or_error->[0]. "\n"
2166 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2167 if ( $taxname{ $listref_or_error->[0] } ) {
2168 push @{ $taxname{ $listref_or_error->[0] } }, $tax_object->taxname;
2170 $taxname{ $listref_or_error->[0] } = [ $tax_object->taxname ];
2175 #some taxes are taxed
2178 warn "finding taxed taxes...\n" if $DEBUG > 2;
2179 foreach my $tax ( keys %taxlisthash ) {
2180 my $tax_object = shift @{ $taxlisthash{$tax} };
2181 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2183 next unless $tax_object->can('tax_on_tax');
2185 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2186 my $totname = ref( $tot ). ' '. $tot->taxnum;
2188 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2190 next unless exists( $taxlisthash{ $totname } ); # only increase
2192 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2193 if ( exists( $totlisthash{ $totname } ) ) {
2194 push @{ $totlisthash{ $totname } }, $tax{ $tax_object->taxname };
2196 $totlisthash{ $totname } = [ $tot, $tax{ $tax_object->taxname } ];
2201 warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2202 foreach my $tax ( keys %totlisthash ) {
2203 my $tax_object = shift @{ $totlisthash{$tax} };
2204 warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2206 my $listref_or_error = $tax_object->taxline( @{ $totlisthash{$tax} } );
2207 unless (ref($listref_or_error)) {
2208 $dbh->rollback if $oldAutoCommit;
2209 return $listref_or_error;
2212 warn "adding taxed tax amount ". $listref_or_error->[1].
2213 " as ". $tax_object->taxname. "\n"
2215 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2218 #consolidate and create tax line items
2219 warn "consolidating and generating...\n" if $DEBUG > 2;
2220 foreach my $taxname ( keys %taxname ) {
2223 warn "adding $taxname\n" if $DEBUG > 1;
2224 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2225 $tax += $tax{$taxitem} unless $seen{$taxitem};
2226 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2230 $tax = sprintf('%.2f', $tax );
2231 $total_setup = sprintf('%.2f', $total_setup+$tax );
2233 push @cust_bill_pkg, new FS::cust_bill_pkg {
2239 'itemdesc' => $taxname,
2244 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2246 #create the new invoice
2247 my $cust_bill = new FS::cust_bill ( {
2248 'custnum' => $self->custnum,
2249 '_date' => ( $options{'invoice_time'} || $time ),
2250 'charged' => $charged,
2252 my $error = $cust_bill->insert;
2254 $dbh->rollback if $oldAutoCommit;
2255 return "can't create invoice for customer #". $self->custnum. ": $error";
2258 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2259 $cust_bill_pkg->invnum($cust_bill->invnum);
2260 my $error = $cust_bill_pkg->insert;
2262 $dbh->rollback if $oldAutoCommit;
2263 return "can't create invoice line item: $error";
2268 foreach my $hook ( @precommit_hooks ) {
2270 &{$hook}; #($self) ?
2273 $dbh->rollback if $oldAutoCommit;
2274 return "$@ running precommit hook $hook\n";
2278 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2284 my ($self, %params) = @_;
2286 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2287 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2288 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2289 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2290 my $appended_cust_bill_pkg = $params{appended_line_items}
2291 or die "no appended line buffer specified";
2292 my $total_setup = $params{setup} or die "no setup accumulator specified";
2293 my $total_recur = $params{recur} or die "no recur accumulator specified";
2294 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2295 my $time = $params{'time'} or die "no time specified";
2296 my (%options) = %{$params{options}}; #hmmm only for 'resetup'
2299 my $real_pkgpart = $cust_pkg->pkgpart;
2300 my %hash = $cust_pkg->hash;
2301 my $old_cust_pkg = new FS::cust_pkg \%hash;
2303 $cust_pkg->pkgpart($part_pkg->pkgpart);
2304 $cust_pkg->set($_, $hash{$_}) foreach qw( setup last_bill bill );
2316 if ( ! $cust_pkg->setup &&
2318 ( $conf->exists('disable_setup_suspended_pkgs') &&
2319 ! $cust_pkg->getfield('susp')
2320 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2322 || $options{'resetup'}
2325 warn " bill setup\n" if $DEBUG > 1;
2328 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2329 return "$@ running calc_setup for $cust_pkg\n"
2332 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2334 $cust_pkg->setfield('setup', $time)
2335 unless $cust_pkg->setup;
2336 #do need it, but it won't get written to the db
2337 #|| $cust_pkg->pkgpart != $real_pkgpart;
2342 # bill recurring fee
2345 #XXX unit stuff here too
2349 if ( $part_pkg->getfield('freq') ne '0' &&
2350 ! $cust_pkg->getfield('susp') &&
2351 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2354 # XXX should this be a package event? probably. events are called
2355 # at collection time at the moment, though...
2356 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2357 if $part_pkg->can('reset_usage');
2358 #don't want to reset usage just cause we want a line item??
2359 #&& $part_pkg->pkgpart == $real_pkgpart;
2361 warn " bill recur\n" if $DEBUG > 1;
2364 # XXX shared with $recur_prog
2365 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2367 #over two params! lets at least switch to a hashref for the rest...
2368 my %param = ( 'precommit_hooks' => $precommit_hooks, );
2370 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2371 return "$@ running calc_recur for $cust_pkg\n"
2375 #change this bit to use Date::Manip? CAREFUL with timezones (see
2376 # mailing list archive)
2377 my ($sec,$min,$hour,$mday,$mon,$year) =
2378 (localtime($sdate) )[0,1,2,3,4,5];
2380 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2381 # only for figuring next bill date, nothing else, so, reset $sdate again
2383 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2384 $cust_pkg->last_bill($sdate);
2386 if ( $part_pkg->freq =~ /^\d+$/ ) {
2387 $mon += $part_pkg->freq;
2388 until ( $mon < 12 ) { $mon -= 12; $year++; }
2389 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2391 $mday += $weeks * 7;
2392 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2395 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2399 return "unparsable frequency: ". $part_pkg->freq;
2401 $cust_pkg->setfield('bill',
2402 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2406 warn "\$setup is undefined" unless defined($setup);
2407 warn "\$recur is undefined" unless defined($recur);
2408 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2411 # If there's line items, create em cust_bill_pkg records
2412 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2417 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2418 # hmm.. and if just the options are modified in some weird price plan?
2420 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2423 my $error = $cust_pkg->replace( $old_cust_pkg,
2424 'options' => { $cust_pkg->options },
2426 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2427 if $error; #just in case
2430 $setup = sprintf( "%.2f", $setup );
2431 $recur = sprintf( "%.2f", $recur );
2432 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2433 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2435 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2436 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2439 if ( $setup != 0 || $recur != 0 ) {
2441 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2443 my $cust_bill_pkg = new FS::cust_bill_pkg {
2444 'pkgnum' => $cust_pkg->pkgnum,
2446 'unitsetup' => $unitsetup,
2448 'unitrecur' => $unitrecur,
2449 'quantity' => $cust_pkg->quantity,
2451 'edate' => $cust_pkg->bill,
2452 'details' => \@details,
2454 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2455 unless $part_pkg->pkgpart == $real_pkgpart;
2456 push @$cust_bill_pkgs, $cust_bill_pkg;
2458 $$total_setup += $setup;
2459 $$total_recur += $recur;
2465 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2467 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg);
2469 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2471 } #if $setup != 0 || $recur != 0
2475 if ( $part_pkg->can('append_cust_bill_pkgs') ) {
2476 my %param = ( 'precommit_hooks' => $precommit_hooks, );
2477 my ($more_cust_bill_pkgs) =
2478 eval { $part_pkg->append_cust_bill_pkgs( $cust_pkg, \$sdate, \%param ) };
2480 return "$@ running append_cust_bill_pkgs for $cust_pkg\n"
2482 return "$more_cust_bill_pkgs"
2483 unless ( ref($more_cust_bill_pkgs) );
2485 foreach my $cust_bill_pkg ( @{$more_cust_bill_pkgs} ) {
2487 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2488 unless $part_pkg->pkgpart == $real_pkgpart;
2489 push @$appended_cust_bill_pkg, $cust_bill_pkg;
2491 $$total_setup += $cust_bill_pkg->setup;
2492 $$total_recur += $cust_bill_pkg->recur;
2498 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2500 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg);
2502 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2510 my $part_pkg = shift;
2511 my $taxlisthash = shift;
2512 my $cust_bill_pkg = shift;
2515 my @taxoverrides = $part_pkg->part_pkg_taxoverride;
2518 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2522 if ( $conf->exists('enable_taxproducts')
2523 && (scalar(@taxoverrides) || $part_pkg->taxproductnum )
2527 my @taxclassnums = ();
2528 my $geocode = $self->geocode('cch');
2530 if ( scalar( @taxoverrides ) ) {
2531 @taxclassnums = map { $_->taxclassnum } @taxoverrides;
2532 }elsif ( $part_pkg->taxproductnum ) {
2533 @taxclassnums = map { $_->taxclassnum }
2534 $part_pkg->part_pkg_taxrate('cch', $geocode);
2539 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2541 @taxes = qsearch({ 'table' => 'tax_rate',
2542 'hashref' => { 'geocode' => $geocode, },
2543 'extra_sql' => $extra_sql,
2545 if scalar(@taxclassnums);
2550 my %taxhash = map { $_ => $self->get("$prefix$_") }
2551 qw( state county country );
2553 $taxhash{'taxclass'} = $part_pkg->taxclass;
2555 @taxes = qsearch( 'cust_main_county', \%taxhash );
2558 $taxhash{'taxclass'} = '';
2559 @taxes = qsearch( 'cust_main_county', \%taxhash );
2562 #one more try at a whole-country tax rate
2564 $taxhash{$_} = '' foreach qw( state county );
2565 @taxes = qsearch( 'cust_main_county', \%taxhash );
2568 } #if $conf->exists('enable_taxproducts')
2570 # maybe eliminate this entirely, along with all the 0% records
2573 if ( $conf->exists('enable_taxproducts') ) {
2575 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2576 join('/', ( map $self->get("$prefix$_"),
2579 $part_pkg->taxproduct_description,
2580 $part_pkg->pkgpart ). "\n";
2583 "fatal: can't find tax rate for state/county/country/taxclass ".
2584 join('/', ( map $self->get("$prefix$_"),
2585 qw(state county country)
2587 $part_pkg->taxclass ). "\n";
2592 foreach my $tax ( @taxes ) {
2593 my $taxname = ref( $tax ). ' '. $tax->taxnum;
2594 if ( exists( $taxlisthash->{ $taxname } ) ) {
2595 push @{ $taxlisthash->{ $taxname } }, $cust_bill_pkg;
2597 $taxlisthash->{ $taxname } = [ $tax, $cust_bill_pkg ];
2603 =item collect OPTIONS
2605 (Attempt to) collect money for this customer's outstanding invoices (see
2606 L<FS::cust_bill>). Usually used after the bill method.
2608 Actions are now triggered by billing events; see L<FS::part_event> and the
2609 billing events web interface. Old-style invoice events (see
2610 L<FS::part_bill_event>) have been deprecated.
2612 If there is an error, returns the error, otherwise returns false.
2614 Options are passed as name-value pairs.
2616 Currently available options are:
2622 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.
2626 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2630 set true to surpress email card/ACH decline notices.
2634 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2638 allows for one time override of normal customer billing method
2642 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)
2650 my( $self, %options ) = @_;
2651 my $invoice_time = $options{'invoice_time'} || time;
2654 local $SIG{HUP} = 'IGNORE';
2655 local $SIG{INT} = 'IGNORE';
2656 local $SIG{QUIT} = 'IGNORE';
2657 local $SIG{TERM} = 'IGNORE';
2658 local $SIG{TSTP} = 'IGNORE';
2659 local $SIG{PIPE} = 'IGNORE';
2661 my $oldAutoCommit = $FS::UID::AutoCommit;
2662 local $FS::UID::AutoCommit = 0;
2665 $self->select_for_update; #mutex
2668 my $balance = $self->balance;
2669 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2672 if ( exists($options{'retry_card'}) ) {
2673 carp 'retry_card option passed to collect is deprecated; use retry';
2674 $options{'retry'} ||= $options{'retry_card'};
2676 if ( exists($options{'retry'}) && $options{'retry'} ) {
2677 my $error = $self->retry_realtime;
2679 $dbh->rollback if $oldAutoCommit;
2684 # false laziness w/pay_batch::import_results
2686 my $due_cust_event = $self->due_cust_event(
2687 'debug' => ( $options{'debug'} || 0 ),
2688 'time' => $invoice_time,
2689 'check_freq' => $options{'check_freq'},
2691 unless( ref($due_cust_event) ) {
2692 $dbh->rollback if $oldAutoCommit;
2693 return $due_cust_event;
2696 foreach my $cust_event ( @$due_cust_event ) {
2700 #re-eval event conditions (a previous event could have changed things)
2701 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2702 #don't leave stray "new/locked" records around
2703 my $error = $cust_event->delete;
2705 #gah, even with transactions
2706 $dbh->commit if $oldAutoCommit; #well.
2713 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2714 warn " running cust_event ". $cust_event->eventnum. "\n"
2718 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2719 if ( my $error = $cust_event->do_event() ) {
2720 #XXX wtf is this? figure out a proper dealio with return value
2722 # gah, even with transactions.
2723 $dbh->commit if $oldAutoCommit; #well.
2730 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2735 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2737 Inserts database records for and returns an ordered listref of new events due
2738 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2739 events are due, an empty listref is returned. If there is an error, returns a
2740 scalar error message.
2742 To actually run the events, call each event's test_condition method, and if
2743 still true, call the event's do_event method.
2745 Options are passed as a hashref or as a list of name-value pairs. Available
2752 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.
2756 "Current time" for the events.
2760 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)
2764 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2768 Explicitly pass the objects to be tested (typically used with eventtable).
2774 sub due_cust_event {
2776 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2779 #my $DEBUG = $opt{'debug'}
2780 local($DEBUG) = $opt{'debug'}
2781 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2783 warn "$me due_cust_event called with options ".
2784 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2787 $opt{'time'} ||= time;
2789 local $SIG{HUP} = 'IGNORE';
2790 local $SIG{INT} = 'IGNORE';
2791 local $SIG{QUIT} = 'IGNORE';
2792 local $SIG{TERM} = 'IGNORE';
2793 local $SIG{TSTP} = 'IGNORE';
2794 local $SIG{PIPE} = 'IGNORE';
2796 my $oldAutoCommit = $FS::UID::AutoCommit;
2797 local $FS::UID::AutoCommit = 0;
2800 $self->select_for_update; #mutex
2803 # 1: find possible events (initial search)
2806 my @cust_event = ();
2808 my @eventtable = $opt{'eventtable'}
2809 ? ( $opt{'eventtable'} )
2810 : FS::part_event->eventtables_runorder;
2812 foreach my $eventtable ( @eventtable ) {
2815 if ( $opt{'objects'} ) {
2817 @objects = @{ $opt{'objects'} };
2821 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2822 @objects = ( $eventtable eq 'cust_main' )
2824 : ( $self->$eventtable() );
2828 my @e_cust_event = ();
2830 my $cross = "CROSS JOIN $eventtable";
2831 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2832 unless $eventtable eq 'cust_main';
2834 foreach my $object ( @objects ) {
2836 #this first search uses the condition_sql magic for optimization.
2837 #the more possible events we can eliminate in this step the better
2839 my $cross_where = '';
2840 my $pkey = $object->primary_key;
2841 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2843 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2845 FS::part_event_condition->where_conditions_sql( $eventtable,
2846 'time'=>$opt{'time'}
2848 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2850 $extra_sql = "AND $extra_sql" if $extra_sql;
2852 #here is the agent virtualization
2853 $extra_sql .= " AND ( part_event.agentnum IS NULL
2854 OR part_event.agentnum = ". $self->agentnum. ' )';
2856 $extra_sql .= " $order";
2858 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2859 if $opt{'debug'} > 2;
2860 my @part_event = qsearch( {
2861 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2862 'select' => 'part_event.*',
2863 'table' => 'part_event',
2864 'addl_from' => "$cross $join",
2865 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2866 'eventtable' => $eventtable,
2869 'extra_sql' => "AND $cross_where $extra_sql",
2873 my $pkey = $object->primary_key;
2874 warn " ". scalar(@part_event).
2875 " possible events found for $eventtable ". $object->$pkey(). "\n";
2878 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2882 warn " ". scalar(@e_cust_event).
2883 " subtotal possible cust events found for $eventtable\n"
2886 push @cust_event, @e_cust_event;
2890 warn " ". scalar(@cust_event).
2891 " total possible cust events found in initial search\n"
2895 # 2: test conditions
2900 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
2901 'stats_hashref' => \%unsat ),
2904 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
2907 warn " invalid conditions not eliminated with condition_sql:\n".
2908 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
2915 foreach my $cust_event ( @cust_event ) {
2917 my $error = $cust_event->insert();
2919 $dbh->rollback if $oldAutoCommit;
2925 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2931 warn " returning events: ". Dumper(@cust_event). "\n"
2938 =item retry_realtime
2940 Schedules realtime / batch credit card / electronic check / LEC billing
2941 events for for retry. Useful if card information has changed or manual
2942 retry is desired. The 'collect' method must be called to actually retry
2945 Implementation details: For either this customer, or for each of this
2946 customer's open invoices, changes the status of the first "done" (with
2947 statustext error) realtime processing event to "failed".
2951 sub retry_realtime {
2954 local $SIG{HUP} = 'IGNORE';
2955 local $SIG{INT} = 'IGNORE';
2956 local $SIG{QUIT} = 'IGNORE';
2957 local $SIG{TERM} = 'IGNORE';
2958 local $SIG{TSTP} = 'IGNORE';
2959 local $SIG{PIPE} = 'IGNORE';
2961 my $oldAutoCommit = $FS::UID::AutoCommit;
2962 local $FS::UID::AutoCommit = 0;
2965 #a little false laziness w/due_cust_event (not too bad, really)
2967 my $join = FS::part_event_condition->join_conditions_sql;
2968 my $order = FS::part_event_condition->order_conditions_sql;
2971 . join ( ' OR ' , map {
2972 "( part_event.eventtable = " . dbh->quote($_)
2973 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
2974 } FS::part_event->eventtables)
2977 #here is the agent virtualization
2978 my $agent_virt = " ( part_event.agentnum IS NULL
2979 OR part_event.agentnum = ". $self->agentnum. ' )';
2981 #XXX this shouldn't be hardcoded, actions should declare it...
2982 my @realtime_events = qw(
2983 cust_bill_realtime_card
2984 cust_bill_realtime_check
2985 cust_bill_realtime_lec
2989 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
2994 my @cust_event = qsearchs({
2995 'table' => 'cust_event',
2996 'select' => 'cust_event.*',
2997 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
2998 'hashref' => { 'status' => 'done' },
2999 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3000 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3003 my %seen_invnum = ();
3004 foreach my $cust_event (@cust_event) {
3006 #max one for the customer, one for each open invoice
3007 my $cust_X = $cust_event->cust_X;
3008 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3012 or $cust_event->part_event->eventtable eq 'cust_bill'
3015 my $error = $cust_event->retry;
3017 $dbh->rollback if $oldAutoCommit;
3018 return "error scheduling event for retry: $error";
3023 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3028 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3030 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3031 via a Business::OnlinePayment realtime gateway. See
3032 L<http://420.am/business-onlinepayment> for supported gateways.
3034 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3036 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3038 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3039 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3040 if set, will override the value from the customer record.
3042 I<description> is a free-text field passed to the gateway. It defaults to
3043 "Internet services".
3045 If an I<invnum> is specified, this payment (if successful) is applied to the
3046 specified invoice. If you don't specify an I<invnum> you might want to
3047 call the B<apply_payments> method.
3049 I<quiet> can be set true to surpress email decline notices.
3051 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3052 resulting paynum, if any.
3054 I<payunique> is a unique identifier for this payment.
3056 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3061 my( $self, $method, $amount, %options ) = @_;
3063 warn "$me realtime_bop: $method $amount\n";
3064 warn " $_ => $options{$_}\n" foreach keys %options;
3067 $options{'description'} ||= 'Internet services';
3069 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3071 eval "use Business::OnlinePayment";
3074 my $payinfo = exists($options{'payinfo'})
3075 ? $options{'payinfo'}
3078 my %method2payby = (
3085 # check for banned credit card/ACH
3088 my $ban = qsearchs('banned_pay', {
3089 'payby' => $method2payby{$method},
3090 'payinfo' => md5_base64($payinfo),
3092 return "Banned credit card" if $ban;
3099 if ( $options{'invnum'} ) {
3100 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3101 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3103 map { $_->part_pkg->taxclass }
3105 map { $_->cust_pkg }
3106 $cust_bill->cust_bill_pkg;
3107 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3108 #different taxclasses
3109 $taxclass = $taxclasses[0];
3113 #look for an agent gateway override first
3115 if ( $method eq 'CC' ) {
3116 $cardtype = cardtype($payinfo);
3117 } elsif ( $method eq 'ECHECK' ) {
3120 $cardtype = $method;
3124 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3125 cardtype => $cardtype,
3126 taxclass => $taxclass, } )
3127 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3129 taxclass => $taxclass, } )
3130 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3131 cardtype => $cardtype,
3133 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3135 taxclass => '', } );
3137 my $payment_gateway = '';
3138 my( $processor, $login, $password, $action, @bop_options );
3139 if ( $override ) { #use a payment gateway override
3141 $payment_gateway = $override->payment_gateway;
3143 $processor = $payment_gateway->gateway_module;
3144 $login = $payment_gateway->gateway_username;
3145 $password = $payment_gateway->gateway_password;
3146 $action = $payment_gateway->gateway_action;
3147 @bop_options = $payment_gateway->options;
3149 } else { #use the standard settings from the config
3151 ( $processor, $login, $password, $action, @bop_options ) =
3152 $self->default_payment_gateway($method);
3160 my $address = exists($options{'address1'})
3161 ? $options{'address1'}
3163 my $address2 = exists($options{'address2'})
3164 ? $options{'address2'}
3166 $address .= ", ". $address2 if length($address2);
3168 my $o_payname = exists($options{'payname'})
3169 ? $options{'payname'}
3171 my($payname, $payfirst, $paylast);
3172 if ( $o_payname && $method ne 'ECHECK' ) {
3173 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3174 or return "Illegal payname $payname";
3175 ($payfirst, $paylast) = ($1, $2);
3177 $payfirst = $self->getfield('first');
3178 $paylast = $self->getfield('last');
3179 $payname = "$payfirst $paylast";
3182 my @invoicing_list = $self->invoicing_list_emailonly;
3183 if ( $conf->exists('emailinvoiceautoalways')
3184 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3185 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3186 push @invoicing_list, $self->all_emails;
3189 my $email = ($conf->exists('business-onlinepayment-email-override'))
3190 ? $conf->config('business-onlinepayment-email-override')
3191 : $invoicing_list[0];
3195 my $payip = exists($options{'payip'})
3198 $content{customer_ip} = $payip
3201 $content{invoice_number} = $options{'invnum'}
3202 if exists($options{'invnum'}) && length($options{'invnum'});
3204 $content{email_customer} =
3205 ( $conf->exists('business-onlinepayment-email_customer')
3206 || $conf->exists('business-onlinepayment-email-override') );
3209 if ( $method eq 'CC' ) {
3211 $content{card_number} = $payinfo;
3212 $paydate = exists($options{'paydate'})
3213 ? $options{'paydate'}
3215 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3216 $content{expiration} = "$2/$1";
3218 my $paycvv = exists($options{'paycvv'})
3219 ? $options{'paycvv'}
3221 $content{cvv2} = $paycvv
3224 my $paystart_month = exists($options{'paystart_month'})
3225 ? $options{'paystart_month'}
3226 : $self->paystart_month;
3228 my $paystart_year = exists($options{'paystart_year'})
3229 ? $options{'paystart_year'}
3230 : $self->paystart_year;
3232 $content{card_start} = "$paystart_month/$paystart_year"
3233 if $paystart_month && $paystart_year;
3235 my $payissue = exists($options{'payissue'})
3236 ? $options{'payissue'}
3238 $content{issue_number} = $payissue if $payissue;
3240 $content{recurring_billing} = 'YES'
3241 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3243 'payinfo' => $payinfo,
3245 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3247 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3251 } elsif ( $method eq 'ECHECK' ) {
3252 ( $content{account_number}, $content{routing_code} ) =
3253 split('@', $payinfo);
3254 $content{bank_name} = $o_payname;
3255 $content{bank_state} = exists($options{'paystate'})
3256 ? $options{'paystate'}
3257 : $self->getfield('paystate');
3258 $content{account_type} = exists($options{'paytype'})
3259 ? uc($options{'paytype'}) || 'CHECKING'
3260 : uc($self->getfield('paytype')) || 'CHECKING';
3261 $content{account_name} = $payname;
3262 $content{customer_org} = $self->company ? 'B' : 'I';
3263 $content{state_id} = exists($options{'stateid'})
3264 ? $options{'stateid'}
3265 : $self->getfield('stateid');
3266 $content{state_id_state} = exists($options{'stateid_state'})
3267 ? $options{'stateid_state'}
3268 : $self->getfield('stateid_state');
3269 $content{customer_ssn} = exists($options{'ss'})
3272 } elsif ( $method eq 'LEC' ) {
3273 $content{phone} = $payinfo;
3277 # run transaction(s)
3280 my $balance = exists( $options{'balance'} )
3281 ? $options{'balance'}
3284 $self->select_for_update; #mutex ... just until we get our pending record in
3286 #the checks here are intended to catch concurrent payments
3287 #double-form-submission prevention is taken care of in cust_pay_pending::check
3290 return "The customer's balance has changed; $method transaction aborted."
3291 if $self->balance < $balance;
3292 #&& $self->balance < $amount; #might as well anyway?
3294 #also check and make sure there aren't *other* pending payments for this cust
3296 my @pending = qsearch('cust_pay_pending', {
3297 'custnum' => $self->custnum,
3298 'status' => { op=>'!=', value=>'done' }
3300 return "A payment is already being processed for this customer (".
3301 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3302 "); $method transaction aborted."
3303 if scalar(@pending);
3305 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3307 my $cust_pay_pending = new FS::cust_pay_pending {
3308 'custnum' => $self->custnum,
3309 #'invnum' => $options{'invnum'},
3312 'payby' => $method2payby{$method},
3313 'payinfo' => $payinfo,
3314 'paydate' => $paydate,
3316 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3318 $cust_pay_pending->payunique( $options{payunique} )
3319 if defined($options{payunique}) && length($options{payunique});
3320 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3321 return $cpp_new_err if $cpp_new_err;
3323 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3325 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3326 $transaction->content(
3329 'password' => $password,
3330 'action' => $action1,
3331 'description' => $options{'description'},
3332 'amount' => $amount,
3333 #'invoice_number' => $options{'invnum'},
3334 'customer_id' => $self->custnum,
3335 'last_name' => $paylast,
3336 'first_name' => $payfirst,
3338 'address' => $address,
3339 'city' => ( exists($options{'city'})
3342 'state' => ( exists($options{'state'})
3345 'zip' => ( exists($options{'zip'})
3348 'country' => ( exists($options{'country'})
3349 ? $options{'country'}
3351 'referer' => 'http://cleanwhisker.420.am/',
3353 'phone' => $self->daytime || $self->night,
3357 $cust_pay_pending->status('pending');
3358 my $cpp_pending_err = $cust_pay_pending->replace;
3359 return $cpp_pending_err if $cpp_pending_err;
3362 my $BOP_TESTING = 0;
3363 my $BOP_TESTING_SUCCESS = 1;
3365 unless ( $BOP_TESTING ) {
3366 $transaction->submit();
3368 if ( $BOP_TESTING_SUCCESS ) {
3369 $transaction->is_success(1);
3370 $transaction->authorization('fake auth');
3372 $transaction->is_success(0);
3373 $transaction->error_message('fake failure');
3377 if ( $transaction->is_success() && $action2 ) {
3379 $cust_pay_pending->status('authorized');
3380 my $cpp_authorized_err = $cust_pay_pending->replace;
3381 return $cpp_authorized_err if $cpp_authorized_err;
3383 my $auth = $transaction->authorization;
3384 my $ordernum = $transaction->can('order_number')
3385 ? $transaction->order_number
3389 new Business::OnlinePayment( $processor, @bop_options );
3396 password => $password,
3397 order_number => $ordernum,
3399 authorization => $auth,
3400 description => $options{'description'},
3403 foreach my $field (qw( authorization_source_code returned_ACI
3404 transaction_identifier validation_code
3405 transaction_sequence_num local_transaction_date
3406 local_transaction_time AVS_result_code )) {
3407 $capture{$field} = $transaction->$field() if $transaction->can($field);
3410 $capture->content( %capture );
3414 unless ( $capture->is_success ) {
3415 my $e = "Authorization successful but capture failed, custnum #".
3416 $self->custnum. ': '. $capture->result_code.
3417 ": ". $capture->error_message;
3424 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3425 my $cpp_captured_err = $cust_pay_pending->replace;
3426 return $cpp_captured_err if $cpp_captured_err;
3429 # remove paycvv after initial transaction
3432 #false laziness w/misc/process/payment.cgi - check both to make sure working
3434 if ( defined $self->dbdef_table->column('paycvv')
3435 && length($self->paycvv)
3436 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3438 my $error = $self->remove_cvv;
3440 warn "WARNING: error removing cvv: $error\n";
3448 if ( $transaction->is_success() ) {
3451 if ( $payment_gateway ) { # agent override
3452 $paybatch = $payment_gateway->gatewaynum. '-';
3455 $paybatch .= "$processor:". $transaction->authorization;
3457 $paybatch .= ':'. $transaction->order_number
3458 if $transaction->can('order_number')
3459 && length($transaction->order_number);
3461 my $cust_pay = new FS::cust_pay ( {
3462 'custnum' => $self->custnum,
3463 'invnum' => $options{'invnum'},
3466 'payby' => $method2payby{$method},
3467 'payinfo' => $payinfo,
3468 'paybatch' => $paybatch,
3469 'paydate' => $paydate,
3471 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3472 $cust_pay->payunique( $options{payunique} )
3473 if defined($options{payunique}) && length($options{payunique});
3475 my $oldAutoCommit = $FS::UID::AutoCommit;
3476 local $FS::UID::AutoCommit = 0;
3479 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3481 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3484 $cust_pay->invnum(''); #try again with no specific invnum
3485 my $error2 = $cust_pay->insert( $options{'manual'} ?
3486 ( 'manual' => 1 ) : ()
3489 # gah. but at least we have a record of the state we had to abort in
3490 # from cust_pay_pending now.
3491 my $e = "WARNING: $method captured but payment not recorded - ".
3492 "error inserting payment ($processor): $error2".
3493 " (previously tried insert with invnum #$options{'invnum'}" .
3494 ": $error ) - pending payment saved as paypendingnum ".
3495 $cust_pay_pending->paypendingnum. "\n";
3501 if ( $options{'paynum_ref'} ) {
3502 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3505 $cust_pay_pending->status('done');
3506 $cust_pay_pending->statustext('captured');
3507 my $cpp_done_err = $cust_pay_pending->replace;
3509 if ( $cpp_done_err ) {
3511 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3512 my $e = "WARNING: $method captured but payment not recorded - ".
3513 "error updating status for paypendingnum ".
3514 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3520 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3521 return ''; #no error
3527 my $perror = "$processor error: ". $transaction->error_message;
3529 unless ( $transaction->error_message ) {
3532 if ( $transaction->can('response_page') ) {
3534 'page' => ( $transaction->can('response_page')
3535 ? $transaction->response_page
3538 'code' => ( $transaction->can('response_code')
3539 ? $transaction->response_code
3542 'headers' => ( $transaction->can('response_headers')
3543 ? $transaction->response_headers
3549 "No additional debugging information available for $processor";
3552 $perror .= "No error_message returned from $processor -- ".
3553 ( ref($t_response) ? Dumper($t_response) : $t_response );
3557 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3558 && $conf->exists('emaildecline')
3559 && grep { $_ ne 'POST' } $self->invoicing_list
3560 && ! grep { $transaction->error_message =~ /$_/ }
3561 $conf->config('emaildecline-exclude')
3563 my @templ = $conf->config('declinetemplate');
3564 my $template = new Text::Template (
3566 SOURCE => [ map "$_\n", @templ ],
3567 ) or return "($perror) can't create template: $Text::Template::ERROR";
3568 $template->compile()
3569 or return "($perror) can't compile template: $Text::Template::ERROR";
3571 my $templ_hash = { error => $transaction->error_message };
3573 my $error = send_email(
3574 'from' => $conf->config('invoice_from'),
3575 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3576 'subject' => 'Your payment could not be processed',
3577 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3580 $perror .= " (also received error sending decline notification: $error)"
3585 $cust_pay_pending->status('done');
3586 $cust_pay_pending->statustext("declined: $perror");
3587 my $cpp_done_err = $cust_pay_pending->replace;
3588 if ( $cpp_done_err ) {
3589 my $e = "WARNING: $method declined but pending payment not resolved - ".
3590 "error updating status for paypendingnum ".
3591 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3593 $perror = "$e ($perror)";
3606 my( $self, $method, $amount, %options ) = @_;
3608 if ( $options{'fake_failure'} ) {
3609 return "Error: No error; test failure requested with fake_failure";
3612 my %method2payby = (
3619 #if ( $payment_gateway ) { # agent override
3620 # $paybatch = $payment_gateway->gatewaynum. '-';
3623 #$paybatch .= "$processor:". $transaction->authorization;
3625 #$paybatch .= ':'. $transaction->order_number
3626 # if $transaction->can('order_number')
3627 # && length($transaction->order_number);
3629 my $paybatch = 'FakeProcessor:54:32';
3631 my $cust_pay = new FS::cust_pay ( {
3632 'custnum' => $self->custnum,
3633 'invnum' => $options{'invnum'},
3636 'payby' => $method2payby{$method},
3637 #'payinfo' => $payinfo,
3638 'payinfo' => '4111111111111111',
3639 'paybatch' => $paybatch,
3640 #'paydate' => $paydate,
3641 'paydate' => '2012-05-01',
3643 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3645 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3648 $cust_pay->invnum(''); #try again with no specific invnum
3649 my $error2 = $cust_pay->insert( $options{'manual'} ?
3650 ( 'manual' => 1 ) : ()
3653 # gah, even with transactions.
3654 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3655 "error inserting (fake!) payment: $error2".
3656 " (previously tried insert with invnum #$options{'invnum'}" .
3663 if ( $options{'paynum_ref'} ) {
3664 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3667 return ''; #no error
3671 =item default_payment_gateway
3675 sub default_payment_gateway {
3676 my( $self, $method ) = @_;
3678 die "Real-time processing not enabled\n"
3679 unless $conf->exists('business-onlinepayment');
3682 my $bop_config = 'business-onlinepayment';
3683 $bop_config .= '-ach'
3684 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3685 my ( $processor, $login, $password, $action, @bop_options ) =
3686 $conf->config($bop_config);
3687 $action ||= 'normal authorization';
3688 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3689 die "No real-time processor is enabled - ".
3690 "did you set the business-onlinepayment configuration value?\n"
3693 ( $processor, $login, $password, $action, @bop_options )
3698 Removes the I<paycvv> field from the database directly.
3700 If there is an error, returns the error, otherwise returns false.
3706 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3707 or return dbh->errstr;
3708 $sth->execute($self->custnum)
3709 or return $sth->errstr;
3714 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3716 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3717 via a Business::OnlinePayment realtime gateway. See
3718 L<http://420.am/business-onlinepayment> for supported gateways.
3720 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3722 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3724 Most gateways require a reference to an original payment transaction to refund,
3725 so you probably need to specify a I<paynum>.
3727 I<amount> defaults to the original amount of the payment if not specified.
3729 I<reason> specifies a reason for the refund.
3731 I<paydate> specifies the expiration date for a credit card overriding the
3732 value from the customer record or the payment record. Specified as yyyy-mm-dd
3734 Implementation note: If I<amount> is unspecified or equal to the amount of the
3735 orignal payment, first an attempt is made to "void" the transaction via
3736 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3737 the normal attempt is made to "refund" ("credit") the transaction via the
3738 gateway is attempted.
3740 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3741 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3742 #if set, will override the value from the customer record.
3744 #If an I<invnum> is specified, this payment (if successful) is applied to the
3745 #specified invoice. If you don't specify an I<invnum> you might want to
3746 #call the B<apply_payments> method.
3750 #some false laziness w/realtime_bop, not enough to make it worth merging
3751 #but some useful small subs should be pulled out
3752 sub realtime_refund_bop {
3753 my( $self, $method, %options ) = @_;
3755 warn "$me realtime_refund_bop: $method refund\n";
3756 warn " $_ => $options{$_}\n" foreach keys %options;
3759 eval "use Business::OnlinePayment";
3763 # look up the original payment and optionally a gateway for that payment
3767 my $amount = $options{'amount'};
3769 my( $processor, $login, $password, @bop_options ) ;
3770 my( $auth, $order_number ) = ( '', '', '' );
3772 if ( $options{'paynum'} ) {
3774 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3775 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3776 or return "Unknown paynum $options{'paynum'}";
3777 $amount ||= $cust_pay->paid;
3779 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3780 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3781 $cust_pay->paybatch;
3782 my $gatewaynum = '';
3783 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3785 if ( $gatewaynum ) { #gateway for the payment to be refunded
3787 my $payment_gateway =
3788 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3789 die "payment gateway $gatewaynum not found"
3790 unless $payment_gateway;
3792 $processor = $payment_gateway->gateway_module;
3793 $login = $payment_gateway->gateway_username;
3794 $password = $payment_gateway->gateway_password;
3795 @bop_options = $payment_gateway->options;
3797 } else { #try the default gateway
3799 my( $conf_processor, $unused_action );
3800 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3801 $self->default_payment_gateway($method);
3803 return "processor of payment $options{'paynum'} $processor does not".
3804 " match default processor $conf_processor"
3805 unless $processor eq $conf_processor;
3810 } else { # didn't specify a paynum, so look for agent gateway overrides
3811 # like a normal transaction
3814 if ( $method eq 'CC' ) {
3815 $cardtype = cardtype($self->payinfo);
3816 } elsif ( $method eq 'ECHECK' ) {
3819 $cardtype = $method;
3822 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3823 cardtype => $cardtype,
3825 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3827 taxclass => '', } );
3829 if ( $override ) { #use a payment gateway override
3831 my $payment_gateway = $override->payment_gateway;
3833 $processor = $payment_gateway->gateway_module;
3834 $login = $payment_gateway->gateway_username;
3835 $password = $payment_gateway->gateway_password;
3836 #$action = $payment_gateway->gateway_action;
3837 @bop_options = $payment_gateway->options;
3839 } else { #use the standard settings from the config
3842 ( $processor, $login, $password, $unused_action, @bop_options ) =
3843 $self->default_payment_gateway($method);
3848 return "neither amount nor paynum specified" unless $amount;
3853 'password' => $password,
3854 'order_number' => $order_number,
3855 'amount' => $amount,
3856 'referer' => 'http://cleanwhisker.420.am/',
3858 $content{authorization} = $auth
3859 if length($auth); #echeck/ACH transactions have an order # but no auth
3860 #(at least with authorize.net)
3862 my $disable_void_after;
3863 if ($conf->exists('disable_void_after')
3864 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3865 $disable_void_after = $1;
3868 #first try void if applicable
3869 if ( $cust_pay && $cust_pay->paid == $amount
3871 ( not defined($disable_void_after) )
3872 || ( time < ($cust_pay->_date + $disable_void_after ) )
3875 warn " attempting void\n" if $DEBUG > 1;
3876 my $void = new Business::OnlinePayment( $processor, @bop_options );
3877 $void->content( 'action' => 'void', %content );
3879 if ( $void->is_success ) {
3880 my $error = $cust_pay->void($options{'reason'});
3882 # gah, even with transactions.
3883 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3884 "error voiding payment: $error";
3888 warn " void successful\n" if $DEBUG > 1;
3893 warn " void unsuccessful, trying refund\n"
3897 my $address = $self->address1;
3898 $address .= ", ". $self->address2 if $self->address2;
3900 my($payname, $payfirst, $paylast);
3901 if ( $self->payname && $method ne 'ECHECK' ) {
3902 $payname = $self->payname;
3903 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3904 or return "Illegal payname $payname";
3905 ($payfirst, $paylast) = ($1, $2);
3907 $payfirst = $self->getfield('first');
3908 $paylast = $self->getfield('last');
3909 $payname = "$payfirst $paylast";
3912 my @invoicing_list = $self->invoicing_list_emailonly;
3913 if ( $conf->exists('emailinvoiceautoalways')
3914 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3915 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3916 push @invoicing_list, $self->all_emails;
3919 my $email = ($conf->exists('business-onlinepayment-email-override'))
3920 ? $conf->config('business-onlinepayment-email-override')
3921 : $invoicing_list[0];
3923 my $payip = exists($options{'payip'})
3926 $content{customer_ip} = $payip
3930 if ( $method eq 'CC' ) {
3933 $content{card_number} = $payinfo = $cust_pay->payinfo;
3934 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3935 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3936 ($content{expiration} = "$2/$1"); # where available
3938 $content{card_number} = $payinfo = $self->payinfo;
3939 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3940 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3941 $content{expiration} = "$2/$1";
3944 } elsif ( $method eq 'ECHECK' ) {
3947 $payinfo = $cust_pay->payinfo;
3949 $payinfo = $self->payinfo;
3951 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3952 $content{bank_name} = $self->payname;
3953 $content{account_type} = 'CHECKING';
3954 $content{account_name} = $payname;
3955 $content{customer_org} = $self->company ? 'B' : 'I';
3956 $content{customer_ssn} = $self->ss;
3957 } elsif ( $method eq 'LEC' ) {
3958 $content{phone} = $payinfo = $self->payinfo;
3962 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3963 my %sub_content = $refund->content(
3964 'action' => 'credit',
3965 'customer_id' => $self->custnum,
3966 'last_name' => $paylast,
3967 'first_name' => $payfirst,
3969 'address' => $address,
3970 'city' => $self->city,
3971 'state' => $self->state,
3972 'zip' => $self->zip,
3973 'country' => $self->country,
3975 'phone' => $self->daytime || $self->night,
3978 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3982 return "$processor error: ". $refund->error_message
3983 unless $refund->is_success();
3985 my %method2payby = (
3991 my $paybatch = "$processor:". $refund->authorization;
3992 $paybatch .= ':'. $refund->order_number
3993 if $refund->can('order_number') && $refund->order_number;
3995 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3996 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3997 last unless @cust_bill_pay;
3998 my $cust_bill_pay = pop @cust_bill_pay;
3999 my $error = $cust_bill_pay->delete;
4003 my $cust_refund = new FS::cust_refund ( {
4004 'custnum' => $self->custnum,
4005 'paynum' => $options{'paynum'},
4006 'refund' => $amount,
4008 'payby' => $method2payby{$method},
4009 'payinfo' => $payinfo,
4010 'paybatch' => $paybatch,
4011 'reason' => $options{'reason'} || 'card or ACH refund',
4013 my $error = $cust_refund->insert;
4015 $cust_refund->paynum(''); #try again with no specific paynum
4016 my $error2 = $cust_refund->insert;
4018 # gah, even with transactions.
4019 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4020 "error inserting refund ($processor): $error2".
4021 " (previously tried insert with paynum #$options{'paynum'}" .
4032 =item batch_card OPTION => VALUE...
4034 Adds a payment for this invoice to the pending credit card batch (see
4035 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4036 runs the payment using a realtime gateway.
4041 my ($self, %options) = @_;
4044 if (exists($options{amount})) {
4045 $amount = $options{amount};
4047 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4049 return '' unless $amount > 0;
4051 my $invnum = delete $options{invnum};
4052 my $payby = $options{invnum} || $self->payby; #dubious
4054 if ($options{'realtime'}) {
4055 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4061 my $oldAutoCommit = $FS::UID::AutoCommit;
4062 local $FS::UID::AutoCommit = 0;
4065 #this needs to handle mysql as well as Pg, like svc_acct.pm
4066 #(make it into a common function if folks need to do batching with mysql)
4067 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4068 or return "Cannot lock pay_batch: " . $dbh->errstr;
4072 'payby' => FS::payby->payby2payment($payby),
4075 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4077 unless ( $pay_batch ) {
4078 $pay_batch = new FS::pay_batch \%pay_batch;
4079 my $error = $pay_batch->insert;
4081 $dbh->rollback if $oldAutoCommit;
4082 die "error creating new batch: $error\n";
4086 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4087 'batchnum' => $pay_batch->batchnum,
4088 'custnum' => $self->custnum,
4091 foreach (qw( address1 address2 city state zip country payby payinfo paydate
4093 $options{$_} = '' unless exists($options{$_});
4096 my $cust_pay_batch = new FS::cust_pay_batch ( {
4097 'batchnum' => $pay_batch->batchnum,
4098 'invnum' => $invnum || 0, # is there a better value?
4099 # this field should be
4101 # cust_bill_pay_batch now
4102 'custnum' => $self->custnum,
4103 'last' => $self->getfield('last'),
4104 'first' => $self->getfield('first'),
4105 'address1' => $options{address1} || $self->address1,
4106 'address2' => $options{address2} || $self->address2,
4107 'city' => $options{city} || $self->city,
4108 'state' => $options{state} || $self->state,
4109 'zip' => $options{zip} || $self->zip,
4110 'country' => $options{country} || $self->country,
4111 'payby' => $options{payby} || $self->payby,
4112 'payinfo' => $options{payinfo} || $self->payinfo,
4113 'exp' => $options{paydate} || $self->paydate,
4114 'payname' => $options{payname} || $self->payname,
4115 'amount' => $amount, # consolidating
4118 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4119 if $old_cust_pay_batch;
4122 if ($old_cust_pay_batch) {
4123 $error = $cust_pay_batch->replace($old_cust_pay_batch)
4125 $error = $cust_pay_batch->insert;
4129 $dbh->rollback if $oldAutoCommit;
4133 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
4134 foreach my $cust_bill ($self->open_cust_bill) {
4135 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4136 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4137 'invnum' => $cust_bill->invnum,
4138 'paybatchnum' => $cust_pay_batch->paybatchnum,
4139 'amount' => $cust_bill->owed,
4142 if ($unapplied >= $cust_bill_pay_batch->amount){
4143 $unapplied -= $cust_bill_pay_batch->amount;
4146 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4147 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4149 $error = $cust_bill_pay_batch->insert;
4151 $dbh->rollback if $oldAutoCommit;
4156 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4162 Returns the total owed for this customer on all invoices
4163 (see L<FS::cust_bill/owed>).
4169 $self->total_owed_date(2145859200); #12/31/2037
4172 =item total_owed_date TIME
4174 Returns the total owed for this customer on all invoices with date earlier than
4175 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4176 see L<Time::Local> and L<Date::Parse> for conversion functions.
4180 sub total_owed_date {
4184 foreach my $cust_bill (
4185 grep { $_->_date <= $time }
4186 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4188 $total_bill += $cust_bill->owed;
4190 sprintf( "%.2f", $total_bill );
4193 =item apply_payments_and_credits
4195 Applies unapplied payments and credits.
4197 In most cases, this new method should be used in place of sequential
4198 apply_payments and apply_credits methods.
4200 If there is an error, returns the error, otherwise returns false.
4204 sub apply_payments_and_credits {
4207 local $SIG{HUP} = 'IGNORE';
4208 local $SIG{INT} = 'IGNORE';
4209 local $SIG{QUIT} = 'IGNORE';
4210 local $SIG{TERM} = 'IGNORE';
4211 local $SIG{TSTP} = 'IGNORE';
4212 local $SIG{PIPE} = 'IGNORE';
4214 my $oldAutoCommit = $FS::UID::AutoCommit;
4215 local $FS::UID::AutoCommit = 0;
4218 $self->select_for_update; #mutex
4220 foreach my $cust_bill ( $self->open_cust_bill ) {
4221 my $error = $cust_bill->apply_payments_and_credits;
4223 $dbh->rollback if $oldAutoCommit;
4224 return "Error applying: $error";
4228 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4233 =item apply_credits OPTION => VALUE ...
4235 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4236 to outstanding invoice balances in chronological order (or reverse
4237 chronological order if the I<order> option is set to B<newest>) and returns the
4238 value of any remaining unapplied credits available for refund (see
4239 L<FS::cust_refund>).
4241 Dies if there is an error.
4249 local $SIG{HUP} = 'IGNORE';
4250 local $SIG{INT} = 'IGNORE';
4251 local $SIG{QUIT} = 'IGNORE';
4252 local $SIG{TERM} = 'IGNORE';
4253 local $SIG{TSTP} = 'IGNORE';
4254 local $SIG{PIPE} = 'IGNORE';
4256 my $oldAutoCommit = $FS::UID::AutoCommit;
4257 local $FS::UID::AutoCommit = 0;
4260 $self->select_for_update; #mutex
4262 unless ( $self->total_credited ) {
4263 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4267 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4268 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4270 my @invoices = $self->open_cust_bill;
4271 @invoices = sort { $b->_date <=> $a->_date } @invoices
4272 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4275 foreach my $cust_bill ( @invoices ) {
4278 if ( !defined($credit) || $credit->credited == 0) {
4279 $credit = pop @credits or last;
4282 if ($cust_bill->owed >= $credit->credited) {
4283 $amount=$credit->credited;
4285 $amount=$cust_bill->owed;
4288 my $cust_credit_bill = new FS::cust_credit_bill ( {
4289 'crednum' => $credit->crednum,
4290 'invnum' => $cust_bill->invnum,
4291 'amount' => $amount,
4293 my $error = $cust_credit_bill->insert;
4295 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4299 redo if ($cust_bill->owed > 0);
4303 my $total_credited = $self->total_credited;
4305 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4307 return $total_credited;
4310 =item apply_payments
4312 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4313 to outstanding invoice balances in chronological order.
4315 #and returns the value of any remaining unapplied payments.
4317 Dies if there is an error.
4321 sub apply_payments {
4324 local $SIG{HUP} = 'IGNORE';
4325 local $SIG{INT} = 'IGNORE';
4326 local $SIG{QUIT} = 'IGNORE';
4327 local $SIG{TERM} = 'IGNORE';
4328 local $SIG{TSTP} = 'IGNORE';
4329 local $SIG{PIPE} = 'IGNORE';
4331 my $oldAutoCommit = $FS::UID::AutoCommit;
4332 local $FS::UID::AutoCommit = 0;
4335 $self->select_for_update; #mutex
4339 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4340 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4342 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4343 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4347 foreach my $cust_bill ( @invoices ) {
4350 if ( !defined($payment) || $payment->unapplied == 0 ) {
4351 $payment = pop @payments or last;
4354 if ( $cust_bill->owed >= $payment->unapplied ) {
4355 $amount = $payment->unapplied;
4357 $amount = $cust_bill->owed;
4360 my $cust_bill_pay = new FS::cust_bill_pay ( {
4361 'paynum' => $payment->paynum,
4362 'invnum' => $cust_bill->invnum,
4363 'amount' => $amount,
4365 my $error = $cust_bill_pay->insert;
4367 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4371 redo if ( $cust_bill->owed > 0);
4375 my $total_unapplied_payments = $self->total_unapplied_payments;
4377 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4379 return $total_unapplied_payments;
4382 =item total_credited
4384 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4385 customer. See L<FS::cust_credit/credited>.
4389 sub total_credited {
4391 my $total_credit = 0;
4392 foreach my $cust_credit ( qsearch('cust_credit', {
4393 'custnum' => $self->custnum,
4395 $total_credit += $cust_credit->credited;
4397 sprintf( "%.2f", $total_credit );
4400 =item total_unapplied_payments
4402 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4403 See L<FS::cust_pay/unapplied>.
4407 sub total_unapplied_payments {
4409 my $total_unapplied = 0;
4410 foreach my $cust_pay ( qsearch('cust_pay', {
4411 'custnum' => $self->custnum,
4413 $total_unapplied += $cust_pay->unapplied;
4415 sprintf( "%.2f", $total_unapplied );
4418 =item total_unapplied_refunds
4420 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4421 customer. See L<FS::cust_refund/unapplied>.
4425 sub total_unapplied_refunds {
4427 my $total_unapplied = 0;
4428 foreach my $cust_refund ( qsearch('cust_refund', {
4429 'custnum' => $self->custnum,
4431 $total_unapplied += $cust_refund->unapplied;
4433 sprintf( "%.2f", $total_unapplied );
4438 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4439 total_credited minus total_unapplied_payments).
4447 + $self->total_unapplied_refunds
4448 - $self->total_credited
4449 - $self->total_unapplied_payments
4453 =item balance_date TIME
4455 Returns the balance for this customer, only considering invoices with date
4456 earlier than TIME (total_owed_date minus total_credited minus
4457 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4458 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4467 $self->total_owed_date($time)
4468 + $self->total_unapplied_refunds
4469 - $self->total_credited
4470 - $self->total_unapplied_payments
4474 =item in_transit_payments
4476 Returns the total of requests for payments for this customer pending in
4477 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4481 sub in_transit_payments {
4483 my $in_transit_payments = 0;
4484 foreach my $pay_batch ( qsearch('pay_batch', {
4487 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4488 'batchnum' => $pay_batch->batchnum,
4489 'custnum' => $self->custnum,
4491 $in_transit_payments += $cust_pay_batch->amount;
4494 sprintf( "%.2f", $in_transit_payments );
4497 =item paydate_monthyear
4499 Returns a two-element list consisting of the month and year of this customer's
4500 paydate (credit card expiration date for CARD customers)
4504 sub paydate_monthyear {
4506 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4508 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4515 =item invoicing_list [ ARRAYREF ]
4517 If an arguement is given, sets these email addresses as invoice recipients
4518 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4519 (except as warnings), so use check_invoicing_list first.
4521 Returns a list of email addresses (with svcnum entries expanded).
4523 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4524 check it without disturbing anything by passing nothing.
4526 This interface may change in the future.
4530 sub invoicing_list {
4531 my( $self, $arrayref ) = @_;
4534 my @cust_main_invoice;
4535 if ( $self->custnum ) {
4536 @cust_main_invoice =
4537 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4539 @cust_main_invoice = ();
4541 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4542 #warn $cust_main_invoice->destnum;
4543 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4544 #warn $cust_main_invoice->destnum;
4545 my $error = $cust_main_invoice->delete;
4546 warn $error if $error;
4549 if ( $self->custnum ) {
4550 @cust_main_invoice =
4551 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4553 @cust_main_invoice = ();
4555 my %seen = map { $_->address => 1 } @cust_main_invoice;
4556 foreach my $address ( @{$arrayref} ) {
4557 next if exists $seen{$address} && $seen{$address};
4558 $seen{$address} = 1;
4559 my $cust_main_invoice = new FS::cust_main_invoice ( {
4560 'custnum' => $self->custnum,
4563 my $error = $cust_main_invoice->insert;
4564 warn $error if $error;
4568 if ( $self->custnum ) {
4570 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4577 =item check_invoicing_list ARRAYREF
4579 Checks these arguements as valid input for the invoicing_list method. If there
4580 is an error, returns the error, otherwise returns false.
4584 sub check_invoicing_list {
4585 my( $self, $arrayref ) = @_;
4587 foreach my $address ( @$arrayref ) {
4589 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4590 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4593 my $cust_main_invoice = new FS::cust_main_invoice ( {
4594 'custnum' => $self->custnum,
4597 my $error = $self->custnum
4598 ? $cust_main_invoice->check
4599 : $cust_main_invoice->checkdest
4601 return $error if $error;
4605 return "Email address required"
4606 if $conf->exists('cust_main-require_invoicing_list_email')
4607 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4612 =item set_default_invoicing_list
4614 Sets the invoicing list to all accounts associated with this customer,
4615 overwriting any previous invoicing list.
4619 sub set_default_invoicing_list {
4621 $self->invoicing_list($self->all_emails);
4626 Returns the email addresses of all accounts provisioned for this customer.
4633 foreach my $cust_pkg ( $self->all_pkgs ) {
4634 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4636 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4637 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4639 $list{$_}=1 foreach map { $_->email } @svc_acct;
4644 =item invoicing_list_addpost
4646 Adds postal invoicing to this customer. If this customer is already configured
4647 to receive postal invoices, does nothing.
4651 sub invoicing_list_addpost {
4653 return if grep { $_ eq 'POST' } $self->invoicing_list;
4654 my @invoicing_list = $self->invoicing_list;
4655 push @invoicing_list, 'POST';
4656 $self->invoicing_list(\@invoicing_list);
4659 =item invoicing_list_emailonly
4661 Returns the list of email invoice recipients (invoicing_list without non-email
4662 destinations such as POST and FAX).
4666 sub invoicing_list_emailonly {
4668 warn "$me invoicing_list_emailonly called"
4670 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4673 =item invoicing_list_emailonly_scalar
4675 Returns the list of email invoice recipients (invoicing_list without non-email
4676 destinations such as POST and FAX) as a comma-separated scalar.
4680 sub invoicing_list_emailonly_scalar {
4682 warn "$me invoicing_list_emailonly_scalar called"
4684 join(', ', $self->invoicing_list_emailonly);
4687 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4689 Returns an array of customers referred by this customer (referral_custnum set
4690 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4691 customers referred by customers referred by this customer and so on, inclusive.
4692 The default behavior is DEPTH 1 (no recursion).
4696 sub referral_cust_main {
4698 my $depth = @_ ? shift : 1;
4699 my $exclude = @_ ? shift : {};
4702 map { $exclude->{$_->custnum}++; $_; }
4703 grep { ! $exclude->{ $_->custnum } }
4704 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4708 map { $_->referral_cust_main($depth-1, $exclude) }
4715 =item referral_cust_main_ncancelled
4717 Same as referral_cust_main, except only returns customers with uncancelled
4722 sub referral_cust_main_ncancelled {
4724 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4727 =item referral_cust_pkg [ DEPTH ]
4729 Like referral_cust_main, except returns a flat list of all unsuspended (and
4730 uncancelled) packages for each customer. The number of items in this list may
4731 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4735 sub referral_cust_pkg {
4737 my $depth = @_ ? shift : 1;
4739 map { $_->unsuspended_pkgs }
4740 grep { $_->unsuspended_pkgs }
4741 $self->referral_cust_main($depth);
4744 =item referring_cust_main
4746 Returns the single cust_main record for the customer who referred this customer
4747 (referral_custnum), or false.
4751 sub referring_cust_main {
4753 return '' unless $self->referral_custnum;
4754 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4757 =item credit AMOUNT, REASON
4759 Applies a credit to this customer. If there is an error, returns the error,
4760 otherwise returns false.
4765 my( $self, $amount, $reason, %options ) = @_;
4766 my $cust_credit = new FS::cust_credit {
4767 'custnum' => $self->custnum,
4768 'amount' => $amount,
4769 'reason' => $reason,
4771 $cust_credit->insert(%options);
4774 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4776 Creates a one-time charge for this customer. If there is an error, returns
4777 the error, otherwise returns false.
4783 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4784 if ( ref( $_[0] ) ) {
4785 $amount = $_[0]->{amount};
4786 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4787 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4788 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4789 : '$'. sprintf("%.2f",$amount);
4790 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4791 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4792 $additional = $_[0]->{additional};
4796 $pkg = @_ ? shift : 'One-time charge';
4797 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4798 $taxclass = @_ ? shift : '';
4802 local $SIG{HUP} = 'IGNORE';
4803 local $SIG{INT} = 'IGNORE';
4804 local $SIG{QUIT} = 'IGNORE';
4805 local $SIG{TERM} = 'IGNORE';
4806 local $SIG{TSTP} = 'IGNORE';
4807 local $SIG{PIPE} = 'IGNORE';
4809 my $oldAutoCommit = $FS::UID::AutoCommit;
4810 local $FS::UID::AutoCommit = 0;
4813 my $part_pkg = new FS::part_pkg ( {
4815 'comment' => $comment,
4819 'classnum' => $classnum ? $classnum : '',
4820 'taxclass' => $taxclass,
4823 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4824 ( 0 .. @$additional - 1 )
4826 'additional_count' => scalar(@$additional),
4827 'setup_fee' => $amount,
4830 my $error = $part_pkg->insert( options => \%options );
4832 $dbh->rollback if $oldAutoCommit;
4836 my $pkgpart = $part_pkg->pkgpart;
4837 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4838 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4839 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4840 $error = $type_pkgs->insert;
4842 $dbh->rollback if $oldAutoCommit;
4847 my $cust_pkg = new FS::cust_pkg ( {
4848 'custnum' => $self->custnum,
4849 'pkgpart' => $pkgpart,
4850 'quantity' => $quantity,
4853 $error = $cust_pkg->insert;
4855 $dbh->rollback if $oldAutoCommit;
4859 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4864 #=item charge_postal_fee
4866 #Applies a one time charge this customer. If there is an error,
4867 #returns the error, returns the cust_pkg charge object or false
4868 #if there was no charge.
4872 # This should be a customer event. For that to work requires that bill
4873 # also be a customer event.
4875 sub charge_postal_fee {
4878 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4879 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4881 my $cust_pkg = new FS::cust_pkg ( {
4882 'custnum' => $self->custnum,
4883 'pkgpart' => $pkgpart,
4887 my $error = $cust_pkg->insert;
4888 $error ? $error : $cust_pkg;
4893 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4899 sort { $a->_date <=> $b->_date }
4900 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4903 =item open_cust_bill
4905 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4910 sub open_cust_bill {
4912 grep { $_->owed > 0 } $self->cust_bill;
4917 Returns all the credits (see L<FS::cust_credit>) for this customer.
4923 sort { $a->_date <=> $b->_date }
4924 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4929 Returns all the payments (see L<FS::cust_pay>) for this customer.
4935 sort { $a->_date <=> $b->_date }
4936 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4941 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4947 sort { $a->_date <=> $b->_date }
4948 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4951 =item cust_pay_batch
4953 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
4957 sub cust_pay_batch {
4959 sort { $a->_date <=> $b->_date }
4960 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
4965 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4971 sort { $a->_date <=> $b->_date }
4972 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4977 Returns a name string for this customer, either "Company (Last, First)" or
4984 my $name = $self->contact;
4985 $name = $self->company. " ($name)" if $self->company;
4991 Returns a name string for this (service/shipping) contact, either
4992 "Company (Last, First)" or "Last, First".
4998 if ( $self->get('ship_last') ) {
4999 my $name = $self->ship_contact;
5000 $name = $self->ship_company. " ($name)" if $self->ship_company;
5009 Returns this customer's full (billing) contact name only, "Last, First"
5015 $self->get('last'). ', '. $self->first;
5020 Returns this customer's full (shipping) contact name only, "Last, First"
5026 $self->get('ship_last')
5027 ? $self->get('ship_last'). ', '. $self->ship_first
5033 Returns this customer's full country name
5039 code2country($self->country);
5042 =item geocode DATA_VENDOR
5044 Returns a value for the customer location as encoded by DATA_VENDOR.
5045 Currently this only makes sense for "CCH" as DATA_VENDOR.
5050 my ($self, $data_vendor) = (shift, shift); #always cch for now
5052 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5056 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5057 if $self->country eq 'US';
5059 #CCH specific location stuff
5060 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5063 my $cust_tax_location =
5065 'table' => 'cust_tax_location',
5066 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5067 'extra_sql' => $extra_sql,
5070 $geocode = $cust_tax_location->geocode
5071 if $cust_tax_location;
5080 Returns a status string for this customer, currently:
5084 =item prospect - No packages have ever been ordered
5086 =item active - One or more recurring packages is active
5088 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5090 =item suspended - All non-cancelled recurring packages are suspended
5092 =item cancelled - All recurring packages are cancelled
5098 sub status { shift->cust_status(@_); }
5102 for my $status (qw( prospect active inactive suspended cancelled )) {
5103 my $method = $status.'_sql';
5104 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5105 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5106 $sth->execute( ($self->custnum) x $numnum )
5107 or die "Error executing 'SELECT $sql': ". $sth->errstr;
5108 return $status if $sth->fetchrow_arrayref->[0];
5112 =item ucfirst_cust_status
5114 =item ucfirst_status
5116 Returns the status with the first character capitalized.
5120 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5122 sub ucfirst_cust_status {
5124 ucfirst($self->cust_status);
5129 Returns a hex triplet color string for this customer's status.
5133 use vars qw(%statuscolor);
5134 tie %statuscolor, 'Tie::IxHash',
5135 'prospect' => '7e0079', #'000000', #black? naw, purple
5136 'active' => '00CC00', #green
5137 'inactive' => '0000CC', #blue
5138 'suspended' => 'FF9900', #yellow
5139 'cancelled' => 'FF0000', #red
5142 sub statuscolor { shift->cust_statuscolor(@_); }
5144 sub cust_statuscolor {
5146 $statuscolor{$self->cust_status};
5151 Returns an array of hashes representing the customer's RT tickets.
5158 my $num = $conf->config('cust_main-max_tickets') || 10;
5161 unless ( $conf->config('ticket_system-custom_priority_field') ) {
5163 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5167 foreach my $priority (
5168 $conf->config('ticket_system-custom_priority_field-values'), ''
5170 last if scalar(@tickets) >= $num;
5172 @{ FS::TicketSystem->customer_tickets( $self->custnum,
5173 $num - scalar(@tickets),
5182 # Return services representing svc_accts in customer support packages
5183 sub support_services {
5185 my %packages = map { $_ => 1 } $conf->config('support_packages');
5187 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5188 grep { $_->part_svc->svcdb eq 'svc_acct' }
5189 map { $_->cust_svc }
5190 grep { exists $packages{ $_->pkgpart } }
5191 $self->ncancelled_pkgs;
5197 =head1 CLASS METHODS
5203 Class method that returns the list of possible status strings for customers
5204 (see L<the status method|/status>). For example:
5206 @statuses = FS::cust_main->statuses();
5211 #my $self = shift; #could be class...
5217 Returns an SQL expression identifying prospective cust_main records (customers
5218 with no packages ever ordered)
5222 use vars qw($select_count_pkgs);
5223 $select_count_pkgs =
5224 "SELECT COUNT(*) FROM cust_pkg
5225 WHERE cust_pkg.custnum = cust_main.custnum";
5227 sub select_count_pkgs_sql {
5231 sub prospect_sql { "
5232 0 = ( $select_count_pkgs )
5237 Returns an SQL expression identifying active cust_main records (customers with
5238 active recurring packages).
5243 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5249 Returns an SQL expression identifying inactive cust_main records (customers with
5250 no active recurring packages, but otherwise unsuspended/uncancelled).
5254 sub inactive_sql { "
5255 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5257 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5263 Returns an SQL expression identifying suspended cust_main records.
5268 sub suspended_sql { susp_sql(@_); }
5270 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5272 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5278 Returns an SQL expression identifying cancelled cust_main records.
5282 sub cancelled_sql { cancel_sql(@_); }
5285 my $recurring_sql = FS::cust_pkg->recurring_sql;
5286 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5289 0 < ( $select_count_pkgs )
5290 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
5291 AND 0 = ( $select_count_pkgs AND $recurring_sql
5292 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5294 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5300 =item uncancelled_sql
5302 Returns an SQL expression identifying un-cancelled cust_main records.
5306 sub uncancelled_sql { uncancel_sql(@_); }
5307 sub uncancel_sql { "
5308 ( 0 < ( $select_count_pkgs
5309 AND ( cust_pkg.cancel IS NULL
5310 OR cust_pkg.cancel = 0
5313 OR 0 = ( $select_count_pkgs )
5319 Returns an SQL fragment to retreive the balance.
5324 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5325 WHERE cust_bill.custnum = cust_main.custnum )
5326 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5327 WHERE cust_pay.custnum = cust_main.custnum )
5328 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5329 WHERE cust_credit.custnum = cust_main.custnum )
5330 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5331 WHERE cust_refund.custnum = cust_main.custnum )
5334 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5336 Returns an SQL fragment to retreive the balance for this customer, only
5337 considering invoices with date earlier than START_TIME, and optionally not
5338 later than END_TIME (total_owed_date minus total_credited minus
5339 total_unapplied_payments).
5341 Times are specified as SQL fragments or numeric
5342 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5343 L<Date::Parse> for conversion functions. The empty string can be passed
5344 to disable that time constraint completely.
5346 Available options are:
5350 =item unapplied_date
5352 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)
5357 set to true to remove all customer comparison clauses, for totals
5362 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5367 JOIN clause (typically used with the total option)
5373 sub balance_date_sql {
5374 my( $class, $start, $end, %opt ) = @_;
5376 my $owed = FS::cust_bill->owed_sql;
5377 my $unapp_refund = FS::cust_refund->unapplied_sql;
5378 my $unapp_credit = FS::cust_credit->unapplied_sql;
5379 my $unapp_pay = FS::cust_pay->unapplied_sql;
5381 my $j = $opt{'join'} || '';
5383 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5384 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5385 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5386 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5388 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5389 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5390 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5391 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5396 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5398 Helper method for balance_date_sql; name (and usage) subject to change
5399 (suggestions welcome).
5401 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5402 cust_refund, cust_credit or cust_pay).
5404 If TABLE is "cust_bill" or the unapplied_date option is true, only
5405 considers records with date earlier than START_TIME, and optionally not
5406 later than END_TIME .
5410 sub _money_table_where {
5411 my( $class, $table, $start, $end, %opt ) = @_;
5414 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5415 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5416 push @where, "$table._date <= $start" if defined($start) && length($start);
5417 push @where, "$table._date > $end" if defined($end) && length($end);
5419 push @where, @{$opt{'where'}} if $opt{'where'};
5420 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5426 =item search_sql HASHREF
5430 Returns a qsearch hash expression to search for parameters specified in HREF.
5431 Valid parameters are
5439 =item cancelled_pkgs
5445 listref of start date, end date
5451 =item current_balance
5453 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5457 =item flattened_pkgs
5466 my ($class, $params) = @_;
5477 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5479 "cust_main.agentnum = $1";
5486 #prospect active inactive suspended cancelled
5487 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5488 my $method = $params->{'status'}. '_sql';
5489 #push @where, $class->$method();
5490 push @where, FS::cust_main->$method();
5494 # parse cancelled package checkbox
5499 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5500 unless $params->{'cancelled_pkgs'};
5506 foreach my $field (qw( signupdate )) {
5508 next unless exists($params->{$field});
5510 my($beginning, $ending) = @{$params->{$field}};
5513 "cust_main.$field IS NOT NULL",
5514 "cust_main.$field >= $beginning",
5515 "cust_main.$field <= $ending";
5517 $orderby ||= "ORDER BY cust_main.$field";
5525 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5527 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5534 #my $balance_sql = $class->balance_sql();
5535 my $balance_sql = FS::cust_main->balance_sql();
5537 push @where, map { s/current_balance/$balance_sql/; $_ }
5538 @{ $params->{'current_balance'} };
5541 # setup queries, subs, etc. for the search
5544 $orderby ||= 'ORDER BY custnum';
5546 # here is the agent virtualization
5547 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5549 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5551 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5553 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5555 my $select = join(', ',
5556 'cust_main.custnum',
5557 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5560 my(@extra_headers) = ();
5561 my(@extra_fields) = ();
5563 if ($params->{'flattened_pkgs'}) {
5565 if ($dbh->{Driver}->{Name} eq 'Pg') {
5567 $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";
5569 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5570 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5571 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5573 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5574 "omitting packing information from report.";
5577 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";
5579 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5580 $sth->execute() or die $sth->errstr;
5581 my $headerrow = $sth->fetchrow_arrayref;
5582 my $headercount = $headerrow ? $headerrow->[0] : 0;
5583 while($headercount) {
5584 unshift @extra_headers, "Package ". $headercount;
5585 unshift @extra_fields, eval q!sub {my $c = shift;
5586 my @a = split '\|', $c->magic;
5587 my $p = $a[!.--$headercount. q!];
5595 'table' => 'cust_main',
5596 'select' => $select,
5598 'extra_sql' => $extra_sql,
5599 'order_by' => $orderby,
5600 'count_query' => $count_query,
5601 'extra_headers' => \@extra_headers,
5602 'extra_fields' => \@extra_fields,
5607 =item email_search_sql HASHREF
5611 Emails a notice to the specified customers.
5613 Valid parameters are those of the L<search_sql> method, plus the following:
5635 Optional job queue job for status updates.
5639 Returns an error message, or false for success.
5641 If an error occurs during any email, stops the enture send and returns that
5642 error. Presumably if you're getting SMTP errors aborting is better than
5643 retrying everything.
5647 sub email_search_sql {
5648 my($class, $params) = @_;
5650 my $from = delete $params->{from};
5651 my $subject = delete $params->{subject};
5652 my $html_body = delete $params->{html_body};
5653 my $text_body = delete $params->{text_body};
5655 my $job = delete $params->{'job'};
5657 my $sql_query = $class->search_sql($params);
5659 my $count_query = delete($sql_query->{'count_query'});
5660 my $count_sth = dbh->prepare($count_query)
5661 or die "Error preparing $count_query: ". dbh->errstr;
5663 or die "Error executing $count_query: ". $count_sth->errstr;
5664 my $count_arrayref = $count_sth->fetchrow_arrayref;
5665 my $num_cust = $count_arrayref->[0];
5667 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5668 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5671 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5673 #eventually order+limit magic to reduce memory use?
5674 foreach my $cust_main ( qsearch($sql_query) ) {
5676 my $to = $cust_main->invoicing_list_emailonly_scalar;
5679 my $error = send_email(
5683 'subject' => $subject,
5684 'html_body' => $html_body,
5685 'text_body' => $text_body,
5688 return $error if $error;
5690 if ( $job ) { #progressbar foo
5692 if ( time - $min_sec > $last ) {
5693 my $error = $job->update_statustext(
5694 int( 100 * $num / $num_cust )
5696 die $error if $error;
5706 use Storable qw(thaw);
5709 sub process_email_search_sql {
5711 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5713 my $param = thaw(decode_base64(shift));
5714 warn Dumper($param) if $DEBUG;
5716 $param->{'job'} = $job;
5718 my $error = FS::cust_main->email_search_sql( $param );
5719 die $error if $error;
5723 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5725 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5726 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5727 appropriate ship_ field is also searched).
5729 Additional options are the same as FS::Record::qsearch
5734 my( $self, $fuzzy, $hash, @opt) = @_;
5739 check_and_rebuild_fuzzyfiles();
5740 foreach my $field ( keys %$fuzzy ) {
5742 my $all = $self->all_X($field);
5743 next unless scalar(@$all);
5746 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5749 foreach ( keys %match ) {
5750 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5751 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5754 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5757 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5759 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5767 Returns a masked version of the named field
5772 my ($self,$field) = @_;
5776 'x'x(length($self->getfield($field))-4).
5777 substr($self->getfield($field), (length($self->getfield($field))-4));
5787 =item smart_search OPTION => VALUE ...
5789 Accepts the following options: I<search>, the string to search for. The string
5790 will be searched for as a customer number, phone number, name or company name,
5791 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5792 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5793 skip fuzzy matching when an exact match is found.
5795 Any additional options are treated as an additional qualifier on the search
5798 Returns a (possibly empty) array of FS::cust_main objects.
5805 #here is the agent virtualization
5806 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5810 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5811 my $search = delete $options{'search'};
5812 ( my $alphanum_search = $search ) =~ s/\W//g;
5814 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5816 #false laziness w/Record::ut_phone
5817 my $phonen = "$1-$2-$3";
5818 $phonen .= " x$4" if $4;
5820 push @cust_main, qsearch( {
5821 'table' => 'cust_main',
5822 'hashref' => { %options },
5823 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5825 join(' OR ', map "$_ = '$phonen'",
5826 qw( daytime night fax
5827 ship_daytime ship_night ship_fax )
5830 " AND $agentnums_sql", #agent virtualization
5833 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5834 #try looking for matches with extensions unless one was specified
5836 push @cust_main, qsearch( {
5837 'table' => 'cust_main',
5838 'hashref' => { %options },
5839 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5841 join(' OR ', map "$_ LIKE '$phonen\%'",
5843 ship_daytime ship_night )
5846 " AND $agentnums_sql", #agent virtualization
5851 # custnum search (also try agent_custid), with some tweaking options if your
5852 # legacy cust "numbers" have letters
5853 } elsif ( $search =~ /^\s*(\d+)\s*$/
5854 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5855 && $search =~ /^\s*(\w\w?\d+)\s*$/
5860 push @cust_main, qsearch( {
5861 'table' => 'cust_main',
5862 'hashref' => { 'custnum' => $1, %options },
5863 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5866 push @cust_main, qsearch( {
5867 'table' => 'cust_main',
5868 'hashref' => { 'agent_custid' => $1, %options },
5869 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5872 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5874 my($company, $last, $first) = ( $1, $2, $3 );
5876 # "Company (Last, First)"
5877 #this is probably something a browser remembered,
5878 #so just do an exact search
5880 foreach my $prefix ( '', 'ship_' ) {
5881 push @cust_main, qsearch( {
5882 'table' => 'cust_main',
5883 'hashref' => { $prefix.'first' => $first,
5884 $prefix.'last' => $last,
5885 $prefix.'company' => $company,
5888 'extra_sql' => " AND $agentnums_sql",
5892 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5893 # try (ship_){last,company}
5897 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5898 # # full strings the browser remembers won't work
5899 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5901 use Lingua::EN::NameParse;
5902 my $NameParse = new Lingua::EN::NameParse(
5904 allow_reversed => 1,
5907 my($last, $first) = ( '', '' );
5908 #maybe disable this too and just rely on NameParse?
5909 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5911 ($last, $first) = ( $1, $2 );
5913 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5914 } elsif ( ! $NameParse->parse($value) ) {
5916 my %name = $NameParse->components;
5917 $first = $name{'given_name_1'};
5918 $last = $name{'surname_1'};
5922 if ( $first && $last ) {
5924 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5927 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5929 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5930 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5933 push @cust_main, qsearch( {
5934 'table' => 'cust_main',
5935 'hashref' => \%options,
5936 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5939 # or it just be something that was typed in... (try that in a sec)
5943 my $q_value = dbh->quote($value);
5946 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5947 $sql .= " ( LOWER(last) = $q_value
5948 OR LOWER(company) = $q_value
5949 OR LOWER(ship_last) = $q_value
5950 OR LOWER(ship_company) = $q_value
5953 push @cust_main, qsearch( {
5954 'table' => 'cust_main',
5955 'hashref' => \%options,
5956 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5959 #no exact match, trying substring/fuzzy
5960 #always do substring & fuzzy (unless they're explicity config'ed off)
5961 #getting complaints searches are not returning enough
5962 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
5964 #still some false laziness w/search_sql (was search/cust_main.cgi)
5969 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
5970 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5973 if ( $first && $last ) {
5976 { 'first' => { op=>'ILIKE', value=>"%$first%" },
5977 'last' => { op=>'ILIKE', value=>"%$last%" },
5979 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
5980 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
5987 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
5988 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
5992 foreach my $hashref ( @hashrefs ) {
5994 push @cust_main, qsearch( {
5995 'table' => 'cust_main',
5996 'hashref' => { %$hashref,
5999 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6008 " AND $agentnums_sql", #extra_sql #agent virtualization
6011 if ( $first && $last ) {
6012 push @cust_main, FS::cust_main->fuzzy_search(
6013 { 'last' => $last, #fuzzy hashref
6014 'first' => $first }, #
6018 foreach my $field ( 'last', 'company' ) {
6020 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6025 #eliminate duplicates
6027 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6037 Accepts the following options: I<email>, the email address to search for. The
6038 email address will be searched for as an email invoice destination and as an
6041 #Any additional options are treated as an additional qualifier on the search
6042 #(i.e. I<agentnum>).
6044 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6054 my $email = delete $options{'email'};
6056 #we're only being used by RT at the moment... no agent virtualization yet
6057 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6061 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6063 my ( $user, $domain ) = ( $1, $2 );
6065 warn "$me smart_search: searching for $user in domain $domain"
6071 'table' => 'cust_main_invoice',
6072 'hashref' => { 'dest' => $email },
6079 map $_->cust_svc->cust_pkg,
6081 'table' => 'svc_acct',
6082 'hashref' => { 'username' => $user, },
6084 'AND ( SELECT domain FROM svc_domain
6085 WHERE svc_acct.domsvc = svc_domain.svcnum
6086 ) = '. dbh->quote($domain),
6092 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6094 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6101 =item check_and_rebuild_fuzzyfiles
6105 use vars qw(@fuzzyfields);
6106 @fuzzyfields = ( 'last', 'first', 'company' );
6108 sub check_and_rebuild_fuzzyfiles {
6109 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6110 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6113 =item rebuild_fuzzyfiles
6117 sub rebuild_fuzzyfiles {
6119 use Fcntl qw(:flock);
6121 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6122 mkdir $dir, 0700 unless -d $dir;
6124 foreach my $fuzzy ( @fuzzyfields ) {
6126 open(LOCK,">>$dir/cust_main.$fuzzy")
6127 or die "can't open $dir/cust_main.$fuzzy: $!";
6129 or die "can't lock $dir/cust_main.$fuzzy: $!";
6131 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6132 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6134 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6135 my $sth = dbh->prepare("SELECT $field FROM cust_main".
6136 " WHERE $field != '' AND $field IS NOT NULL");
6137 $sth->execute or die $sth->errstr;
6139 while ( my $row = $sth->fetchrow_arrayref ) {
6140 print CACHE $row->[0]. "\n";
6145 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6147 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6158 my( $self, $field ) = @_;
6159 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6160 open(CACHE,"<$dir/cust_main.$field")
6161 or die "can't open $dir/cust_main.$field: $!";
6162 my @array = map { chomp; $_; } <CACHE>;
6167 =item append_fuzzyfiles LASTNAME COMPANY
6171 sub append_fuzzyfiles {
6172 #my( $first, $last, $company ) = @_;
6174 &check_and_rebuild_fuzzyfiles;
6176 use Fcntl qw(:flock);
6178 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6180 foreach my $field (qw( first last company )) {
6185 open(CACHE,">>$dir/cust_main.$field")
6186 or die "can't open $dir/cust_main.$field: $!";
6187 flock(CACHE,LOCK_EX)
6188 or die "can't lock $dir/cust_main.$field: $!";
6190 print CACHE "$value\n";
6192 flock(CACHE,LOCK_UN)
6193 or die "can't unlock $dir/cust_main.$field: $!";
6208 #warn join('-',keys %$param);
6209 my $fh = $param->{filehandle};
6210 my $agentnum = $param->{agentnum};
6212 my $refnum = $param->{refnum};
6213 my $pkgpart = $param->{pkgpart};
6215 #my @fields = @{$param->{fields}};
6216 my $format = $param->{'format'};
6219 if ( $format eq 'simple' ) {
6220 @fields = qw( cust_pkg.setup dayphone first last
6221 address1 address2 city state zip comments );
6223 } elsif ( $format eq 'extended' ) {
6224 @fields = qw( agent_custid refnum
6225 last first address1 address2 city state zip country
6227 ship_last ship_first ship_address1 ship_address2
6228 ship_city ship_state ship_zip ship_country
6229 payinfo paycvv paydate
6232 svc_acct.username svc_acct._password
6235 } elsif ( $format eq 'extended-plus_company' ) {
6236 @fields = qw( agent_custid refnum
6237 last first company address1 address2 city state zip country
6239 ship_last ship_first ship_company ship_address1 ship_address2
6240 ship_city ship_state ship_zip ship_country
6241 payinfo paycvv paydate
6244 svc_acct.username svc_acct._password
6248 die "unknown format $format";
6251 eval "use Text::CSV_XS;";
6254 my $csv = new Text::CSV_XS;
6261 local $SIG{HUP} = 'IGNORE';
6262 local $SIG{INT} = 'IGNORE';
6263 local $SIG{QUIT} = 'IGNORE';
6264 local $SIG{TERM} = 'IGNORE';
6265 local $SIG{TSTP} = 'IGNORE';
6266 local $SIG{PIPE} = 'IGNORE';
6268 my $oldAutoCommit = $FS::UID::AutoCommit;
6269 local $FS::UID::AutoCommit = 0;
6272 #while ( $columns = $csv->getline($fh) ) {
6274 while ( defined($line=<$fh>) ) {
6276 $csv->parse($line) or do {
6277 $dbh->rollback if $oldAutoCommit;
6278 return "can't parse: ". $csv->error_input();
6281 my @columns = $csv->fields();
6282 #warn join('-',@columns);
6285 agentnum => $agentnum,
6287 country => $conf->config('countrydefault') || 'US',
6288 payby => $payby, #default
6289 paydate => '12/2037', #default
6291 my $billtime = time;
6292 my %cust_pkg = ( pkgpart => $pkgpart );
6294 foreach my $field ( @fields ) {
6296 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
6298 #$cust_pkg{$1} = str2time( shift @$columns );
6299 if ( $1 eq 'pkgpart' ) {
6300 $cust_pkg{$1} = shift @columns;
6301 } elsif ( $1 eq 'setup' ) {
6302 $billtime = str2time(shift @columns);
6304 $cust_pkg{$1} = str2time( shift @columns );
6307 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
6309 $svc_acct{$1} = shift @columns;
6313 #refnum interception
6314 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
6316 my $referral = $columns[0];
6317 my %hash = ( 'referral' => $referral,
6318 'agentnum' => $agentnum,
6322 my $part_referral = qsearchs('part_referral', \%hash )
6323 || new FS::part_referral \%hash;
6325 unless ( $part_referral->refnum ) {
6326 my $error = $part_referral->insert;
6328 $dbh->rollback if $oldAutoCommit;
6329 return "can't auto-insert advertising source: $referral: $error";
6333 $columns[0] = $part_referral->refnum;
6336 #$cust_main{$field} = shift @$columns;
6337 $cust_main{$field} = shift @columns;
6341 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
6343 my $invoicing_list = $cust_main{'invoicing_list'}
6344 ? [ delete $cust_main{'invoicing_list'} ]
6347 my $cust_main = new FS::cust_main ( \%cust_main );
6350 tie my %hash, 'Tie::RefHash'; #this part is important
6352 if ( $cust_pkg{'pkgpart'} ) {
6353 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
6356 if ( $svc_acct{'username'} ) {
6357 my $part_pkg = $cust_pkg->part_pkg;
6358 unless ( $part_pkg ) {
6359 $dbh->rollback if $oldAutoCommit;
6360 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
6362 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
6363 push @svc_acct, new FS::svc_acct ( \%svc_acct )
6366 $hash{$cust_pkg} = \@svc_acct;
6369 my $error = $cust_main->insert( \%hash, $invoicing_list );
6372 $dbh->rollback if $oldAutoCommit;
6373 return "can't insert customer for $line: $error";
6376 if ( $format eq 'simple' ) {
6378 #false laziness w/bill.cgi
6379 $error = $cust_main->bill( 'time' => $billtime );
6381 $dbh->rollback if $oldAutoCommit;
6382 return "can't bill customer for $line: $error";
6385 $error = $cust_main->apply_payments_and_credits;
6387 $dbh->rollback if $oldAutoCommit;
6388 return "can't bill customer for $line: $error";
6391 $error = $cust_main->collect();
6393 $dbh->rollback if $oldAutoCommit;
6394 return "can't collect customer for $line: $error";
6402 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6404 return "Empty file!" unless $imported;
6416 #warn join('-',keys %$param);
6417 my $fh = $param->{filehandle};
6418 my @fields = @{$param->{fields}};
6420 eval "use Text::CSV_XS;";
6423 my $csv = new Text::CSV_XS;
6430 local $SIG{HUP} = 'IGNORE';
6431 local $SIG{INT} = 'IGNORE';
6432 local $SIG{QUIT} = 'IGNORE';
6433 local $SIG{TERM} = 'IGNORE';
6434 local $SIG{TSTP} = 'IGNORE';
6435 local $SIG{PIPE} = 'IGNORE';
6437 my $oldAutoCommit = $FS::UID::AutoCommit;
6438 local $FS::UID::AutoCommit = 0;
6441 #while ( $columns = $csv->getline($fh) ) {
6443 while ( defined($line=<$fh>) ) {
6445 $csv->parse($line) or do {
6446 $dbh->rollback if $oldAutoCommit;
6447 return "can't parse: ". $csv->error_input();
6450 my @columns = $csv->fields();
6451 #warn join('-',@columns);
6454 foreach my $field ( @fields ) {
6455 $row{$field} = shift @columns;
6458 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6459 unless ( $cust_main ) {
6460 $dbh->rollback if $oldAutoCommit;
6461 return "unknown custnum $row{'custnum'}";
6464 if ( $row{'amount'} > 0 ) {
6465 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6467 $dbh->rollback if $oldAutoCommit;
6471 } elsif ( $row{'amount'} < 0 ) {
6472 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6475 $dbh->rollback if $oldAutoCommit;
6485 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6487 return "Empty file!" unless $imported;
6493 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6495 Sends a templated email notification to the customer (see L<Text::Template>).
6497 OPTIONS is a hash and may include
6499 I<from> - the email sender (default is invoice_from)
6501 I<to> - comma-separated scalar or arrayref of recipients
6502 (default is invoicing_list)
6504 I<subject> - The subject line of the sent email notification
6505 (default is "Notice from company_name")
6507 I<extra_fields> - a hashref of name/value pairs which will be substituted
6510 The following variables are vavailable in the template.
6512 I<$first> - the customer first name
6513 I<$last> - the customer last name
6514 I<$company> - the customer company
6515 I<$payby> - a description of the method of payment for the customer
6516 # would be nice to use FS::payby::shortname
6517 I<$payinfo> - the account information used to collect for this customer
6518 I<$expdate> - the expiration of the customer payment in seconds from epoch
6523 my ($customer, $template, %options) = @_;
6525 return unless $conf->exists($template);
6527 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6528 $from = $options{from} if exists($options{from});
6530 my $to = join(',', $customer->invoicing_list_emailonly);
6531 $to = $options{to} if exists($options{to});
6533 my $subject = "Notice from " . $conf->config('company_name')
6534 if $conf->exists('company_name');
6535 $subject = $options{subject} if exists($options{subject});
6537 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6538 SOURCE => [ map "$_\n",
6539 $conf->config($template)]
6541 or die "can't create new Text::Template object: Text::Template::ERROR";
6542 $notify_template->compile()
6543 or die "can't compile template: Text::Template::ERROR";
6545 $FS::notify_template::_template::company_name = $conf->config('company_name');
6546 $FS::notify_template::_template::company_address =
6547 join("\n", $conf->config('company_address') ). "\n";
6549 my $paydate = $customer->paydate || '2037-12-31';
6550 $FS::notify_template::_template::first = $customer->first;
6551 $FS::notify_template::_template::last = $customer->last;
6552 $FS::notify_template::_template::company = $customer->company;
6553 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6554 my $payby = $customer->payby;
6555 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6556 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6558 #credit cards expire at the end of the month/year of their exp date
6559 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6560 $FS::notify_template::_template::payby = 'credit card';
6561 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6562 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6564 }elsif ($payby eq 'COMP') {
6565 $FS::notify_template::_template::payby = 'complimentary account';
6567 $FS::notify_template::_template::payby = 'current method';
6569 $FS::notify_template::_template::expdate = $expire_time;
6571 for (keys %{$options{extra_fields}}){
6573 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6576 send_email(from => $from,
6578 subject => $subject,
6579 body => $notify_template->fill_in( PACKAGE =>
6580 'FS::notify_template::_template' ),
6585 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6587 Generates a templated notification to the customer (see L<Text::Template>).
6589 OPTIONS is a hash and may include
6591 I<extra_fields> - a hashref of name/value pairs which will be substituted
6592 into the template. These values may override values mentioned below
6593 and those from the customer record.
6595 The following variables are available in the template instead of or in addition
6596 to the fields of the customer record.
6598 I<$payby> - a description of the method of payment for the customer
6599 # would be nice to use FS::payby::shortname
6600 I<$payinfo> - the masked account information used to collect for this customer
6601 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6602 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6606 sub generate_letter {
6607 my ($self, $template, %options) = @_;
6609 return unless $conf->exists($template);
6611 my $letter_template = new Text::Template
6613 SOURCE => [ map "$_\n", $conf->config($template)],
6614 DELIMITERS => [ '[@--', '--@]' ],
6616 or die "can't create new Text::Template object: Text::Template::ERROR";
6618 $letter_template->compile()
6619 or die "can't compile template: Text::Template::ERROR";
6621 my %letter_data = map { $_ => $self->$_ } $self->fields;
6622 $letter_data{payinfo} = $self->mask_payinfo;
6624 #my $paydate = $self->paydate || '2037-12-31';
6625 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6627 my $payby = $self->payby;
6628 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6629 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6631 #credit cards expire at the end of the month/year of their exp date
6632 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6633 $letter_data{payby} = 'credit card';
6634 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6635 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6637 }elsif ($payby eq 'COMP') {
6638 $letter_data{payby} = 'complimentary account';
6640 $letter_data{payby} = 'current method';
6642 $letter_data{expdate} = $expire_time;
6644 for (keys %{$options{extra_fields}}){
6645 $letter_data{$_} = $options{extra_fields}->{$_};
6648 unless(exists($letter_data{returnaddress})){
6649 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6650 $self->agent_template)
6652 if ( length($retadd) ) {
6653 $letter_data{returnaddress} = $retadd;
6654 } elsif ( grep /\S/, $conf->config('company_address') ) {
6655 $letter_data{returnaddress} =
6656 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6657 $conf->config('company_address')
6660 $letter_data{returnaddress} = '~';
6664 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6666 $letter_data{company_name} = $conf->config('company_name');
6668 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6669 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6673 ) or die "can't open temp file: $!\n";
6675 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6677 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6681 =item print_ps TEMPLATE
6683 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6689 my $file = $self->generate_letter(@_);
6690 FS::Misc::generate_ps($file);
6693 =item print TEMPLATE
6695 Prints the filled in template.
6697 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6701 sub queueable_print {
6704 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6705 or die "invalid customer number: " . $opt{custvnum};
6707 my $error = $self->print( $opt{template} );
6708 die $error if $error;
6712 my ($self, $template) = (shift, shift);
6713 do_print [ $self->print_ps($template) ];
6716 sub agent_template {
6718 $self->_agent_plandata('agent_templatename');
6721 sub agent_invoice_from {
6723 $self->_agent_plandata('agent_invoice_from');
6726 sub _agent_plandata {
6727 my( $self, $option ) = @_;
6729 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6730 #agent-specific Conf
6732 use FS::part_event::Condition;
6734 my $agentnum = $self->agentnum;
6737 if ( driver_name =~ /^Pg/i ) {
6739 } elsif ( driver_name =~ /^mysql/i ) {
6742 die "don't know how to use regular expressions in ". driver_name. " databases";
6745 my $part_event_option =
6747 'select' => 'part_event_option.*',
6748 'table' => 'part_event_option',
6750 LEFT JOIN part_event USING ( eventpart )
6751 LEFT JOIN part_event_option AS peo_agentnum
6752 ON ( part_event.eventpart = peo_agentnum.eventpart
6753 AND peo_agentnum.optionname = 'agentnum'
6754 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6756 LEFT JOIN part_event_option AS peo_cust_bill_age
6757 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6758 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6761 #'hashref' => { 'optionname' => $option },
6762 #'hashref' => { 'part_event_option.optionname' => $option },
6764 " WHERE part_event_option.optionname = ". dbh->quote($option).
6765 " AND action = 'cust_bill_send_agent' ".
6766 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6767 " AND peo_agentnum.optionname = 'agentnum' ".
6768 " AND agentnum IS NULL OR agentnum = $agentnum ".
6770 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6772 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6774 , part_event.weight".
6778 unless ( $part_event_option ) {
6779 return $self->agent->invoice_template || ''
6780 if $option eq 'agent_templatename';
6784 $part_event_option->optionvalue;
6789 ## actual sub, not a method, designed to be called from the queue.
6790 ## sets up the customer, and calls the bill_and_collect
6791 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6792 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6793 $cust_main->bill_and_collect(
6804 The delete method should possibly take an FS::cust_main object reference
6805 instead of a scalar customer number.
6807 Bill and collect options should probably be passed as references instead of a
6810 There should probably be a configuration file with a list of allowed credit
6813 No multiple currency support (probably a larger project than just this module).
6815 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6817 Birthdates rely on negative epoch values.
6819 The payby for card/check batches is broken. With mixed batching, bad
6822 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
6826 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6827 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6828 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.