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 Time::Local qw(timelocal_nocheck);
14 use Digest::MD5 qw(md5_base64);
18 use String::Approx qw(amatch);
19 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( 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;
48 use FS::cust_tax_exempt;
49 use FS::cust_tax_exempt_pkg;
51 use FS::payment_gateway;
52 use FS::agent_payment_gateway;
54 use FS::payinfo_Mixin;
57 @ISA = qw( FS::Record FS::payinfo_Mixin );
59 @EXPORT_OK = qw( smart_search );
61 $realtime_bop_decline_quiet = 0;
63 # 1 is mostly method/subroutine entry and options
64 # 2 traces progress of some operations
65 # 3 is even more information including possibly sensitive data
67 $me = '[FS::cust_main]';
71 $ignore_expired_card = 0;
73 @encrypted_fields = ('payinfo', 'paycvv');
74 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
76 #ask FS::UID to run this stuff for us later
77 #$FS::UID::callback{'FS::cust_main'} = sub {
78 install_callback FS::UID sub {
80 #yes, need it for stuff below (prolly should be cached)
85 my ( $hashref, $cache ) = @_;
86 if ( exists $hashref->{'pkgnum'} ) {
87 #@{ $self->{'_pkgnum'} } = ();
88 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
89 $self->{'_pkgnum'} = $subcache;
90 #push @{ $self->{'_pkgnum'} },
91 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
97 FS::cust_main - Object methods for cust_main records
103 $record = new FS::cust_main \%hash;
104 $record = new FS::cust_main { 'column' => 'value' };
106 $error = $record->insert;
108 $error = $new_record->replace($old_record);
110 $error = $record->delete;
112 $error = $record->check;
114 @cust_pkg = $record->all_pkgs;
116 @cust_pkg = $record->ncancelled_pkgs;
118 @cust_pkg = $record->suspended_pkgs;
120 $error = $record->bill;
121 $error = $record->bill %options;
122 $error = $record->bill 'time' => $time;
124 $error = $record->collect;
125 $error = $record->collect %options;
126 $error = $record->collect 'invoice_time' => $time,
131 An FS::cust_main object represents a customer. FS::cust_main inherits from
132 FS::Record. The following fields are currently supported:
136 =item custnum - primary key (assigned automatically for new customers)
138 =item agentnum - agent (see L<FS::agent>)
140 =item refnum - Advertising source (see L<FS::part_referral>)
146 =item ss - social security number (optional)
148 =item company - (optional)
152 =item address2 - (optional)
156 =item county - (optional, see L<FS::cust_main_county>)
158 =item state - (see L<FS::cust_main_county>)
162 =item country - (see L<FS::cust_main_county>)
164 =item daytime - phone (optional)
166 =item night - phone (optional)
168 =item fax - phone (optional)
170 =item ship_first - name
172 =item ship_last - name
174 =item ship_company - (optional)
178 =item ship_address2 - (optional)
182 =item ship_county - (optional, see L<FS::cust_main_county>)
184 =item ship_state - (see L<FS::cust_main_county>)
188 =item ship_country - (see L<FS::cust_main_county>)
190 =item ship_daytime - phone (optional)
192 =item ship_night - phone (optional)
194 =item ship_fax - phone (optional)
196 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
198 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
200 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
204 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
206 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
208 =item paystart_month - start date month (maestro/solo cards only)
210 =item paystart_year - start date year (maestro/solo cards only)
212 =item payissue - issue number (maestro/solo cards only)
214 =item payname - name on card or billing name
216 =item payip - IP address from which payment information was received
218 =item tax - tax exempt, empty or `Y'
220 =item otaker - order taker (assigned automatically, see L<FS::UID>)
222 =item comments - comments (optional)
224 =item referral_custnum - referring customer number
226 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
236 Creates a new customer. To add the customer to the database, see L<"insert">.
238 Note that this stores the hash reference, not a distinct copy of the hash it
239 points to. You can ask the object for a copy with the I<hash> method.
243 sub table { 'cust_main'; }
245 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
247 Adds this customer to the database. If there is an error, returns the error,
248 otherwise returns false.
250 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
251 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
252 are inserted atomicly, or the transaction is rolled back. Passing an empty
253 hash reference is equivalent to not supplying this parameter. There should be
254 a better explanation of this, but until then, here's an example:
257 tie %hash, 'Tie::RefHash'; #this part is important
259 $cust_pkg => [ $svc_acct ],
262 $cust_main->insert( \%hash );
264 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
265 be set as the invoicing list (see L<"invoicing_list">). Errors return as
266 expected and rollback the entire transaction; it is not necessary to call
267 check_invoicing_list first. The invoicing_list is set after the records in the
268 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
269 invoicing_list destination to the newly-created svc_acct. Here's an example:
271 $cust_main->insert( {}, [ $email, 'POST' ] );
273 Currently available options are: I<depend_jobnum> and I<noexport>.
275 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
276 on the supplied jobnum (they will not run until the specific job completes).
277 This can be used to defer provisioning until some action completes (such
278 as running the customer's credit card successfully).
280 The I<noexport> option is deprecated. If I<noexport> is set true, no
281 provisioning jobs (exports) are scheduled. (You can schedule them later with
282 the B<reexport> method.)
288 my $cust_pkgs = @_ ? shift : {};
289 my $invoicing_list = @_ ? shift : '';
291 warn "$me insert called with options ".
292 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
295 local $SIG{HUP} = 'IGNORE';
296 local $SIG{INT} = 'IGNORE';
297 local $SIG{QUIT} = 'IGNORE';
298 local $SIG{TERM} = 'IGNORE';
299 local $SIG{TSTP} = 'IGNORE';
300 local $SIG{PIPE} = 'IGNORE';
302 my $oldAutoCommit = $FS::UID::AutoCommit;
303 local $FS::UID::AutoCommit = 0;
306 my $prepay_identifier = '';
307 my( $amount, $seconds ) = ( 0, 0 );
309 if ( $self->payby eq 'PREPAY' ) {
311 $self->payby('BILL');
312 $prepay_identifier = $self->payinfo;
315 warn " looking up prepaid card $prepay_identifier\n"
318 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
320 $dbh->rollback if $oldAutoCommit;
321 #return "error applying prepaid card (transaction rolled back): $error";
325 $payby = 'PREP' if $amount;
327 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
330 $self->payby('BILL');
331 $amount = $self->paid;
335 warn " inserting $self\n"
338 $self->signupdate(time) unless $self->signupdate;
340 my $error = $self->SUPER::insert;
342 $dbh->rollback if $oldAutoCommit;
343 #return "inserting cust_main record (transaction rolled back): $error";
347 warn " setting invoicing list\n"
350 if ( $invoicing_list ) {
351 $error = $self->check_invoicing_list( $invoicing_list );
353 $dbh->rollback if $oldAutoCommit;
354 #return "checking invoicing_list (transaction rolled back): $error";
357 $self->invoicing_list( $invoicing_list );
360 if ( $conf->config('cust_main-skeleton_tables')
361 && $conf->config('cust_main-skeleton_custnum') ) {
363 warn " inserting skeleton records\n"
366 my $error = $self->start_copy_skel;
368 $dbh->rollback if $oldAutoCommit;
374 warn " ordering packages\n"
377 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
379 $dbh->rollback if $oldAutoCommit;
384 $dbh->rollback if $oldAutoCommit;
385 return "No svc_acct record to apply pre-paid time";
389 warn " inserting initial $payby payment of $amount\n"
391 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
393 $dbh->rollback if $oldAutoCommit;
394 return "inserting payment (transaction rolled back): $error";
398 unless ( $import || $skip_fuzzyfiles ) {
399 warn " queueing fuzzyfiles update\n"
401 $error = $self->queue_fuzzyfiles_update;
403 $dbh->rollback if $oldAutoCommit;
404 return "updating fuzzy search cache: $error";
408 warn " insert complete; committing transaction\n"
411 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
416 sub start_copy_skel {
419 #'mg_user_preference' => {},
420 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
421 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
422 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
423 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
424 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
427 _copy_skel( 'cust_main', #tablename
428 $conf->config('cust_main-skeleton_custnum'), #sourceid
429 $self->custnum, #destid
430 @tables, #child tables
434 #recursive subroutine, not a method
436 my( $table, $sourceid, $destid, %child_tables ) = @_;
439 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
440 ( $table, $primary_key ) = ( $1, $2 );
442 my $dbdef_table = dbdef->table($table);
443 $primary_key = $dbdef_table->primary_key
444 or return "$table has no primary key".
445 " (or do you need to run dbdef-create?)";
448 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
449 join (', ', keys %child_tables). "\n"
452 foreach my $child_table_def ( keys %child_tables ) {
456 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
457 ( $child_table, $child_pkey ) = ( $1, $2 );
459 $child_table = $child_table_def;
461 $child_pkey = dbdef->table($child_table)->primary_key;
462 # or return "$table has no primary key".
463 # " (or do you need to run dbdef-create?)\n";
467 if ( keys %{ $child_tables{$child_table_def} } ) {
469 return "$child_table has no primary key".
470 " (run dbdef-create or try specifying it?)\n"
473 #false laziness w/Record::insert and only works on Pg
474 #refactor the proper last-inserted-id stuff out of Record::insert if this
475 # ever gets use for anything besides a quick kludge for one customer
476 my $default = dbdef->table($child_table)->column($child_pkey)->default;
477 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
478 or return "can't parse $child_table.$child_pkey default value ".
479 " for sequence name: $default";
484 my @sel_columns = grep { $_ ne $primary_key }
485 dbdef->table($child_table)->columns;
486 my $sel_columns = join(', ', @sel_columns );
488 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
489 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
490 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
492 my $sel_st = "SELECT $sel_columns FROM $child_table".
493 " WHERE $primary_key = $sourceid";
496 my $sel_sth = dbh->prepare( $sel_st )
497 or return dbh->errstr;
499 $sel_sth->execute or return $sel_sth->errstr;
501 while ( my $row = $sel_sth->fetchrow_hashref ) {
503 warn " selected row: ".
504 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
508 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
509 my $ins_sth =dbh->prepare($statement)
510 or return dbh->errstr;
511 my @param = ( $destid, map $row->{$_}, @ins_columns );
512 warn " $statement: [ ". join(', ', @param). " ]\n"
514 $ins_sth->execute( @param )
515 or return $ins_sth->errstr;
517 #next unless keys %{ $child_tables{$child_table} };
518 next unless $sequence;
520 #another section of that laziness
521 my $seq_sql = "SELECT currval('$sequence')";
522 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
523 $seq_sth->execute or return $seq_sth->errstr;
524 my $insertid = $seq_sth->fetchrow_arrayref->[0];
526 # don't drink soap! recurse! recurse! okay!
528 _copy_skel( $child_table_def,
529 $row->{$child_pkey}, #sourceid
531 %{ $child_tables{$child_table_def} },
533 return $error if $error;
543 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
545 Like the insert method on an existing record, this method orders a package
546 and included services atomicaly. Pass a Tie::RefHash data structure to this
547 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
548 be a better explanation of this, but until then, here's an example:
551 tie %hash, 'Tie::RefHash'; #this part is important
553 $cust_pkg => [ $svc_acct ],
556 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
558 Services can be new, in which case they are inserted, or existing unaudited
559 services, in which case they are linked to the newly-created package.
561 Currently available options are: I<depend_jobnum> and I<noexport>.
563 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
564 on the supplied jobnum (they will not run until the specific job completes).
565 This can be used to defer provisioning until some action completes (such
566 as running the customer's credit card successfully).
568 The I<noexport> option is deprecated. If I<noexport> is set true, no
569 provisioning jobs (exports) are scheduled. (You can schedule them later with
570 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
571 on the cust_main object is not recommended, as existing services will also be
578 my $cust_pkgs = shift;
581 my %svc_options = ();
582 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
583 if exists $options{'depend_jobnum'};
584 warn "$me order_pkgs called with options ".
585 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
588 local $SIG{HUP} = 'IGNORE';
589 local $SIG{INT} = 'IGNORE';
590 local $SIG{QUIT} = 'IGNORE';
591 local $SIG{TERM} = 'IGNORE';
592 local $SIG{TSTP} = 'IGNORE';
593 local $SIG{PIPE} = 'IGNORE';
595 my $oldAutoCommit = $FS::UID::AutoCommit;
596 local $FS::UID::AutoCommit = 0;
599 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
601 foreach my $cust_pkg ( keys %$cust_pkgs ) {
602 $cust_pkg->custnum( $self->custnum );
603 my $error = $cust_pkg->insert;
605 $dbh->rollback if $oldAutoCommit;
606 return "inserting cust_pkg (transaction rolled back): $error";
608 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
609 if ( $svc_something->svcnum ) {
610 my $old_cust_svc = $svc_something->cust_svc;
611 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
612 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
613 $error = $new_cust_svc->replace($old_cust_svc);
615 $svc_something->pkgnum( $cust_pkg->pkgnum );
616 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
617 $svc_something->seconds( $svc_something->seconds + $$seconds );
620 $error = $svc_something->insert(%svc_options);
623 $dbh->rollback if $oldAutoCommit;
624 #return "inserting svc_ (transaction rolled back): $error";
630 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
634 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
636 Recharges this (existing) customer with the specified prepaid card (see
637 L<FS::prepay_credit>), specified either by I<identifier> or as an
638 FS::prepay_credit object. If there is an error, returns the error, otherwise
641 Optionally, four scalar references can be passed as well. They will have their
642 values filled in with the amount, number of seconds, and number of upload and
643 download bytes applied by this prepaid
648 sub recharge_prepay {
649 my( $self, $prepay_credit, $amountref, $secondsref,
650 $upbytesref, $downbytesref, $totalbytesref ) = @_;
652 local $SIG{HUP} = 'IGNORE';
653 local $SIG{INT} = 'IGNORE';
654 local $SIG{QUIT} = 'IGNORE';
655 local $SIG{TERM} = 'IGNORE';
656 local $SIG{TSTP} = 'IGNORE';
657 local $SIG{PIPE} = 'IGNORE';
659 my $oldAutoCommit = $FS::UID::AutoCommit;
660 local $FS::UID::AutoCommit = 0;
663 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
665 my $error = $self->get_prepay($prepay_credit, \$amount,
666 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
667 || $self->increment_seconds($seconds)
668 || $self->increment_upbytes($upbytes)
669 || $self->increment_downbytes($downbytes)
670 || $self->increment_totalbytes($totalbytes)
671 || $self->insert_cust_pay_prepay( $amount,
673 ? $prepay_credit->identifier
678 $dbh->rollback if $oldAutoCommit;
682 if ( defined($amountref) ) { $$amountref = $amount; }
683 if ( defined($secondsref) ) { $$secondsref = $seconds; }
684 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
685 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
686 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
688 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
693 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
695 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
696 specified either by I<identifier> or as an FS::prepay_credit object.
698 References to I<amount> and I<seconds> scalars should be passed as arguments
699 and will be incremented by the values of the prepaid card.
701 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
702 check or set this customer's I<agentnum>.
704 If there is an error, returns the error, otherwise returns false.
710 my( $self, $prepay_credit, $amountref, $secondsref,
711 $upref, $downref, $totalref) = @_;
713 local $SIG{HUP} = 'IGNORE';
714 local $SIG{INT} = 'IGNORE';
715 local $SIG{QUIT} = 'IGNORE';
716 local $SIG{TERM} = 'IGNORE';
717 local $SIG{TSTP} = 'IGNORE';
718 local $SIG{PIPE} = 'IGNORE';
720 my $oldAutoCommit = $FS::UID::AutoCommit;
721 local $FS::UID::AutoCommit = 0;
724 unless ( ref($prepay_credit) ) {
726 my $identifier = $prepay_credit;
728 $prepay_credit = qsearchs(
730 { 'identifier' => $prepay_credit },
735 unless ( $prepay_credit ) {
736 $dbh->rollback if $oldAutoCommit;
737 return "Invalid prepaid card: ". $identifier;
742 if ( $prepay_credit->agentnum ) {
743 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
744 $dbh->rollback if $oldAutoCommit;
745 return "prepaid card not valid for agent ". $self->agentnum;
747 $self->agentnum($prepay_credit->agentnum);
750 my $error = $prepay_credit->delete;
752 $dbh->rollback if $oldAutoCommit;
753 return "removing prepay_credit (transaction rolled back): $error";
756 $$amountref += $prepay_credit->amount;
757 $$secondsref += $prepay_credit->seconds;
758 $$upref += $prepay_credit->upbytes;
759 $$downref += $prepay_credit->downbytes;
760 $$totalref += $prepay_credit->totalbytes;
762 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
767 =item increment_upbytes SECONDS
769 Updates this customer's single or primary account (see L<FS::svc_acct>) by
770 the specified number of upbytes. If there is an error, returns the error,
771 otherwise returns false.
775 sub increment_upbytes {
776 _increment_column( shift, 'upbytes', @_);
779 =item increment_downbytes SECONDS
781 Updates this customer's single or primary account (see L<FS::svc_acct>) by
782 the specified number of downbytes. If there is an error, returns the error,
783 otherwise returns false.
787 sub increment_downbytes {
788 _increment_column( shift, 'downbytes', @_);
791 =item increment_totalbytes SECONDS
793 Updates this customer's single or primary account (see L<FS::svc_acct>) by
794 the specified number of totalbytes. If there is an error, returns the error,
795 otherwise returns false.
799 sub increment_totalbytes {
800 _increment_column( shift, 'totalbytes', @_);
803 =item increment_seconds SECONDS
805 Updates this customer's single or primary account (see L<FS::svc_acct>) by
806 the specified number of seconds. If there is an error, returns the error,
807 otherwise returns false.
811 sub increment_seconds {
812 _increment_column( shift, 'seconds', @_);
815 =item _increment_column AMOUNT
817 Updates this customer's single or primary account (see L<FS::svc_acct>) by
818 the specified number of seconds or bytes. If there is an error, returns
819 the error, otherwise returns false.
823 sub _increment_column {
824 my( $self, $column, $amount ) = @_;
825 warn "$me increment_column called: $column, $amount\n"
828 return '' unless $amount;
830 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
831 $self->ncancelled_pkgs;
834 return 'No packages with primary or single services found'.
835 ' to apply pre-paid time';
836 } elsif ( scalar(@cust_pkg) > 1 ) {
837 #maybe have a way to specify the package/account?
838 return 'Multiple packages found to apply pre-paid time';
841 my $cust_pkg = $cust_pkg[0];
842 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
846 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
849 return 'No account found to apply pre-paid time';
850 } elsif ( scalar(@cust_svc) > 1 ) {
851 return 'Multiple accounts found to apply pre-paid time';
854 my $svc_acct = $cust_svc[0]->svc_x;
855 warn " found service svcnum ". $svc_acct->pkgnum.
856 ' ('. $svc_acct->email. ")\n"
859 $column = "increment_$column";
860 $svc_acct->$column($amount);
864 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
866 Inserts a prepayment in the specified amount for this customer. An optional
867 second argument can specify the prepayment identifier for tracking purposes.
868 If there is an error, returns the error, otherwise returns false.
872 sub insert_cust_pay_prepay {
873 shift->insert_cust_pay('PREP', @_);
876 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
878 Inserts a cash payment in the specified amount for this customer. An optional
879 second argument can specify the payment identifier for tracking purposes.
880 If there is an error, returns the error, otherwise returns false.
884 sub insert_cust_pay_cash {
885 shift->insert_cust_pay('CASH', @_);
888 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
890 Inserts a Western Union payment in the specified amount for this customer. An
891 optional second argument can specify the prepayment identifier for tracking
892 purposes. If there is an error, returns the error, otherwise returns false.
896 sub insert_cust_pay_west {
897 shift->insert_cust_pay('WEST', @_);
900 sub insert_cust_pay {
901 my( $self, $payby, $amount ) = splice(@_, 0, 3);
902 my $payinfo = scalar(@_) ? shift : '';
904 my $cust_pay = new FS::cust_pay {
905 'custnum' => $self->custnum,
906 'paid' => sprintf('%.2f', $amount),
907 #'_date' => #date the prepaid card was purchased???
909 'payinfo' => $payinfo,
917 This method is deprecated. See the I<depend_jobnum> option to the insert and
918 order_pkgs methods for a better way to defer provisioning.
920 Re-schedules all exports by calling the B<reexport> method of all associated
921 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
922 otherwise returns false.
929 carp "WARNING: FS::cust_main::reexport is deprectated; ".
930 "use the depend_jobnum option to insert or order_pkgs to delay export";
932 local $SIG{HUP} = 'IGNORE';
933 local $SIG{INT} = 'IGNORE';
934 local $SIG{QUIT} = 'IGNORE';
935 local $SIG{TERM} = 'IGNORE';
936 local $SIG{TSTP} = 'IGNORE';
937 local $SIG{PIPE} = 'IGNORE';
939 my $oldAutoCommit = $FS::UID::AutoCommit;
940 local $FS::UID::AutoCommit = 0;
943 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
944 my $error = $cust_pkg->reexport;
946 $dbh->rollback if $oldAutoCommit;
951 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
956 =item delete NEW_CUSTNUM
958 This deletes the customer. If there is an error, returns the error, otherwise
961 This will completely remove all traces of the customer record. This is not
962 what you want when a customer cancels service; for that, cancel all of the
963 customer's packages (see L</cancel>).
965 If the customer has any uncancelled packages, you need to pass a new (valid)
966 customer number for those packages to be transferred to. Cancelled packages
967 will be deleted. Did I mention that this is NOT what you want when a customer
968 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
970 You can't delete a customer with invoices (see L<FS::cust_bill>),
971 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
972 refunds (see L<FS::cust_refund>).
979 local $SIG{HUP} = 'IGNORE';
980 local $SIG{INT} = 'IGNORE';
981 local $SIG{QUIT} = 'IGNORE';
982 local $SIG{TERM} = 'IGNORE';
983 local $SIG{TSTP} = 'IGNORE';
984 local $SIG{PIPE} = 'IGNORE';
986 my $oldAutoCommit = $FS::UID::AutoCommit;
987 local $FS::UID::AutoCommit = 0;
990 if ( $self->cust_bill ) {
991 $dbh->rollback if $oldAutoCommit;
992 return "Can't delete a customer with invoices";
994 if ( $self->cust_credit ) {
995 $dbh->rollback if $oldAutoCommit;
996 return "Can't delete a customer with credits";
998 if ( $self->cust_pay ) {
999 $dbh->rollback if $oldAutoCommit;
1000 return "Can't delete a customer with payments";
1002 if ( $self->cust_refund ) {
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Can't delete a customer with refunds";
1007 my @cust_pkg = $self->ncancelled_pkgs;
1009 my $new_custnum = shift;
1010 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1011 $dbh->rollback if $oldAutoCommit;
1012 return "Invalid new customer number: $new_custnum";
1014 foreach my $cust_pkg ( @cust_pkg ) {
1015 my %hash = $cust_pkg->hash;
1016 $hash{'custnum'} = $new_custnum;
1017 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1018 my $error = $new_cust_pkg->replace($cust_pkg,
1019 options => { $cust_pkg->options },
1022 $dbh->rollback if $oldAutoCommit;
1027 my @cancelled_cust_pkg = $self->all_pkgs;
1028 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1029 my $error = $cust_pkg->delete;
1031 $dbh->rollback if $oldAutoCommit;
1036 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1037 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1039 my $error = $cust_main_invoice->delete;
1041 $dbh->rollback if $oldAutoCommit;
1046 my $error = $self->SUPER::delete;
1048 $dbh->rollback if $oldAutoCommit;
1052 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1057 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1059 Replaces the OLD_RECORD with this one in the database. If there is an error,
1060 returns the error, otherwise returns false.
1062 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1063 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1064 expected and rollback the entire transaction; it is not necessary to call
1065 check_invoicing_list first. Here's an example:
1067 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1075 warn "$me replace called\n"
1078 local $SIG{HUP} = 'IGNORE';
1079 local $SIG{INT} = 'IGNORE';
1080 local $SIG{QUIT} = 'IGNORE';
1081 local $SIG{TERM} = 'IGNORE';
1082 local $SIG{TSTP} = 'IGNORE';
1083 local $SIG{PIPE} = 'IGNORE';
1085 # We absolutely have to have an old vs. new record to make this work.
1086 if (!defined($old)) {
1087 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1090 my $curuser = $FS::CurrentUser::CurrentUser;
1091 if ( $self->payby eq 'COMP'
1092 && $self->payby ne $old->payby
1093 && ! $curuser->access_right('Complimentary customer')
1096 return "You are not permitted to create complimentary accounts.";
1099 local($ignore_expired_card) = 1
1100 if $old->payby =~ /^(CARD|DCRD)$/
1101 && $self->payby =~ /^(CARD|DCRD)$/
1102 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1104 my $oldAutoCommit = $FS::UID::AutoCommit;
1105 local $FS::UID::AutoCommit = 0;
1108 my $error = $self->SUPER::replace($old);
1111 $dbh->rollback if $oldAutoCommit;
1115 if ( @param ) { # INVOICING_LIST_ARYREF
1116 my $invoicing_list = shift @param;
1117 $error = $self->check_invoicing_list( $invoicing_list );
1119 $dbh->rollback if $oldAutoCommit;
1122 $self->invoicing_list( $invoicing_list );
1125 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1126 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1127 # card/check/lec info has changed, want to retry realtime_ invoice events
1128 my $error = $self->retry_realtime;
1130 $dbh->rollback if $oldAutoCommit;
1135 unless ( $import || $skip_fuzzyfiles ) {
1136 $error = $self->queue_fuzzyfiles_update;
1138 $dbh->rollback if $oldAutoCommit;
1139 return "updating fuzzy search cache: $error";
1143 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1148 =item queue_fuzzyfiles_update
1150 Used by insert & replace to update the fuzzy search cache
1154 sub queue_fuzzyfiles_update {
1157 local $SIG{HUP} = 'IGNORE';
1158 local $SIG{INT} = 'IGNORE';
1159 local $SIG{QUIT} = 'IGNORE';
1160 local $SIG{TERM} = 'IGNORE';
1161 local $SIG{TSTP} = 'IGNORE';
1162 local $SIG{PIPE} = 'IGNORE';
1164 my $oldAutoCommit = $FS::UID::AutoCommit;
1165 local $FS::UID::AutoCommit = 0;
1168 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1169 my $error = $queue->insert( map $self->getfield($_),
1170 qw(first last company)
1173 $dbh->rollback if $oldAutoCommit;
1174 return "queueing job (transaction rolled back): $error";
1177 if ( $self->ship_last ) {
1178 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1179 $error = $queue->insert( map $self->getfield("ship_$_"),
1180 qw(first last company)
1183 $dbh->rollback if $oldAutoCommit;
1184 return "queueing job (transaction rolled back): $error";
1188 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1195 Checks all fields to make sure this is a valid customer record. If there is
1196 an error, returns the error, otherwise returns false. Called by the insert
1197 and replace methods.
1204 warn "$me check BEFORE: \n". $self->_dump
1208 $self->ut_numbern('custnum')
1209 || $self->ut_number('agentnum')
1210 || $self->ut_textn('agent_custid')
1211 || $self->ut_number('refnum')
1212 || $self->ut_name('last')
1213 || $self->ut_name('first')
1214 || $self->ut_snumbern('birthdate')
1215 || $self->ut_snumbern('signupdate')
1216 || $self->ut_textn('company')
1217 || $self->ut_text('address1')
1218 || $self->ut_textn('address2')
1219 || $self->ut_text('city')
1220 || $self->ut_textn('county')
1221 || $self->ut_textn('state')
1222 || $self->ut_country('country')
1223 || $self->ut_anything('comments')
1224 || $self->ut_numbern('referral_custnum')
1225 || $self->ut_textn('stateid')
1226 || $self->ut_textn('stateid_state')
1227 || $self->ut_textn('invoice_terms')
1229 #barf. need message catalogs. i18n. etc.
1230 $error .= "Please select an advertising source."
1231 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1232 return $error if $error;
1234 return "Unknown agent"
1235 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1237 return "Unknown refnum"
1238 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1240 return "Unknown referring custnum: ". $self->referral_custnum
1241 unless ! $self->referral_custnum
1242 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1244 if ( $self->ss eq '' ) {
1249 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1250 or return "Illegal social security number: ". $self->ss;
1251 $self->ss("$1-$2-$3");
1255 # bad idea to disable, causes billing to fail because of no tax rates later
1256 # unless ( $import ) {
1257 unless ( qsearch('cust_main_county', {
1258 'country' => $self->country,
1261 return "Unknown state/county/country: ".
1262 $self->state. "/". $self->county. "/". $self->country
1263 unless qsearch('cust_main_county',{
1264 'state' => $self->state,
1265 'county' => $self->county,
1266 'country' => $self->country,
1272 $self->ut_phonen('daytime', $self->country)
1273 || $self->ut_phonen('night', $self->country)
1274 || $self->ut_phonen('fax', $self->country)
1275 || $self->ut_zip('zip', $self->country)
1277 return $error if $error;
1279 if ( $conf->exists('cust_main-require_phone')
1280 && ! length($self->daytime) && ! length($self->night)
1283 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1285 : FS::Msgcat::_gettext('daytime');
1286 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1288 : FS::Msgcat::_gettext('night');
1290 return "$daytime_label or $night_label is required"
1294 if ( $self->has_ship_address
1295 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1296 $self->addr_fields )
1300 $self->ut_name('ship_last')
1301 || $self->ut_name('ship_first')
1302 || $self->ut_textn('ship_company')
1303 || $self->ut_text('ship_address1')
1304 || $self->ut_textn('ship_address2')
1305 || $self->ut_text('ship_city')
1306 || $self->ut_textn('ship_county')
1307 || $self->ut_textn('ship_state')
1308 || $self->ut_country('ship_country')
1310 return $error if $error;
1312 #false laziness with above
1313 unless ( qsearchs('cust_main_county', {
1314 'country' => $self->ship_country,
1317 return "Unknown ship_state/ship_county/ship_country: ".
1318 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1319 unless qsearch('cust_main_county',{
1320 'state' => $self->ship_state,
1321 'county' => $self->ship_county,
1322 'country' => $self->ship_country,
1328 $self->ut_phonen('ship_daytime', $self->ship_country)
1329 || $self->ut_phonen('ship_night', $self->ship_country)
1330 || $self->ut_phonen('ship_fax', $self->ship_country)
1331 || $self->ut_zip('ship_zip', $self->ship_country)
1333 return $error if $error;
1335 return "Unit # is required."
1336 if $self->ship_address2 =~ /^\s*$/
1337 && $conf->exists('cust_main-require_address2');
1339 } else { # ship_ info eq billing info, so don't store dup info in database
1341 $self->setfield("ship_$_", '')
1342 foreach $self->addr_fields;
1344 return "Unit # is required."
1345 if $self->address2 =~ /^\s*$/
1346 && $conf->exists('cust_main-require_address2');
1350 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1351 # or return "Illegal payby: ". $self->payby;
1353 FS::payby->can_payby($self->table, $self->payby)
1354 or return "Illegal payby: ". $self->payby;
1356 $error = $self->ut_numbern('paystart_month')
1357 || $self->ut_numbern('paystart_year')
1358 || $self->ut_numbern('payissue')
1359 || $self->ut_textn('paytype')
1361 return $error if $error;
1363 if ( $self->payip eq '' ) {
1366 $error = $self->ut_ip('payip');
1367 return $error if $error;
1370 # If it is encrypted and the private key is not availaible then we can't
1371 # check the credit card.
1373 my $check_payinfo = 1;
1375 if ($self->is_encrypted($self->payinfo)) {
1379 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1381 my $payinfo = $self->payinfo;
1382 $payinfo =~ s/\D//g;
1383 $payinfo =~ /^(\d{13,16})$/
1384 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1386 $self->payinfo($payinfo);
1388 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1390 return gettext('unknown_card_type')
1391 if cardtype($self->payinfo) eq "Unknown";
1393 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1395 return 'Banned credit card: banned on '.
1396 time2str('%a %h %o at %r', $ban->_date).
1397 ' by '. $ban->otaker.
1398 ' (ban# '. $ban->bannum. ')';
1401 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1402 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1403 $self->paycvv =~ /^(\d{4})$/
1404 or return "CVV2 (CID) for American Express cards is four digits.";
1407 $self->paycvv =~ /^(\d{3})$/
1408 or return "CVV2 (CVC2/CID) is three digits.";
1415 my $cardtype = cardtype($payinfo);
1416 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1418 return "Start date or issue number is required for $cardtype cards"
1419 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1421 return "Start month must be between 1 and 12"
1422 if $self->paystart_month
1423 and $self->paystart_month < 1 || $self->paystart_month > 12;
1425 return "Start year must be 1990 or later"
1426 if $self->paystart_year
1427 and $self->paystart_year < 1990;
1429 return "Issue number must be beween 1 and 99"
1431 and $self->payissue < 1 || $self->payissue > 99;
1434 $self->paystart_month('');
1435 $self->paystart_year('');
1436 $self->payissue('');
1439 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1441 my $payinfo = $self->payinfo;
1442 $payinfo =~ s/[^\d\@]//g;
1443 if ( $conf->exists('echeck-nonus') ) {
1444 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1445 $payinfo = "$1\@$2";
1447 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1448 $payinfo = "$1\@$2";
1450 $self->payinfo($payinfo);
1453 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1455 return 'Banned ACH account: banned on '.
1456 time2str('%a %h %o at %r', $ban->_date).
1457 ' by '. $ban->otaker.
1458 ' (ban# '. $ban->bannum. ')';
1461 } elsif ( $self->payby eq 'LECB' ) {
1463 my $payinfo = $self->payinfo;
1464 $payinfo =~ s/\D//g;
1465 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1467 $self->payinfo($payinfo);
1470 } elsif ( $self->payby eq 'BILL' ) {
1472 $error = $self->ut_textn('payinfo');
1473 return "Illegal P.O. number: ". $self->payinfo if $error;
1476 } elsif ( $self->payby eq 'COMP' ) {
1478 my $curuser = $FS::CurrentUser::CurrentUser;
1479 if ( ! $self->custnum
1480 && ! $curuser->access_right('Complimentary customer')
1483 return "You are not permitted to create complimentary accounts."
1486 $error = $self->ut_textn('payinfo');
1487 return "Illegal comp account issuer: ". $self->payinfo if $error;
1490 } elsif ( $self->payby eq 'PREPAY' ) {
1492 my $payinfo = $self->payinfo;
1493 $payinfo =~ s/\W//g; #anything else would just confuse things
1494 $self->payinfo($payinfo);
1495 $error = $self->ut_alpha('payinfo');
1496 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1497 return "Unknown prepayment identifier"
1498 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1503 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1504 return "Expiration date required"
1505 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1509 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1510 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1511 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1512 ( $m, $y ) = ( $3, "20$2" );
1514 return "Illegal expiration date: ". $self->paydate;
1516 $self->paydate("$y-$m-01");
1517 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1518 return gettext('expired_card')
1520 && !$ignore_expired_card
1521 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1524 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1525 ( ! $conf->exists('require_cardname')
1526 || $self->payby !~ /^(CARD|DCRD)$/ )
1528 $self->payname( $self->first. " ". $self->getfield('last') );
1530 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1531 or return gettext('illegal_name'). " payname: ". $self->payname;
1535 foreach my $flag (qw( tax spool_cdr )) {
1536 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1540 $self->otaker(getotaker) unless $self->otaker;
1542 warn "$me check AFTER: \n". $self->_dump
1545 $self->SUPER::check;
1550 Returns a list of fields which have ship_ duplicates.
1555 qw( last first company
1556 address1 address2 city county state zip country
1561 =item has_ship_address
1563 Returns true if this customer record has a separate shipping address.
1567 sub has_ship_address {
1569 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1574 Returns all packages (see L<FS::cust_pkg>) for this customer.
1581 return $self->num_pkgs unless wantarray;
1584 if ( $self->{'_pkgnum'} ) {
1585 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1587 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1590 sort sort_packages @cust_pkg;
1595 Synonym for B<all_pkgs>.
1600 shift->all_pkgs(@_);
1603 =item ncancelled_pkgs
1605 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1609 sub ncancelled_pkgs {
1612 return $self->num_ncancelled_pkgs unless wantarray;
1615 if ( $self->{'_pkgnum'} ) {
1617 warn "$me ncancelled_pkgs: returning cached objects"
1620 @cust_pkg = grep { ! $_->getfield('cancel') }
1621 values %{ $self->{'_pkgnum'}->cache };
1625 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1626 $self->custnum. "\n"
1630 qsearch( 'cust_pkg', {
1631 'custnum' => $self->custnum,
1635 qsearch( 'cust_pkg', {
1636 'custnum' => $self->custnum,
1641 sort sort_packages @cust_pkg;
1645 # This should be generalized to use config options to determine order.
1647 if ( $a->get('cancel') and $b->get('cancel') ) {
1648 $a->pkgnum <=> $b->pkgnum;
1649 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1650 return -1 if $b->get('cancel');
1651 return 1 if $a->get('cancel');
1654 $a->pkgnum <=> $b->pkgnum;
1658 =item suspended_pkgs
1660 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1664 sub suspended_pkgs {
1666 grep { $_->susp } $self->ncancelled_pkgs;
1669 =item unflagged_suspended_pkgs
1671 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1672 customer (thouse packages without the `manual_flag' set).
1676 sub unflagged_suspended_pkgs {
1678 return $self->suspended_pkgs
1679 unless dbdef->table('cust_pkg')->column('manual_flag');
1680 grep { ! $_->manual_flag } $self->suspended_pkgs;
1683 =item unsuspended_pkgs
1685 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1690 sub unsuspended_pkgs {
1692 grep { ! $_->susp } $self->ncancelled_pkgs;
1695 =item num_cancelled_pkgs
1697 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1702 sub num_cancelled_pkgs {
1703 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1706 sub num_ncancelled_pkgs {
1707 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1711 my( $self ) = shift;
1712 my $sql = scalar(@_) ? shift : '';
1713 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1714 my $sth = dbh->prepare(
1715 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1716 ) or die dbh->errstr;
1717 $sth->execute($self->custnum) or die $sth->errstr;
1718 $sth->fetchrow_arrayref->[0];
1723 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1724 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1725 on success or a list of errors.
1731 grep { $_->unsuspend } $self->suspended_pkgs;
1736 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1738 Returns a list: an empty list on success or a list of errors.
1744 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1747 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1749 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1750 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1751 of a list of pkgparts; the hashref has the following keys:
1755 =item pkgparts - listref of pkgparts
1757 =item (other options are passed to the suspend method)
1762 Returns a list: an empty list on success or a list of errors.
1766 sub suspend_if_pkgpart {
1768 my (@pkgparts, %opt);
1769 if (ref($_[0]) eq 'HASH'){
1770 @pkgparts = @{$_[0]{pkgparts}};
1775 grep { $_->suspend(%opt) }
1776 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1777 $self->unsuspended_pkgs;
1780 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1782 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1783 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1784 instead of a list of pkgparts; the hashref has the following keys:
1788 =item pkgparts - listref of pkgparts
1790 =item (other options are passed to the suspend method)
1794 Returns a list: an empty list on success or a list of errors.
1798 sub suspend_unless_pkgpart {
1800 my (@pkgparts, %opt);
1801 if (ref($_[0]) eq 'HASH'){
1802 @pkgparts = @{$_[0]{pkgparts}};
1807 grep { $_->suspend(%opt) }
1808 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1809 $self->unsuspended_pkgs;
1812 =item cancel [ OPTION => VALUE ... ]
1814 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1816 Available options are:
1820 =item quiet - can be set true to supress email cancellation notices.
1822 =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.
1824 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1828 Always returns a list: an empty list on success or a list of errors.
1833 my( $self, %opt ) = @_;
1835 warn "$me cancel called on customer ". $self->custnum. " with options ".
1836 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1839 return ( 'access denied' )
1840 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1842 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1844 #should try decryption (we might have the private key)
1845 # and if not maybe queue a job for the server that does?
1846 return ( "Can't (yet) ban encrypted credit cards" )
1847 if $self->is_encrypted($self->payinfo);
1849 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1850 my $error = $ban->insert;
1851 return ( $error ) if $error;
1855 my @pkgs = $self->ncancelled_pkgs;
1857 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1858 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1861 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1864 sub _banned_pay_hashref {
1875 'payby' => $payby2ban{$self->payby},
1876 'payinfo' => md5_base64($self->payinfo),
1877 #don't ever *search* on reason! #'reason' =>
1883 Returns all notes (see L<FS::cust_main_note>) for this customer.
1890 qsearch( 'cust_main_note',
1891 { 'custnum' => $self->custnum },
1893 'ORDER BY _DATE DESC'
1899 Returns the agent (see L<FS::agent>) for this customer.
1905 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1908 =item bill_and_collect
1910 Cancels and suspends any packages due, generates bills, applies payments and
1913 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1915 Options are passed as name-value pairs. Currently available options are:
1921 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:
1925 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1929 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.
1933 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1937 If set true, re-charges setup fees.
1941 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)
1947 sub bill_and_collect {
1948 my( $self, %options ) = @_;
1954 #$^T not $options{time} because freeside-daily -d is for pre-printing invoices
1955 foreach my $cust_pkg (
1956 grep { $_->expire && $_->expire <= $^T } $self->ncancelled_pkgs
1958 my $error = $cust_pkg->cancel;
1959 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1960 " for custnum ". $self->custnum. ": $error"
1968 #$^T not $options{time} because freeside-daily -d is for pre-printing invoices
1969 foreach my $cust_pkg (
1970 grep { ( $_->part_pkg->is_prepaid && $_->bill && $_->bill < $^T
1971 || $_->adjourn && $_->adjourn <= $^T
1975 $self->ncancelled_pkgs
1977 my $error = $cust_pkg->suspend;
1978 warn "Error suspending package ". $cust_pkg->pkgnum.
1979 " for custnum ". $self->custnum. ": $error"
1987 my $error = $self->bill( %options );
1988 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
1990 $self->apply_payments_and_credits;
1992 $error = $self->collect( %options );
1993 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
1999 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2000 conjunction with the collect method by calling B<bill_and_collect>.
2002 If there is an error, returns the error, otherwise returns false.
2004 Options are passed as name-value pairs. Currently available options are:
2010 If set true, re-charges setup fees.
2014 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:
2018 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2022 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2024 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2028 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.
2035 my( $self, %options ) = @_;
2036 return '' if $self->payby eq 'COMP';
2037 warn "$me bill customer ". $self->custnum. "\n"
2040 my $time = $options{'time'} || time;
2045 local $SIG{HUP} = 'IGNORE';
2046 local $SIG{INT} = 'IGNORE';
2047 local $SIG{QUIT} = 'IGNORE';
2048 local $SIG{TERM} = 'IGNORE';
2049 local $SIG{TSTP} = 'IGNORE';
2050 local $SIG{PIPE} = 'IGNORE';
2052 my $oldAutoCommit = $FS::UID::AutoCommit;
2053 local $FS::UID::AutoCommit = 0;
2056 $self->select_for_update; #mutex
2058 #create a new invoice
2059 #(we'll remove it later if it doesn't actually need to be generated [contains
2060 # no line items] and we're inside a transaciton so nothing else will see it)
2061 my $cust_bill = new FS::cust_bill ( {
2062 'custnum' => $self->custnum,
2063 '_date' => ( $options{'invoice_time'} || $time ),
2064 #'charged' => $charged,
2067 $error = $cust_bill->insert;
2069 $dbh->rollback if $oldAutoCommit;
2070 return "can't create invoice for customer #". $self->custnum. ": $error";
2072 my $invnum = $cust_bill->invnum;
2075 # find the packages which are due for billing, find out how much they are
2076 # & generate invoice database.
2079 my( $total_setup, $total_recur ) = ( 0, 0 );
2081 my @precommit_hooks = ();
2083 foreach my $cust_pkg (
2084 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
2087 #NO!! next if $cust_pkg->cancel;
2088 next if $cust_pkg->getfield('cancel');
2090 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2092 #? to avoid use of uninitialized value errors... ?
2093 $cust_pkg->setfield('bill', '')
2094 unless defined($cust_pkg->bill);
2096 my $part_pkg = $cust_pkg->part_pkg;
2098 my %hash = $cust_pkg->hash;
2099 my $old_cust_pkg = new FS::cust_pkg \%hash;
2108 if ( ! $cust_pkg->setup &&
2110 ( $conf->exists('disable_setup_suspended_pkgs') &&
2111 ! $cust_pkg->getfield('susp')
2112 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2114 || $options{'resetup'}
2117 warn " bill setup\n" if $DEBUG > 1;
2119 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2121 $dbh->rollback if $oldAutoCommit;
2122 return "$@ running calc_setup for $cust_pkg\n";
2125 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
2129 # bill recurring fee
2134 if ( $part_pkg->getfield('freq') ne '0' &&
2135 ! $cust_pkg->getfield('susp') &&
2136 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2139 # XXX should this be a package event? probably. events are called
2140 # at collection time at the moment, though...
2141 if ( $part_pkg->can('reset_usage') ) {
2142 warn " resetting usage counters" if $DEBUG > 1;
2143 $part_pkg->reset_usage($cust_pkg);
2146 warn " bill recur\n" if $DEBUG > 1;
2148 # XXX shared with $recur_prog
2149 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2151 #over two params! lets at least switch to a hashref for the rest...
2152 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
2154 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2156 $dbh->rollback if $oldAutoCommit;
2157 return "$@ running calc_recur for $cust_pkg\n";
2160 #change this bit to use Date::Manip? CAREFUL with timezones (see
2161 # mailing list archive)
2162 my ($sec,$min,$hour,$mday,$mon,$year) =
2163 (localtime($sdate) )[0,1,2,3,4,5];
2165 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2166 # only for figuring next bill date, nothing else, so, reset $sdate again
2168 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2169 $cust_pkg->last_bill($sdate);
2171 if ( $part_pkg->freq =~ /^\d+$/ ) {
2172 $mon += $part_pkg->freq;
2173 until ( $mon < 12 ) { $mon -= 12; $year++; }
2174 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2176 $mday += $weeks * 7;
2177 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2180 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2184 $dbh->rollback if $oldAutoCommit;
2185 return "unparsable frequency: ". $part_pkg->freq;
2187 $cust_pkg->setfield('bill',
2188 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2191 warn "\$setup is undefined" unless defined($setup);
2192 warn "\$recur is undefined" unless defined($recur);
2193 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2196 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2199 if ( $cust_pkg->modified ) { # hmmm.. and if the options are modified?
2201 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2204 $error=$cust_pkg->replace($old_cust_pkg,
2205 options => { $cust_pkg->options },
2207 if ( $error ) { #just in case
2208 $dbh->rollback if $oldAutoCommit;
2209 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2212 $setup = sprintf( "%.2f", $setup );
2213 $recur = sprintf( "%.2f", $recur );
2214 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2215 $dbh->rollback if $oldAutoCommit;
2216 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2218 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2219 $dbh->rollback if $oldAutoCommit;
2220 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2223 if ( $setup != 0 || $recur != 0 ) {
2225 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2227 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2228 'invnum' => $invnum,
2229 'pkgnum' => $cust_pkg->pkgnum,
2233 'edate' => $cust_pkg->bill,
2234 'details' => \@details,
2236 $error = $cust_bill_pkg->insert;
2238 $dbh->rollback if $oldAutoCommit;
2239 return "can't create invoice line item for invoice #$invnum: $error";
2241 $total_setup += $setup;
2242 $total_recur += $recur;
2248 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2251 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2254 my %taxhash = map { $_ => $self->get("$prefix$_") }
2255 qw( state county country );
2257 $taxhash{'taxclass'} = $part_pkg->taxclass;
2259 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2262 $taxhash{'taxclass'} = '';
2263 @taxes = qsearch( 'cust_main_county', \%taxhash );
2266 #one more try at a whole-country tax rate
2268 $taxhash{$_} = '' foreach qw( state county );
2269 @taxes = qsearch( 'cust_main_county', \%taxhash );
2272 # maybe eliminate this entirely, along with all the 0% records
2274 $dbh->rollback if $oldAutoCommit;
2276 "fatal: can't find tax rate for state/county/country/taxclass ".
2277 join('/', ( map $self->get("$prefix$_"),
2278 qw(state county country)
2280 $part_pkg->taxclass ). "\n";
2283 foreach my $tax ( @taxes ) {
2285 my $taxable_charged = 0;
2286 $taxable_charged += $setup
2287 unless $part_pkg->setuptax =~ /^Y$/i
2288 || $tax->setuptax =~ /^Y$/i;
2289 $taxable_charged += $recur
2290 unless $part_pkg->recurtax =~ /^Y$/i
2291 || $tax->recurtax =~ /^Y$/i;
2292 next unless $taxable_charged;
2294 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2295 #my ($mon,$year) = (localtime($sdate) )[4,5];
2296 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2298 my $freq = $part_pkg->freq || 1;
2299 if ( $freq !~ /(\d+)$/ ) {
2300 $dbh->rollback if $oldAutoCommit;
2301 return "daily/weekly package definitions not (yet?)".
2302 " compatible with monthly tax exemptions";
2304 my $taxable_per_month =
2305 sprintf("%.2f", $taxable_charged / $freq );
2307 #call the whole thing off if this customer has any old
2308 #exemption records...
2309 my @cust_tax_exempt =
2310 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2311 if ( @cust_tax_exempt ) {
2312 $dbh->rollback if $oldAutoCommit;
2314 'this customer still has old-style tax exemption records; '.
2315 'run bin/fs-migrate-cust_tax_exempt?';
2318 foreach my $which_month ( 1 .. $freq ) {
2320 #maintain the new exemption table now
2323 FROM cust_tax_exempt_pkg
2324 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2325 LEFT JOIN cust_bill USING ( invnum )
2331 my $sth = dbh->prepare($sql) or do {
2332 $dbh->rollback if $oldAutoCommit;
2333 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2341 $dbh->rollback if $oldAutoCommit;
2342 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2344 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2346 my $remaining_exemption =
2347 $tax->exempt_amount - $existing_exemption;
2348 if ( $remaining_exemption > 0 ) {
2349 my $addl = $remaining_exemption > $taxable_per_month
2350 ? $taxable_per_month
2351 : $remaining_exemption;
2352 $taxable_charged -= $addl;
2354 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2355 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2356 'taxnum' => $tax->taxnum,
2357 'year' => 1900+$year,
2359 'amount' => sprintf("%.2f", $addl ),
2361 $error = $cust_tax_exempt_pkg->insert;
2363 $dbh->rollback if $oldAutoCommit;
2364 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2366 } # if $remaining_exemption > 0
2370 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2371 until ( $mon < 13 ) { $mon -= 12; $year++; }
2373 } #foreach $which_month
2375 } #if $tax->exempt_amount
2377 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2379 #$tax += $taxable_charged * $cust_main_county->tax / 100
2380 $tax{ $tax->taxname || 'Tax' } +=
2381 $taxable_charged * $tax->tax / 100
2383 } #foreach my $tax ( @taxes )
2385 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2387 } #if $setup != 0 || $recur != 0
2389 } #if $cust_pkg->modified
2391 } #foreach my $cust_pkg
2393 unless ( $cust_bill->cust_bill_pkg ) {
2394 $cust_bill->delete; #don't create an invoice w/o line items
2396 # XXX this seems to be broken
2397 #( DBD::Pg::st execute failed: ERROR: syntax error at or near "hcb" )
2398 # # get rid of our fake history too, waste of unecessary space
2399 # my $h_cleanup_query = q{
2400 # DELETE FROM h_cust_bill hcb
2401 # WHERE hcb.invnum = ?
2402 # AND NOT EXISTS ( SELECT 1 FROM cust_bill cb where cb.invnum = hcb.invnum )
2404 # my $h_sth = $dbh->prepare($h_cleanup_query);
2405 # $h_sth->execute($invnum);
2407 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2411 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2413 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2414 my $tax = sprintf("%.2f", $tax{$taxname} );
2415 $charged = sprintf( "%.2f", $charged+$tax );
2417 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2418 'invnum' => $invnum,
2424 'itemdesc' => $taxname,
2426 $error = $cust_bill_pkg->insert;
2428 $dbh->rollback if $oldAutoCommit;
2429 return "can't create invoice line item for invoice #$invnum: $error";
2431 $total_setup += $tax;
2435 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2436 $error = $cust_bill->replace;
2438 $dbh->rollback if $oldAutoCommit;
2439 return "can't update charged for invoice #$invnum: $error";
2442 foreach my $hook ( @precommit_hooks ) {
2444 &{$hook}; #($self) ?
2447 $dbh->rollback if $oldAutoCommit;
2448 return "$@ running precommit hook $hook\n";
2452 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2456 =item collect OPTIONS
2458 (Attempt to) collect money for this customer's outstanding invoices (see
2459 L<FS::cust_bill>). Usually used after the bill method.
2461 Actions are now triggered by billing events; see L<FS::part_event> and the
2462 billing events web interface. Old-style invoice events (see
2463 L<FS::part_bill_event>) have been deprecated.
2465 If there is an error, returns the error, otherwise returns false.
2467 Options are passed as name-value pairs.
2469 Currently available options are:
2475 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.
2479 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2483 set true to surpress email card/ACH decline notices.
2487 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2491 allows for one time override of normal customer billing method
2495 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)
2503 my( $self, %options ) = @_;
2504 my $invoice_time = $options{'invoice_time'} || time;
2507 local $SIG{HUP} = 'IGNORE';
2508 local $SIG{INT} = 'IGNORE';
2509 local $SIG{QUIT} = 'IGNORE';
2510 local $SIG{TERM} = 'IGNORE';
2511 local $SIG{TSTP} = 'IGNORE';
2512 local $SIG{PIPE} = 'IGNORE';
2514 my $oldAutoCommit = $FS::UID::AutoCommit;
2515 local $FS::UID::AutoCommit = 0;
2518 $self->select_for_update; #mutex
2521 my $balance = $self->balance;
2522 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2525 if ( exists($options{'retry_card'}) ) {
2526 carp 'retry_card option passed to collect is deprecated; use retry';
2527 $options{'retry'} ||= $options{'retry_card'};
2529 if ( exists($options{'retry'}) && $options{'retry'} ) {
2530 my $error = $self->retry_realtime;
2532 $dbh->rollback if $oldAutoCommit;
2537 # false laziness w/pay_batch::import_results
2539 my $due_cust_event = $self->due_cust_event(
2540 'debug' => ( $options{'debug'} || 0 ),
2541 'time' => $invoice_time,
2542 'check_freq' => $options{'check_freq'},
2544 unless( ref($due_cust_event) ) {
2545 $dbh->rollback if $oldAutoCommit;
2546 return $due_cust_event;
2549 foreach my $cust_event ( @$due_cust_event ) {
2553 #re-eval event conditions (a previous event could have changed things)
2554 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2555 #don't leave stray "new/locked" records around
2556 my $error = $cust_event->delete;
2558 #gah, even with transactions
2559 $dbh->commit if $oldAutoCommit; #well.
2566 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2567 warn " running cust_event ". $cust_event->eventnum. "\n"
2571 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2572 if ( my $error = $cust_event->do_event() ) {
2573 #XXX wtf is this? figure out a proper dealio with return value
2575 # gah, even with transactions.
2576 $dbh->commit if $oldAutoCommit; #well.
2583 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2588 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2590 Inserts database records for and returns an ordered listref of new events due
2591 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2592 events are due, an empty listref is returned. If there is an error, returns a
2593 scalar error message.
2595 To actually run the events, call each event's test_condition method, and if
2596 still true, call the event's do_event method.
2598 Options are passed as a hashref or as a list of name-value pairs. Available
2605 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.
2609 "Current time" for the events.
2613 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)
2617 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2621 Explicitly pass the objects to be tested (typically used with eventtable).
2627 sub due_cust_event {
2629 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2632 #my $DEBUG = $opt{'debug'}
2633 local($DEBUG) = $opt{'debug'}
2634 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2636 warn "$me due_cust_event called with options ".
2637 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2640 $opt{'time'} ||= time;
2642 local $SIG{HUP} = 'IGNORE';
2643 local $SIG{INT} = 'IGNORE';
2644 local $SIG{QUIT} = 'IGNORE';
2645 local $SIG{TERM} = 'IGNORE';
2646 local $SIG{TSTP} = 'IGNORE';
2647 local $SIG{PIPE} = 'IGNORE';
2649 my $oldAutoCommit = $FS::UID::AutoCommit;
2650 local $FS::UID::AutoCommit = 0;
2653 $self->select_for_update; #mutex
2656 # 1: find possible events (initial search)
2659 my @cust_event = ();
2661 my @eventtable = $opt{'eventtable'}
2662 ? ( $opt{'eventtable'} )
2663 : FS::part_event->eventtables_runorder;
2665 foreach my $eventtable ( @eventtable ) {
2668 if ( $opt{'objects'} ) {
2670 @objects = @{ $opt{'objects'} };
2674 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2675 @objects = ( $eventtable eq 'cust_main' )
2677 : ( $self->$eventtable() );
2681 my @e_cust_event = ();
2683 my $cross = "CROSS JOIN $eventtable";
2684 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2685 unless $eventtable eq 'cust_main';
2687 foreach my $object ( @objects ) {
2689 #this first search uses the condition_sql magic for optimization.
2690 #the more possible events we can eliminate in this step the better
2692 my $cross_where = '';
2693 my $pkey = $object->primary_key;
2694 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2696 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2698 FS::part_event_condition->where_conditions_sql( $eventtable,
2699 'time'=>$opt{'time'}
2701 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2703 $extra_sql = "AND $extra_sql" if $extra_sql;
2705 #here is the agent virtualization
2706 $extra_sql .= " AND ( part_event.agentnum IS NULL
2707 OR part_event.agentnum = ". $self->agentnum. ' )';
2709 $extra_sql .= " $order";
2711 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2712 if $opt{'debug'} > 2;
2713 my @part_event = qsearch( {
2714 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2715 'select' => 'part_event.*',
2716 'table' => 'part_event',
2717 'addl_from' => "$cross $join",
2718 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2719 'eventtable' => $eventtable,
2722 'extra_sql' => "AND $cross_where $extra_sql",
2726 my $pkey = $object->primary_key;
2727 warn " ". scalar(@part_event).
2728 " possible events found for $eventtable ". $object->$pkey(). "\n";
2731 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2735 warn " ". scalar(@e_cust_event).
2736 " subtotal possible cust events found for $eventtable\n"
2739 push @cust_event, @e_cust_event;
2743 warn " ". scalar(@cust_event).
2744 " total possible cust events found in initial search\n"
2748 # 2: test conditions
2753 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
2754 'stats_hashref' => \%unsat ),
2757 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
2760 warn " invalid conditions not eliminated with condition_sql:\n".
2761 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
2768 foreach my $cust_event ( @cust_event ) {
2770 my $error = $cust_event->insert();
2772 $dbh->rollback if $oldAutoCommit;
2778 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2784 warn " returning events: ". Dumper(@cust_event). "\n"
2791 =item retry_realtime
2793 Schedules realtime / batch credit card / electronic check / LEC billing
2794 events for for retry. Useful if card information has changed or manual
2795 retry is desired. The 'collect' method must be called to actually retry
2798 Implementation details: For either this customer, or for each of this
2799 customer's open invoices, changes the status of the first "done" (with
2800 statustext error) realtime processing event to "failed".
2804 sub retry_realtime {
2807 local $SIG{HUP} = 'IGNORE';
2808 local $SIG{INT} = 'IGNORE';
2809 local $SIG{QUIT} = 'IGNORE';
2810 local $SIG{TERM} = 'IGNORE';
2811 local $SIG{TSTP} = 'IGNORE';
2812 local $SIG{PIPE} = 'IGNORE';
2814 my $oldAutoCommit = $FS::UID::AutoCommit;
2815 local $FS::UID::AutoCommit = 0;
2818 #a little false laziness w/due_cust_event (not too bad, really)
2820 my $join = FS::part_event_condition->join_conditions_sql;
2821 my $order = FS::part_event_condition->order_conditions_sql;
2824 . join ( ' OR ' , map {
2825 "( part_event.eventtable = " . dbh->quote($_)
2826 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
2827 } FS::part_event->eventtables)
2830 #here is the agent virtualization
2831 my $agent_virt = " ( part_event.agentnum IS NULL
2832 OR part_event.agentnum = ". $self->agentnum. ' )';
2834 #XXX this shouldn't be hardcoded, actions should declare it...
2835 my @realtime_events = qw(
2836 cust_bill_realtime_card
2837 cust_bill_realtime_check
2838 cust_bill_realtime_lec
2842 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
2847 my @cust_event = qsearchs({
2848 'table' => 'cust_event',
2849 'select' => 'cust_event.*',
2850 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
2851 'hashref' => { 'status' => 'done' },
2852 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
2853 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
2856 my %seen_invnum = ();
2857 foreach my $cust_event (@cust_event) {
2859 #max one for the customer, one for each open invoice
2860 my $cust_X = $cust_event->cust_X;
2861 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
2865 or $cust_event->part_event->eventtable eq 'cust_bill'
2868 my $error = $cust_event->retry;
2870 $dbh->rollback if $oldAutoCommit;
2871 return "error scheduling event for retry: $error";
2876 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2881 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2883 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2884 via a Business::OnlinePayment realtime gateway. See
2885 L<http://420.am/business-onlinepayment> for supported gateways.
2887 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2889 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
2891 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2892 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2893 if set, will override the value from the customer record.
2895 I<description> is a free-text field passed to the gateway. It defaults to
2896 "Internet services".
2898 If an I<invnum> is specified, this payment (if successful) is applied to the
2899 specified invoice. If you don't specify an I<invnum> you might want to
2900 call the B<apply_payments> method.
2902 I<quiet> can be set true to surpress email decline notices.
2904 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
2905 resulting paynum, if any.
2907 I<payunique> is a unique identifier for this payment.
2909 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2914 my( $self, $method, $amount, %options ) = @_;
2916 warn "$me realtime_bop: $method $amount\n";
2917 warn " $_ => $options{$_}\n" foreach keys %options;
2920 $options{'description'} ||= 'Internet services';
2922 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
2924 eval "use Business::OnlinePayment";
2927 my $payinfo = exists($options{'payinfo'})
2928 ? $options{'payinfo'}
2931 my %method2payby = (
2938 # check for banned credit card/ACH
2941 my $ban = qsearchs('banned_pay', {
2942 'payby' => $method2payby{$method},
2943 'payinfo' => md5_base64($payinfo),
2945 return "Banned credit card" if $ban;
2952 if ( $options{'invnum'} ) {
2953 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2954 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2956 map { $_->part_pkg->taxclass }
2958 map { $_->cust_pkg }
2959 $cust_bill->cust_bill_pkg;
2960 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2961 #different taxclasses
2962 $taxclass = $taxclasses[0];
2966 #look for an agent gateway override first
2968 if ( $method eq 'CC' ) {
2969 $cardtype = cardtype($payinfo);
2970 } elsif ( $method eq 'ECHECK' ) {
2973 $cardtype = $method;
2977 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2978 cardtype => $cardtype,
2979 taxclass => $taxclass, } )
2980 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2982 taxclass => $taxclass, } )
2983 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2984 cardtype => $cardtype,
2986 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2988 taxclass => '', } );
2990 my $payment_gateway = '';
2991 my( $processor, $login, $password, $action, @bop_options );
2992 if ( $override ) { #use a payment gateway override
2994 $payment_gateway = $override->payment_gateway;
2996 $processor = $payment_gateway->gateway_module;
2997 $login = $payment_gateway->gateway_username;
2998 $password = $payment_gateway->gateway_password;
2999 $action = $payment_gateway->gateway_action;
3000 @bop_options = $payment_gateway->options;
3002 } else { #use the standard settings from the config
3004 ( $processor, $login, $password, $action, @bop_options ) =
3005 $self->default_payment_gateway($method);
3013 my $address = exists($options{'address1'})
3014 ? $options{'address1'}
3016 my $address2 = exists($options{'address2'})
3017 ? $options{'address2'}
3019 $address .= ", ". $address2 if length($address2);
3021 my $o_payname = exists($options{'payname'})
3022 ? $options{'payname'}
3024 my($payname, $payfirst, $paylast);
3025 if ( $o_payname && $method ne 'ECHECK' ) {
3026 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3027 or return "Illegal payname $payname";
3028 ($payfirst, $paylast) = ($1, $2);
3030 $payfirst = $self->getfield('first');
3031 $paylast = $self->getfield('last');
3032 $payname = "$payfirst $paylast";
3035 my @invoicing_list = $self->invoicing_list_emailonly;
3036 if ( $conf->exists('emailinvoiceautoalways')
3037 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3038 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3039 push @invoicing_list, $self->all_emails;
3042 my $email = ($conf->exists('business-onlinepayment-email-override'))
3043 ? $conf->config('business-onlinepayment-email-override')
3044 : $invoicing_list[0];
3048 my $payip = exists($options{'payip'})
3051 $content{customer_ip} = $payip
3054 $content{invoice_number} = $options{'invnum'}
3055 if exists($options{'invnum'}) && length($options{'invnum'});
3057 $content{email_customer} =
3058 ( $conf->exists('business-onlinepayment-email_customer')
3059 || $conf->exists('business-onlinepayment-email-override') );
3062 if ( $method eq 'CC' ) {
3064 $content{card_number} = $payinfo;
3065 $paydate = exists($options{'paydate'})
3066 ? $options{'paydate'}
3068 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3069 $content{expiration} = "$2/$1";
3071 my $paycvv = exists($options{'paycvv'})
3072 ? $options{'paycvv'}
3074 $content{cvv2} = $paycvv
3077 my $paystart_month = exists($options{'paystart_month'})
3078 ? $options{'paystart_month'}
3079 : $self->paystart_month;
3081 my $paystart_year = exists($options{'paystart_year'})
3082 ? $options{'paystart_year'}
3083 : $self->paystart_year;
3085 $content{card_start} = "$paystart_month/$paystart_year"
3086 if $paystart_month && $paystart_year;
3088 my $payissue = exists($options{'payissue'})
3089 ? $options{'payissue'}
3091 $content{issue_number} = $payissue if $payissue;
3093 $content{recurring_billing} = 'YES'
3094 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3096 'payinfo' => $payinfo,
3098 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3100 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3104 } elsif ( $method eq 'ECHECK' ) {
3105 ( $content{account_number}, $content{routing_code} ) =
3106 split('@', $payinfo);
3107 $content{bank_name} = $o_payname;
3108 $content{bank_state} = exists($options{'paystate'})
3109 ? $options{'paystate'}
3110 : $self->getfield('paystate');
3111 $content{account_type} = exists($options{'paytype'})
3112 ? uc($options{'paytype'}) || 'CHECKING'
3113 : uc($self->getfield('paytype')) || 'CHECKING';
3114 $content{account_name} = $payname;
3115 $content{customer_org} = $self->company ? 'B' : 'I';
3116 $content{state_id} = exists($options{'stateid'})
3117 ? $options{'stateid'}
3118 : $self->getfield('stateid');
3119 $content{state_id_state} = exists($options{'stateid_state'})
3120 ? $options{'stateid_state'}
3121 : $self->getfield('stateid_state');
3122 $content{customer_ssn} = exists($options{'ss'})
3125 } elsif ( $method eq 'LEC' ) {
3126 $content{phone} = $payinfo;
3130 # run transaction(s)
3133 my $balance = exists( $options{'balance'} )
3134 ? $options{'balance'}
3137 $self->select_for_update; #mutex ... just until we get our pending record in
3139 #the checks here are intended to catch concurrent payments
3140 #double-form-submission prevention is taken care of in cust_pay_pending::check
3143 return "The customer's balance has changed; $method transaction aborted."
3144 if $self->balance < $balance;
3145 #&& $self->balance < $amount; #might as well anyway?
3147 #also check and make sure there aren't *other* pending payments for this cust
3149 my @pending = qsearch('cust_pay_pending', {
3150 'custnum' => $self->custnum,
3151 'status' => { op=>'!=', value=>'done' }
3153 return "A payment is already being processed for this customer (".
3154 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3155 "); $method transaction aborted."
3156 if scalar(@pending);
3158 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3160 my $cust_pay_pending = new FS::cust_pay_pending {
3161 'custnum' => $self->custnum,
3162 #'invnum' => $options{'invnum'},
3165 'payby' => $method2payby{$method},
3166 'payinfo' => $payinfo,
3167 'paydate' => $paydate,
3169 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3171 $cust_pay_pending->payunique( $options{payunique} )
3172 if defined($options{payunique}) && length($options{payunique});
3173 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3174 return $cpp_new_err if $cpp_new_err;
3176 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3178 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3179 $transaction->content(
3182 'password' => $password,
3183 'action' => $action1,
3184 'description' => $options{'description'},
3185 'amount' => $amount,
3186 #'invoice_number' => $options{'invnum'},
3187 'customer_id' => $self->custnum,
3188 'last_name' => $paylast,
3189 'first_name' => $payfirst,
3191 'address' => $address,
3192 'city' => ( exists($options{'city'})
3195 'state' => ( exists($options{'state'})
3198 'zip' => ( exists($options{'zip'})
3201 'country' => ( exists($options{'country'})
3202 ? $options{'country'}
3204 'referer' => 'http://cleanwhisker.420.am/',
3206 'phone' => $self->daytime || $self->night,
3210 $cust_pay_pending->status('pending');
3211 my $cpp_pending_err = $cust_pay_pending->replace;
3212 return $cpp_pending_err if $cpp_pending_err;
3215 my $BOP_TESTING = 0;
3216 my $BOP_TESTING_SUCCESS = 1;
3218 unless ( $BOP_TESTING ) {
3219 $transaction->submit();
3221 if ( $BOP_TESTING_SUCCESS ) {
3222 $transaction->is_success(1);
3223 $transaction->authorization('fake auth');
3225 $transaction->is_success(0);
3226 $transaction->error_message('fake failure');
3230 if ( $transaction->is_success() && $action2 ) {
3232 $cust_pay_pending->status('authorized');
3233 my $cpp_authorized_err = $cust_pay_pending->replace;
3234 return $cpp_authorized_err if $cpp_authorized_err;
3236 my $auth = $transaction->authorization;
3237 my $ordernum = $transaction->can('order_number')
3238 ? $transaction->order_number
3242 new Business::OnlinePayment( $processor, @bop_options );
3249 password => $password,
3250 order_number => $ordernum,
3252 authorization => $auth,
3253 description => $options{'description'},
3256 foreach my $field (qw( authorization_source_code returned_ACI
3257 transaction_identifier validation_code
3258 transaction_sequence_num local_transaction_date
3259 local_transaction_time AVS_result_code )) {
3260 $capture{$field} = $transaction->$field() if $transaction->can($field);
3263 $capture->content( %capture );
3267 unless ( $capture->is_success ) {
3268 my $e = "Authorization successful but capture failed, custnum #".
3269 $self->custnum. ': '. $capture->result_code.
3270 ": ". $capture->error_message;
3277 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3278 my $cpp_captured_err = $cust_pay_pending->replace;
3279 return $cpp_captured_err if $cpp_captured_err;
3282 # remove paycvv after initial transaction
3285 #false laziness w/misc/process/payment.cgi - check both to make sure working
3287 if ( defined $self->dbdef_table->column('paycvv')
3288 && length($self->paycvv)
3289 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3291 my $error = $self->remove_cvv;
3293 warn "WARNING: error removing cvv: $error\n";
3301 if ( $transaction->is_success() ) {
3304 if ( $payment_gateway ) { # agent override
3305 $paybatch = $payment_gateway->gatewaynum. '-';
3308 $paybatch .= "$processor:". $transaction->authorization;
3310 $paybatch .= ':'. $transaction->order_number
3311 if $transaction->can('order_number')
3312 && length($transaction->order_number);
3314 my $cust_pay = new FS::cust_pay ( {
3315 'custnum' => $self->custnum,
3316 'invnum' => $options{'invnum'},
3319 'payby' => $method2payby{$method},
3320 'payinfo' => $payinfo,
3321 'paybatch' => $paybatch,
3322 'paydate' => $paydate,
3324 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3325 $cust_pay->payunique( $options{payunique} )
3326 if defined($options{payunique}) && length($options{payunique});
3328 my $oldAutoCommit = $FS::UID::AutoCommit;
3329 local $FS::UID::AutoCommit = 0;
3332 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3334 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3337 $cust_pay->invnum(''); #try again with no specific invnum
3338 my $error2 = $cust_pay->insert( $options{'manual'} ?
3339 ( 'manual' => 1 ) : ()
3342 # gah. but at least we have a record of the state we had to abort in
3343 # from cust_pay_pending now.
3344 my $e = "WARNING: $method captured but payment not recorded - ".
3345 "error inserting payment ($processor): $error2".
3346 " (previously tried insert with invnum #$options{'invnum'}" .
3347 ": $error ) - pending payment saved as paypendingnum ".
3348 $cust_pay_pending->paypendingnum. "\n";
3354 if ( $options{'paynum_ref'} ) {
3355 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3358 $cust_pay_pending->status('done');
3359 $cust_pay_pending->statustext('captured');
3360 my $cpp_done_err = $cust_pay_pending->replace;
3362 if ( $cpp_done_err ) {
3364 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3365 my $e = "WARNING: $method captured but payment not recorded - ".
3366 "error updating status for paypendingnum ".
3367 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3373 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3374 return ''; #no error
3380 my $perror = "$processor error: ". $transaction->error_message;
3382 unless ( $transaction->error_message ) {
3385 if ( $transaction->can('response_page') ) {
3387 'page' => ( $transaction->can('response_page')
3388 ? $transaction->response_page
3391 'code' => ( $transaction->can('response_code')
3392 ? $transaction->response_code
3395 'headers' => ( $transaction->can('response_headers')
3396 ? $transaction->response_headers
3402 "No additional debugging information available for $processor";
3405 $perror .= "No error_message returned from $processor -- ".
3406 ( ref($t_response) ? Dumper($t_response) : $t_response );
3410 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3411 && $conf->exists('emaildecline')
3412 && grep { $_ ne 'POST' } $self->invoicing_list
3413 && ! grep { $transaction->error_message =~ /$_/ }
3414 $conf->config('emaildecline-exclude')
3416 my @templ = $conf->config('declinetemplate');
3417 my $template = new Text::Template (
3419 SOURCE => [ map "$_\n", @templ ],
3420 ) or return "($perror) can't create template: $Text::Template::ERROR";
3421 $template->compile()
3422 or return "($perror) can't compile template: $Text::Template::ERROR";
3424 my $templ_hash = { error => $transaction->error_message };
3426 my $error = send_email(
3427 'from' => $conf->config('invoice_from'),
3428 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3429 'subject' => 'Your payment could not be processed',
3430 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3433 $perror .= " (also received error sending decline notification: $error)"
3438 $cust_pay_pending->status('done');
3439 $cust_pay_pending->statustext("declined: $perror");
3440 my $cpp_done_err = $cust_pay_pending->replace;
3441 if ( $cpp_done_err ) {
3442 my $e = "WARNING: $method declined but pending payment not resolved - ".
3443 "error updating status for paypendingnum ".
3444 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3446 $perror = "$e ($perror)";
3459 my( $self, $method, $amount, %options ) = @_;
3461 if ( $options{'fake_failure'} ) {
3462 return "Error: No error; test failure requested with fake_failure";
3465 my %method2payby = (
3472 #if ( $payment_gateway ) { # agent override
3473 # $paybatch = $payment_gateway->gatewaynum. '-';
3476 #$paybatch .= "$processor:". $transaction->authorization;
3478 #$paybatch .= ':'. $transaction->order_number
3479 # if $transaction->can('order_number')
3480 # && length($transaction->order_number);
3482 my $paybatch = 'FakeProcessor:54:32';
3484 my $cust_pay = new FS::cust_pay ( {
3485 'custnum' => $self->custnum,
3486 'invnum' => $options{'invnum'},
3489 'payby' => $method2payby{$method},
3490 #'payinfo' => $payinfo,
3491 'payinfo' => '4111111111111111',
3492 'paybatch' => $paybatch,
3493 #'paydate' => $paydate,
3494 'paydate' => '2012-05-01',
3496 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3498 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3501 $cust_pay->invnum(''); #try again with no specific invnum
3502 my $error2 = $cust_pay->insert( $options{'manual'} ?
3503 ( 'manual' => 1 ) : ()
3506 # gah, even with transactions.
3507 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3508 "error inserting (fake!) payment: $error2".
3509 " (previously tried insert with invnum #$options{'invnum'}" .
3516 if ( $options{'paynum_ref'} ) {
3517 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3520 return ''; #no error
3524 =item default_payment_gateway
3528 sub default_payment_gateway {
3529 my( $self, $method ) = @_;
3531 die "Real-time processing not enabled\n"
3532 unless $conf->exists('business-onlinepayment');
3535 my $bop_config = 'business-onlinepayment';
3536 $bop_config .= '-ach'
3537 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3538 my ( $processor, $login, $password, $action, @bop_options ) =
3539 $conf->config($bop_config);
3540 $action ||= 'normal authorization';
3541 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3542 die "No real-time processor is enabled - ".
3543 "did you set the business-onlinepayment configuration value?\n"
3546 ( $processor, $login, $password, $action, @bop_options )
3551 Removes the I<paycvv> field from the database directly.
3553 If there is an error, returns the error, otherwise returns false.
3559 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3560 or return dbh->errstr;
3561 $sth->execute($self->custnum)
3562 or return $sth->errstr;
3567 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3569 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3570 via a Business::OnlinePayment realtime gateway. See
3571 L<http://420.am/business-onlinepayment> for supported gateways.
3573 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3575 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3577 Most gateways require a reference to an original payment transaction to refund,
3578 so you probably need to specify a I<paynum>.
3580 I<amount> defaults to the original amount of the payment if not specified.
3582 I<reason> specifies a reason for the refund.
3584 I<paydate> specifies the expiration date for a credit card overriding the
3585 value from the customer record or the payment record. Specified as yyyy-mm-dd
3587 Implementation note: If I<amount> is unspecified or equal to the amount of the
3588 orignal payment, first an attempt is made to "void" the transaction via
3589 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3590 the normal attempt is made to "refund" ("credit") the transaction via the
3591 gateway is attempted.
3593 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3594 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3595 #if set, will override the value from the customer record.
3597 #If an I<invnum> is specified, this payment (if successful) is applied to the
3598 #specified invoice. If you don't specify an I<invnum> you might want to
3599 #call the B<apply_payments> method.
3603 #some false laziness w/realtime_bop, not enough to make it worth merging
3604 #but some useful small subs should be pulled out
3605 sub realtime_refund_bop {
3606 my( $self, $method, %options ) = @_;
3608 warn "$me realtime_refund_bop: $method refund\n";
3609 warn " $_ => $options{$_}\n" foreach keys %options;
3612 eval "use Business::OnlinePayment";
3616 # look up the original payment and optionally a gateway for that payment
3620 my $amount = $options{'amount'};
3622 my( $processor, $login, $password, @bop_options ) ;
3623 my( $auth, $order_number ) = ( '', '', '' );
3625 if ( $options{'paynum'} ) {
3627 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3628 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3629 or return "Unknown paynum $options{'paynum'}";
3630 $amount ||= $cust_pay->paid;
3632 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3633 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3634 $cust_pay->paybatch;
3635 my $gatewaynum = '';
3636 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3638 if ( $gatewaynum ) { #gateway for the payment to be refunded
3640 my $payment_gateway =
3641 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3642 die "payment gateway $gatewaynum not found"
3643 unless $payment_gateway;
3645 $processor = $payment_gateway->gateway_module;
3646 $login = $payment_gateway->gateway_username;
3647 $password = $payment_gateway->gateway_password;
3648 @bop_options = $payment_gateway->options;
3650 } else { #try the default gateway
3652 my( $conf_processor, $unused_action );
3653 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3654 $self->default_payment_gateway($method);
3656 return "processor of payment $options{'paynum'} $processor does not".
3657 " match default processor $conf_processor"
3658 unless $processor eq $conf_processor;
3663 } else { # didn't specify a paynum, so look for agent gateway overrides
3664 # like a normal transaction
3667 if ( $method eq 'CC' ) {
3668 $cardtype = cardtype($self->payinfo);
3669 } elsif ( $method eq 'ECHECK' ) {
3672 $cardtype = $method;
3675 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3676 cardtype => $cardtype,
3678 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3680 taxclass => '', } );
3682 if ( $override ) { #use a payment gateway override
3684 my $payment_gateway = $override->payment_gateway;
3686 $processor = $payment_gateway->gateway_module;
3687 $login = $payment_gateway->gateway_username;
3688 $password = $payment_gateway->gateway_password;
3689 #$action = $payment_gateway->gateway_action;
3690 @bop_options = $payment_gateway->options;
3692 } else { #use the standard settings from the config
3695 ( $processor, $login, $password, $unused_action, @bop_options ) =
3696 $self->default_payment_gateway($method);
3701 return "neither amount nor paynum specified" unless $amount;
3706 'password' => $password,
3707 'order_number' => $order_number,
3708 'amount' => $amount,
3709 'referer' => 'http://cleanwhisker.420.am/',
3711 $content{authorization} = $auth
3712 if length($auth); #echeck/ACH transactions have an order # but no auth
3713 #(at least with authorize.net)
3715 my $disable_void_after;
3716 if ($conf->exists('disable_void_after')
3717 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3718 $disable_void_after = $1;
3721 #first try void if applicable
3722 if ( $cust_pay && $cust_pay->paid == $amount
3724 ( not defined($disable_void_after) )
3725 || ( time < ($cust_pay->_date + $disable_void_after ) )
3728 warn " attempting void\n" if $DEBUG > 1;
3729 my $void = new Business::OnlinePayment( $processor, @bop_options );
3730 $void->content( 'action' => 'void', %content );
3732 if ( $void->is_success ) {
3733 my $error = $cust_pay->void($options{'reason'});
3735 # gah, even with transactions.
3736 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3737 "error voiding payment: $error";
3741 warn " void successful\n" if $DEBUG > 1;
3746 warn " void unsuccessful, trying refund\n"
3750 my $address = $self->address1;
3751 $address .= ", ". $self->address2 if $self->address2;
3753 my($payname, $payfirst, $paylast);
3754 if ( $self->payname && $method ne 'ECHECK' ) {
3755 $payname = $self->payname;
3756 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3757 or return "Illegal payname $payname";
3758 ($payfirst, $paylast) = ($1, $2);
3760 $payfirst = $self->getfield('first');
3761 $paylast = $self->getfield('last');
3762 $payname = "$payfirst $paylast";
3765 my @invoicing_list = $self->invoicing_list_emailonly;
3766 if ( $conf->exists('emailinvoiceautoalways')
3767 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3768 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3769 push @invoicing_list, $self->all_emails;
3772 my $email = ($conf->exists('business-onlinepayment-email-override'))
3773 ? $conf->config('business-onlinepayment-email-override')
3774 : $invoicing_list[0];
3776 my $payip = exists($options{'payip'})
3779 $content{customer_ip} = $payip
3783 if ( $method eq 'CC' ) {
3786 $content{card_number} = $payinfo = $cust_pay->payinfo;
3787 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3788 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3789 ($content{expiration} = "$2/$1"); # where available
3791 $content{card_number} = $payinfo = $self->payinfo;
3792 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3793 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3794 $content{expiration} = "$2/$1";
3797 } elsif ( $method eq 'ECHECK' ) {
3800 $payinfo = $cust_pay->payinfo;
3802 $payinfo = $self->payinfo;
3804 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3805 $content{bank_name} = $self->payname;
3806 $content{account_type} = 'CHECKING';
3807 $content{account_name} = $payname;
3808 $content{customer_org} = $self->company ? 'B' : 'I';
3809 $content{customer_ssn} = $self->ss;
3810 } elsif ( $method eq 'LEC' ) {
3811 $content{phone} = $payinfo = $self->payinfo;
3815 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3816 my %sub_content = $refund->content(
3817 'action' => 'credit',
3818 'customer_id' => $self->custnum,
3819 'last_name' => $paylast,
3820 'first_name' => $payfirst,
3822 'address' => $address,
3823 'city' => $self->city,
3824 'state' => $self->state,
3825 'zip' => $self->zip,
3826 'country' => $self->country,
3828 'phone' => $self->daytime || $self->night,
3831 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3835 return "$processor error: ". $refund->error_message
3836 unless $refund->is_success();
3838 my %method2payby = (
3844 my $paybatch = "$processor:". $refund->authorization;
3845 $paybatch .= ':'. $refund->order_number
3846 if $refund->can('order_number') && $refund->order_number;
3848 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3849 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3850 last unless @cust_bill_pay;
3851 my $cust_bill_pay = pop @cust_bill_pay;
3852 my $error = $cust_bill_pay->delete;
3856 my $cust_refund = new FS::cust_refund ( {
3857 'custnum' => $self->custnum,
3858 'paynum' => $options{'paynum'},
3859 'refund' => $amount,
3861 'payby' => $method2payby{$method},
3862 'payinfo' => $payinfo,
3863 'paybatch' => $paybatch,
3864 'reason' => $options{'reason'} || 'card or ACH refund',
3866 my $error = $cust_refund->insert;
3868 $cust_refund->paynum(''); #try again with no specific paynum
3869 my $error2 = $cust_refund->insert;
3871 # gah, even with transactions.
3872 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3873 "error inserting refund ($processor): $error2".
3874 " (previously tried insert with paynum #$options{'paynum'}" .
3885 =item batch_card OPTION => VALUE...
3887 Adds a payment for this invoice to the pending credit card batch (see
3888 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3889 runs the payment using a realtime gateway.
3894 my ($self, %options) = @_;
3897 if (exists($options{amount})) {
3898 $amount = $options{amount};
3900 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3902 return '' unless $amount > 0;
3904 my $invnum = delete $options{invnum};
3905 my $payby = $options{invnum} || $self->payby; #dubious
3907 if ($options{'realtime'}) {
3908 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3914 my $oldAutoCommit = $FS::UID::AutoCommit;
3915 local $FS::UID::AutoCommit = 0;
3918 #this needs to handle mysql as well as Pg, like svc_acct.pm
3919 #(make it into a common function if folks need to do batching with mysql)
3920 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3921 or return "Cannot lock pay_batch: " . $dbh->errstr;
3925 'payby' => FS::payby->payby2payment($payby),
3928 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3930 unless ( $pay_batch ) {
3931 $pay_batch = new FS::pay_batch \%pay_batch;
3932 my $error = $pay_batch->insert;
3934 $dbh->rollback if $oldAutoCommit;
3935 die "error creating new batch: $error\n";
3939 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3940 'batchnum' => $pay_batch->batchnum,
3941 'custnum' => $self->custnum,
3944 foreach (qw( address1 address2 city state zip country payby payinfo paydate
3946 $options{$_} = '' unless exists($options{$_});
3949 my $cust_pay_batch = new FS::cust_pay_batch ( {
3950 'batchnum' => $pay_batch->batchnum,
3951 'invnum' => $invnum || 0, # is there a better value?
3952 # this field should be
3954 # cust_bill_pay_batch now
3955 'custnum' => $self->custnum,
3956 'last' => $self->getfield('last'),
3957 'first' => $self->getfield('first'),
3958 'address1' => $options{address1} || $self->address1,
3959 'address2' => $options{address2} || $self->address2,
3960 'city' => $options{city} || $self->city,
3961 'state' => $options{state} || $self->state,
3962 'zip' => $options{zip} || $self->zip,
3963 'country' => $options{country} || $self->country,
3964 'payby' => $options{payby} || $self->payby,
3965 'payinfo' => $options{payinfo} || $self->payinfo,
3966 'exp' => $options{paydate} || $self->paydate,
3967 'payname' => $options{payname} || $self->payname,
3968 'amount' => $amount, # consolidating
3971 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3972 if $old_cust_pay_batch;
3975 if ($old_cust_pay_batch) {
3976 $error = $cust_pay_batch->replace($old_cust_pay_batch)
3978 $error = $cust_pay_batch->insert;
3982 $dbh->rollback if $oldAutoCommit;
3986 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
3987 foreach my $cust_bill ($self->open_cust_bill) {
3988 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3989 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3990 'invnum' => $cust_bill->invnum,
3991 'paybatchnum' => $cust_pay_batch->paybatchnum,
3992 'amount' => $cust_bill->owed,
3995 if ($unapplied >= $cust_bill_pay_batch->amount){
3996 $unapplied -= $cust_bill_pay_batch->amount;
3999 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4000 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4002 $error = $cust_bill_pay_batch->insert;
4004 $dbh->rollback if $oldAutoCommit;
4009 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4015 Returns the total owed for this customer on all invoices
4016 (see L<FS::cust_bill/owed>).
4022 $self->total_owed_date(2145859200); #12/31/2037
4025 =item total_owed_date TIME
4027 Returns the total owed for this customer on all invoices with date earlier than
4028 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4029 see L<Time::Local> and L<Date::Parse> for conversion functions.
4033 sub total_owed_date {
4037 foreach my $cust_bill (
4038 grep { $_->_date <= $time }
4039 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4041 $total_bill += $cust_bill->owed;
4043 sprintf( "%.2f", $total_bill );
4046 =item apply_payments_and_credits
4048 Applies unapplied payments and credits.
4050 In most cases, this new method should be used in place of sequential
4051 apply_payments and apply_credits methods.
4053 If there is an error, returns the error, otherwise returns false.
4057 sub apply_payments_and_credits {
4060 local $SIG{HUP} = 'IGNORE';
4061 local $SIG{INT} = 'IGNORE';
4062 local $SIG{QUIT} = 'IGNORE';
4063 local $SIG{TERM} = 'IGNORE';
4064 local $SIG{TSTP} = 'IGNORE';
4065 local $SIG{PIPE} = 'IGNORE';
4067 my $oldAutoCommit = $FS::UID::AutoCommit;
4068 local $FS::UID::AutoCommit = 0;
4071 $self->select_for_update; #mutex
4073 foreach my $cust_bill ( $self->open_cust_bill ) {
4074 my $error = $cust_bill->apply_payments_and_credits;
4076 $dbh->rollback if $oldAutoCommit;
4077 return "Error applying: $error";
4081 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4086 =item apply_credits OPTION => VALUE ...
4088 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4089 to outstanding invoice balances in chronological order (or reverse
4090 chronological order if the I<order> option is set to B<newest>) and returns the
4091 value of any remaining unapplied credits available for refund (see
4092 L<FS::cust_refund>).
4094 Dies if there is an error.
4102 local $SIG{HUP} = 'IGNORE';
4103 local $SIG{INT} = 'IGNORE';
4104 local $SIG{QUIT} = 'IGNORE';
4105 local $SIG{TERM} = 'IGNORE';
4106 local $SIG{TSTP} = 'IGNORE';
4107 local $SIG{PIPE} = 'IGNORE';
4109 my $oldAutoCommit = $FS::UID::AutoCommit;
4110 local $FS::UID::AutoCommit = 0;
4113 $self->select_for_update; #mutex
4115 unless ( $self->total_credited ) {
4116 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4120 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4121 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4123 my @invoices = $self->open_cust_bill;
4124 @invoices = sort { $b->_date <=> $a->_date } @invoices
4125 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4128 foreach my $cust_bill ( @invoices ) {
4131 if ( !defined($credit) || $credit->credited == 0) {
4132 $credit = pop @credits or last;
4135 if ($cust_bill->owed >= $credit->credited) {
4136 $amount=$credit->credited;
4138 $amount=$cust_bill->owed;
4141 my $cust_credit_bill = new FS::cust_credit_bill ( {
4142 'crednum' => $credit->crednum,
4143 'invnum' => $cust_bill->invnum,
4144 'amount' => $amount,
4146 my $error = $cust_credit_bill->insert;
4148 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4152 redo if ($cust_bill->owed > 0);
4156 my $total_credited = $self->total_credited;
4158 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4160 return $total_credited;
4163 =item apply_payments
4165 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4166 to outstanding invoice balances in chronological order.
4168 #and returns the value of any remaining unapplied payments.
4170 Dies if there is an error.
4174 sub apply_payments {
4177 local $SIG{HUP} = 'IGNORE';
4178 local $SIG{INT} = 'IGNORE';
4179 local $SIG{QUIT} = 'IGNORE';
4180 local $SIG{TERM} = 'IGNORE';
4181 local $SIG{TSTP} = 'IGNORE';
4182 local $SIG{PIPE} = 'IGNORE';
4184 my $oldAutoCommit = $FS::UID::AutoCommit;
4185 local $FS::UID::AutoCommit = 0;
4188 $self->select_for_update; #mutex
4192 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4193 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4195 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4196 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4200 foreach my $cust_bill ( @invoices ) {
4203 if ( !defined($payment) || $payment->unapplied == 0 ) {
4204 $payment = pop @payments or last;
4207 if ( $cust_bill->owed >= $payment->unapplied ) {
4208 $amount = $payment->unapplied;
4210 $amount = $cust_bill->owed;
4213 my $cust_bill_pay = new FS::cust_bill_pay ( {
4214 'paynum' => $payment->paynum,
4215 'invnum' => $cust_bill->invnum,
4216 'amount' => $amount,
4218 my $error = $cust_bill_pay->insert;
4220 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4224 redo if ( $cust_bill->owed > 0);
4228 my $total_unapplied_payments = $self->total_unapplied_payments;
4230 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4232 return $total_unapplied_payments;
4235 =item total_credited
4237 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4238 customer. See L<FS::cust_credit/credited>.
4242 sub total_credited {
4244 my $total_credit = 0;
4245 foreach my $cust_credit ( qsearch('cust_credit', {
4246 'custnum' => $self->custnum,
4248 $total_credit += $cust_credit->credited;
4250 sprintf( "%.2f", $total_credit );
4253 =item total_unapplied_payments
4255 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4256 See L<FS::cust_pay/unapplied>.
4260 sub total_unapplied_payments {
4262 my $total_unapplied = 0;
4263 foreach my $cust_pay ( qsearch('cust_pay', {
4264 'custnum' => $self->custnum,
4266 $total_unapplied += $cust_pay->unapplied;
4268 sprintf( "%.2f", $total_unapplied );
4271 =item total_unapplied_refunds
4273 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4274 customer. See L<FS::cust_refund/unapplied>.
4278 sub total_unapplied_refunds {
4280 my $total_unapplied = 0;
4281 foreach my $cust_refund ( qsearch('cust_refund', {
4282 'custnum' => $self->custnum,
4284 $total_unapplied += $cust_refund->unapplied;
4286 sprintf( "%.2f", $total_unapplied );
4291 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4292 total_credited minus total_unapplied_payments).
4300 + $self->total_unapplied_refunds
4301 - $self->total_credited
4302 - $self->total_unapplied_payments
4306 =item balance_date TIME
4308 Returns the balance for this customer, only considering invoices with date
4309 earlier than TIME (total_owed_date minus total_credited minus
4310 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4311 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4320 $self->total_owed_date($time)
4321 + $self->total_unapplied_refunds
4322 - $self->total_credited
4323 - $self->total_unapplied_payments
4327 =item in_transit_payments
4329 Returns the total of requests for payments for this customer pending in
4330 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4334 sub in_transit_payments {
4336 my $in_transit_payments = 0;
4337 foreach my $pay_batch ( qsearch('pay_batch', {
4340 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4341 'batchnum' => $pay_batch->batchnum,
4342 'custnum' => $self->custnum,
4344 $in_transit_payments += $cust_pay_batch->amount;
4347 sprintf( "%.2f", $in_transit_payments );
4350 =item paydate_monthyear
4352 Returns a two-element list consisting of the month and year of this customer's
4353 paydate (credit card expiration date for CARD customers)
4357 sub paydate_monthyear {
4359 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4361 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4368 =item invoicing_list [ ARRAYREF ]
4370 If an arguement is given, sets these email addresses as invoice recipients
4371 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4372 (except as warnings), so use check_invoicing_list first.
4374 Returns a list of email addresses (with svcnum entries expanded).
4376 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4377 check it without disturbing anything by passing nothing.
4379 This interface may change in the future.
4383 sub invoicing_list {
4384 my( $self, $arrayref ) = @_;
4387 my @cust_main_invoice;
4388 if ( $self->custnum ) {
4389 @cust_main_invoice =
4390 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4392 @cust_main_invoice = ();
4394 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4395 #warn $cust_main_invoice->destnum;
4396 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4397 #warn $cust_main_invoice->destnum;
4398 my $error = $cust_main_invoice->delete;
4399 warn $error if $error;
4402 if ( $self->custnum ) {
4403 @cust_main_invoice =
4404 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4406 @cust_main_invoice = ();
4408 my %seen = map { $_->address => 1 } @cust_main_invoice;
4409 foreach my $address ( @{$arrayref} ) {
4410 next if exists $seen{$address} && $seen{$address};
4411 $seen{$address} = 1;
4412 my $cust_main_invoice = new FS::cust_main_invoice ( {
4413 'custnum' => $self->custnum,
4416 my $error = $cust_main_invoice->insert;
4417 warn $error if $error;
4421 if ( $self->custnum ) {
4423 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4430 =item check_invoicing_list ARRAYREF
4432 Checks these arguements as valid input for the invoicing_list method. If there
4433 is an error, returns the error, otherwise returns false.
4437 sub check_invoicing_list {
4438 my( $self, $arrayref ) = @_;
4440 foreach my $address ( @$arrayref ) {
4442 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4443 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4446 my $cust_main_invoice = new FS::cust_main_invoice ( {
4447 'custnum' => $self->custnum,
4450 my $error = $self->custnum
4451 ? $cust_main_invoice->check
4452 : $cust_main_invoice->checkdest
4454 return $error if $error;
4458 return "Email address required"
4459 if $conf->exists('cust_main-require_invoicing_list_email')
4460 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4465 =item set_default_invoicing_list
4467 Sets the invoicing list to all accounts associated with this customer,
4468 overwriting any previous invoicing list.
4472 sub set_default_invoicing_list {
4474 $self->invoicing_list($self->all_emails);
4479 Returns the email addresses of all accounts provisioned for this customer.
4486 foreach my $cust_pkg ( $self->all_pkgs ) {
4487 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4489 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4490 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4492 $list{$_}=1 foreach map { $_->email } @svc_acct;
4497 =item invoicing_list_addpost
4499 Adds postal invoicing to this customer. If this customer is already configured
4500 to receive postal invoices, does nothing.
4504 sub invoicing_list_addpost {
4506 return if grep { $_ eq 'POST' } $self->invoicing_list;
4507 my @invoicing_list = $self->invoicing_list;
4508 push @invoicing_list, 'POST';
4509 $self->invoicing_list(\@invoicing_list);
4512 =item invoicing_list_emailonly
4514 Returns the list of email invoice recipients (invoicing_list without non-email
4515 destinations such as POST and FAX).
4519 sub invoicing_list_emailonly {
4521 warn "$me invoicing_list_emailonly called"
4523 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4526 =item invoicing_list_emailonly_scalar
4528 Returns the list of email invoice recipients (invoicing_list without non-email
4529 destinations such as POST and FAX) as a comma-separated scalar.
4533 sub invoicing_list_emailonly_scalar {
4535 warn "$me invoicing_list_emailonly_scalar called"
4537 join(', ', $self->invoicing_list_emailonly);
4540 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4542 Returns an array of customers referred by this customer (referral_custnum set
4543 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4544 customers referred by customers referred by this customer and so on, inclusive.
4545 The default behavior is DEPTH 1 (no recursion).
4549 sub referral_cust_main {
4551 my $depth = @_ ? shift : 1;
4552 my $exclude = @_ ? shift : {};
4555 map { $exclude->{$_->custnum}++; $_; }
4556 grep { ! $exclude->{ $_->custnum } }
4557 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4561 map { $_->referral_cust_main($depth-1, $exclude) }
4568 =item referral_cust_main_ncancelled
4570 Same as referral_cust_main, except only returns customers with uncancelled
4575 sub referral_cust_main_ncancelled {
4577 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4580 =item referral_cust_pkg [ DEPTH ]
4582 Like referral_cust_main, except returns a flat list of all unsuspended (and
4583 uncancelled) packages for each customer. The number of items in this list may
4584 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4588 sub referral_cust_pkg {
4590 my $depth = @_ ? shift : 1;
4592 map { $_->unsuspended_pkgs }
4593 grep { $_->unsuspended_pkgs }
4594 $self->referral_cust_main($depth);
4597 =item referring_cust_main
4599 Returns the single cust_main record for the customer who referred this customer
4600 (referral_custnum), or false.
4604 sub referring_cust_main {
4606 return '' unless $self->referral_custnum;
4607 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4610 =item credit AMOUNT, REASON
4612 Applies a credit to this customer. If there is an error, returns the error,
4613 otherwise returns false.
4618 my( $self, $amount, $reason, %options ) = @_;
4619 my $cust_credit = new FS::cust_credit {
4620 'custnum' => $self->custnum,
4621 'amount' => $amount,
4622 'reason' => $reason,
4624 $cust_credit->insert(%options);
4627 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4629 Creates a one-time charge for this customer. If there is an error, returns
4630 the error, otherwise returns false.
4636 my ( $amount, $pkg, $comment, $taxclass, $additional, $classnum );
4637 if ( ref( $_[0] ) ) {
4638 $amount = $_[0]->{amount};
4639 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4640 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4641 : '$'. sprintf("%.2f",$amount);
4642 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4643 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4644 $additional = $_[0]->{additional};
4647 $pkg = @_ ? shift : 'One-time charge';
4648 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4649 $taxclass = @_ ? shift : '';
4653 local $SIG{HUP} = 'IGNORE';
4654 local $SIG{INT} = 'IGNORE';
4655 local $SIG{QUIT} = 'IGNORE';
4656 local $SIG{TERM} = 'IGNORE';
4657 local $SIG{TSTP} = 'IGNORE';
4658 local $SIG{PIPE} = 'IGNORE';
4660 my $oldAutoCommit = $FS::UID::AutoCommit;
4661 local $FS::UID::AutoCommit = 0;
4664 my $part_pkg = new FS::part_pkg ( {
4666 'comment' => $comment,
4670 'classnum' => $classnum ? $classnum : '',
4671 'taxclass' => $taxclass,
4674 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4675 ( 0 .. @$additional - 1 )
4677 'additional_count' => scalar(@$additional),
4678 'setup_fee' => $amount,
4681 my $error = $part_pkg->insert( options => \%options );
4683 $dbh->rollback if $oldAutoCommit;
4687 my $pkgpart = $part_pkg->pkgpart;
4688 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4689 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4690 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4691 $error = $type_pkgs->insert;
4693 $dbh->rollback if $oldAutoCommit;
4698 my $cust_pkg = new FS::cust_pkg ( {
4699 'custnum' => $self->custnum,
4700 'pkgpart' => $pkgpart,
4703 $error = $cust_pkg->insert;
4705 $dbh->rollback if $oldAutoCommit;
4709 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4716 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4722 sort { $a->_date <=> $b->_date }
4723 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4726 =item open_cust_bill
4728 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4733 sub open_cust_bill {
4735 grep { $_->owed > 0 } $self->cust_bill;
4740 Returns all the credits (see L<FS::cust_credit>) for this customer.
4746 sort { $a->_date <=> $b->_date }
4747 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4752 Returns all the payments (see L<FS::cust_pay>) for this customer.
4758 sort { $a->_date <=> $b->_date }
4759 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4764 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4770 sort { $a->_date <=> $b->_date }
4771 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4774 =item cust_pay_batch
4776 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
4780 sub cust_pay_batch {
4782 sort { $a->_date <=> $b->_date }
4783 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
4788 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4794 sort { $a->_date <=> $b->_date }
4795 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4800 Returns a name string for this customer, either "Company (Last, First)" or
4807 my $name = $self->contact;
4808 $name = $self->company. " ($name)" if $self->company;
4814 Returns a name string for this (service/shipping) contact, either
4815 "Company (Last, First)" or "Last, First".
4821 if ( $self->get('ship_last') ) {
4822 my $name = $self->ship_contact;
4823 $name = $self->ship_company. " ($name)" if $self->ship_company;
4832 Returns this customer's full (billing) contact name only, "Last, First"
4838 $self->get('last'). ', '. $self->first;
4843 Returns this customer's full (shipping) contact name only, "Last, First"
4849 $self->get('ship_last')
4850 ? $self->get('ship_last'). ', '. $self->ship_first
4856 Returns this customer's full country name
4862 code2country($self->country);
4869 Returns a status string for this customer, currently:
4873 =item prospect - No packages have ever been ordered
4875 =item active - One or more recurring packages is active
4877 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4879 =item suspended - All non-cancelled recurring packages are suspended
4881 =item cancelled - All recurring packages are cancelled
4887 sub status { shift->cust_status(@_); }
4891 for my $status (qw( prospect active inactive suspended cancelled )) {
4892 my $method = $status.'_sql';
4893 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4894 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4895 $sth->execute( ($self->custnum) x $numnum )
4896 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4897 return $status if $sth->fetchrow_arrayref->[0];
4901 =item ucfirst_cust_status
4903 =item ucfirst_status
4905 Returns the status with the first character capitalized.
4909 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4911 sub ucfirst_cust_status {
4913 ucfirst($self->cust_status);
4918 Returns a hex triplet color string for this customer's status.
4922 use vars qw(%statuscolor);
4923 tie my %statuscolor, 'Tie::IxHash',
4924 'prospect' => '7e0079', #'000000', #black? naw, purple
4925 'active' => '00CC00', #green
4926 'inactive' => '0000CC', #blue
4927 'suspended' => 'FF9900', #yellow
4928 'cancelled' => 'FF0000', #red
4931 sub statuscolor { shift->cust_statuscolor(@_); }
4933 sub cust_statuscolor {
4935 $statuscolor{$self->cust_status};
4940 Returns an array of hashes representing the customer's RT tickets.
4947 my $num = $conf->config('cust_main-max_tickets') || 10;
4950 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4952 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4956 foreach my $priority (
4957 $conf->config('ticket_system-custom_priority_field-values'), ''
4959 last if scalar(@tickets) >= $num;
4961 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4962 $num - scalar(@tickets),
4971 # Return services representing svc_accts in customer support packages
4972 sub support_services {
4974 my %packages = map { $_ => 1 } $conf->config('support_packages');
4976 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4977 grep { $_->part_svc->svcdb eq 'svc_acct' }
4978 map { $_->cust_svc }
4979 grep { exists $packages{ $_->pkgpart } }
4980 $self->ncancelled_pkgs;
4986 =head1 CLASS METHODS
4992 Class method that returns the list of possible status strings for customers
4993 (see L<the status method|/status>). For example:
4995 @statuses = FS::cust_main->statuses();
5000 #my $self = shift; #could be class...
5006 Returns an SQL expression identifying prospective cust_main records (customers
5007 with no packages ever ordered)
5011 use vars qw($select_count_pkgs);
5012 $select_count_pkgs =
5013 "SELECT COUNT(*) FROM cust_pkg
5014 WHERE cust_pkg.custnum = cust_main.custnum";
5016 sub select_count_pkgs_sql {
5020 sub prospect_sql { "
5021 0 = ( $select_count_pkgs )
5026 Returns an SQL expression identifying active cust_main records (customers with
5027 no active recurring packages, but otherwise unsuspended/uncancelled).
5032 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5038 Returns an SQL expression identifying inactive cust_main records (customers with
5039 active recurring packages).
5043 sub inactive_sql { "
5044 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5046 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5052 Returns an SQL expression identifying suspended cust_main records.
5057 sub suspended_sql { susp_sql(@_); }
5059 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5061 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5067 Returns an SQL expression identifying cancelled cust_main records.
5071 sub cancelled_sql { cancel_sql(@_); }
5074 my $recurring_sql = FS::cust_pkg->recurring_sql;
5075 #my $recurring_sql = "
5076 # '0' != ( select freq from part_pkg
5077 # where cust_pkg.pkgpart = part_pkg.pkgpart )
5081 0 < ( $select_count_pkgs )
5082 AND 0 = ( $select_count_pkgs AND $recurring_sql
5083 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5089 =item uncancelled_sql
5091 Returns an SQL expression identifying un-cancelled cust_main records.
5095 sub uncancelled_sql { uncancel_sql(@_); }
5096 sub uncancel_sql { "
5097 ( 0 < ( $select_count_pkgs
5098 AND ( cust_pkg.cancel IS NULL
5099 OR cust_pkg.cancel = 0
5102 OR 0 = ( $select_count_pkgs )
5108 Returns an SQL fragment to retreive the balance.
5113 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5114 WHERE cust_bill.custnum = cust_main.custnum )
5115 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5116 WHERE cust_pay.custnum = cust_main.custnum )
5117 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5118 WHERE cust_credit.custnum = cust_main.custnum )
5119 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5120 WHERE cust_refund.custnum = cust_main.custnum )
5123 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5125 Returns an SQL fragment to retreive the balance for this customer, only
5126 considering invoices with date earlier than START_TIME, and optionally not
5127 later than END_TIME (total_owed_date minus total_credited minus
5128 total_unapplied_payments).
5130 Times are specified as SQL fragments or numeric
5131 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5132 L<Date::Parse> for conversion functions. The empty string can be passed
5133 to disable that time constraint completely.
5135 Available options are:
5139 =item unapplied_date - 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)
5141 =item total - set to true to remove all customer comparison clauses, for totals
5143 =item where - WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5145 =item join - JOIN clause (typically used with the total option)
5153 sub balance_date_sql {
5154 my( $class, $start, $end, %opt ) = @_;
5156 my $owed = FS::cust_bill->owed_sql;
5157 my $unapp_refund = FS::cust_refund->unapplied_sql;
5158 my $unapp_credit = FS::cust_credit->unapplied_sql;
5159 my $unapp_pay = FS::cust_pay->unapplied_sql;
5161 my $j = $opt{'join'} || '';
5163 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5164 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5165 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5166 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5168 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5169 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5170 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5171 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5176 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5178 Helper method for balance_date_sql; name (and usage) subject to change
5179 (suggestions welcome).
5181 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5182 cust_refund, cust_credit or cust_pay).
5184 If TABLE is "cust_bill" or the unapplied_date option is true, only
5185 considers records with date earlier than START_TIME, and optionally not
5186 later than END_TIME .
5190 sub _money_table_where {
5191 my( $class, $table, $start, $end, %opt ) = @_;
5194 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5195 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5196 push @where, "$table._date <= $start" if defined($start) && length($start);
5197 push @where, "$table._date > $end" if defined($end) && length($end);
5199 push @where, @{$opt{'where'}} if $opt{'where'};
5200 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5206 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5208 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5209 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5210 appropriate ship_ field is also searched).
5212 Additional options are the same as FS::Record::qsearch
5217 my( $self, $fuzzy, $hash, @opt) = @_;
5222 check_and_rebuild_fuzzyfiles();
5223 foreach my $field ( keys %$fuzzy ) {
5225 my $all = $self->all_X($field);
5226 next unless scalar(@$all);
5229 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5232 foreach ( keys %match ) {
5233 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5234 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5237 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5240 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5242 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5250 Returns a masked version of the named field
5255 my ($self,$field) = @_;
5259 'x'x(length($self->getfield($field))-4).
5260 substr($self->getfield($field), (length($self->getfield($field))-4));
5270 =item smart_search OPTION => VALUE ...
5272 Accepts the following options: I<search>, the string to search for. The string
5273 will be searched for as a customer number, phone number, name or company name,
5274 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5275 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5276 skip fuzzy matching when an exact match is found.
5278 Any additional options are treated as an additional qualifier on the search
5281 Returns a (possibly empty) array of FS::cust_main objects.
5288 #here is the agent virtualization
5289 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5293 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5294 my $search = delete $options{'search'};
5295 ( my $alphanum_search = $search ) =~ s/\W//g;
5297 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5299 #false laziness w/Record::ut_phone
5300 my $phonen = "$1-$2-$3";
5301 $phonen .= " x$4" if $4;
5303 push @cust_main, qsearch( {
5304 'table' => 'cust_main',
5305 'hashref' => { %options },
5306 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5308 join(' OR ', map "$_ = '$phonen'",
5309 qw( daytime night fax
5310 ship_daytime ship_night ship_fax )
5313 " AND $agentnums_sql", #agent virtualization
5316 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5317 #try looking for matches with extensions unless one was specified
5319 push @cust_main, qsearch( {
5320 'table' => 'cust_main',
5321 'hashref' => { %options },
5322 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5324 join(' OR ', map "$_ LIKE '$phonen\%'",
5326 ship_daytime ship_night )
5329 " AND $agentnums_sql", #agent virtualization
5334 # custnum search (also try agent_custid), with some tweaking options if your
5335 # legacy cust "numbers" have letters
5336 } elsif ( $search =~ /^\s*(\d+)\s*$/
5337 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5338 && $search =~ /^\s*(\w\w?\d+)\s*$/
5343 push @cust_main, qsearch( {
5344 'table' => 'cust_main',
5345 'hashref' => { 'custnum' => $1, %options },
5346 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5349 push @cust_main, qsearch( {
5350 'table' => 'cust_main',
5351 'hashref' => { 'agent_custid' => $1, %options },
5352 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5355 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5357 my($company, $last, $first) = ( $1, $2, $3 );
5359 # "Company (Last, First)"
5360 #this is probably something a browser remembered,
5361 #so just do an exact search
5363 foreach my $prefix ( '', 'ship_' ) {
5364 push @cust_main, qsearch( {
5365 'table' => 'cust_main',
5366 'hashref' => { $prefix.'first' => $first,
5367 $prefix.'last' => $last,
5368 $prefix.'company' => $company,
5371 'extra_sql' => " AND $agentnums_sql",
5375 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5376 # try (ship_){last,company}
5380 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5381 # # full strings the browser remembers won't work
5382 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5384 use Lingua::EN::NameParse;
5385 my $NameParse = new Lingua::EN::NameParse(
5387 allow_reversed => 1,
5390 my($last, $first) = ( '', '' );
5391 #maybe disable this too and just rely on NameParse?
5392 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5394 ($last, $first) = ( $1, $2 );
5396 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5397 } elsif ( ! $NameParse->parse($value) ) {
5399 my %name = $NameParse->components;
5400 $first = $name{'given_name_1'};
5401 $last = $name{'surname_1'};
5405 if ( $first && $last ) {
5407 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5410 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5412 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5413 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5416 push @cust_main, qsearch( {
5417 'table' => 'cust_main',
5418 'hashref' => \%options,
5419 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5422 # or it just be something that was typed in... (try that in a sec)
5426 my $q_value = dbh->quote($value);
5429 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5430 $sql .= " ( LOWER(last) = $q_value
5431 OR LOWER(company) = $q_value
5432 OR LOWER(ship_last) = $q_value
5433 OR LOWER(ship_company) = $q_value
5436 push @cust_main, qsearch( {
5437 'table' => 'cust_main',
5438 'hashref' => \%options,
5439 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5442 #no exact match, trying substring/fuzzy
5443 #always do substring & fuzzy (unless they're explicity config'ed off)
5444 #getting complaints searches are not returning enough
5445 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
5447 #still some false laziness w/ search/cust_main.cgi
5452 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
5453 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5456 if ( $first && $last ) {
5459 { 'first' => { op=>'ILIKE', value=>"%$first%" },
5460 'last' => { op=>'ILIKE', value=>"%$last%" },
5462 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
5463 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
5470 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
5471 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
5475 foreach my $hashref ( @hashrefs ) {
5477 push @cust_main, qsearch( {
5478 'table' => 'cust_main',
5479 'hashref' => { %$hashref,
5482 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
5491 " AND $agentnums_sql", #extra_sql #agent virtualization
5494 if ( $first && $last ) {
5495 push @cust_main, FS::cust_main->fuzzy_search(
5496 { 'last' => $last, #fuzzy hashref
5497 'first' => $first }, #
5501 foreach my $field ( 'last', 'company' ) {
5503 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
5508 #eliminate duplicates
5510 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5518 =item check_and_rebuild_fuzzyfiles
5522 use vars qw(@fuzzyfields);
5523 @fuzzyfields = ( 'last', 'first', 'company' );
5525 sub check_and_rebuild_fuzzyfiles {
5526 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5527 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
5530 =item rebuild_fuzzyfiles
5534 sub rebuild_fuzzyfiles {
5536 use Fcntl qw(:flock);
5538 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5539 mkdir $dir, 0700 unless -d $dir;
5541 foreach my $fuzzy ( @fuzzyfields ) {
5543 open(LOCK,">>$dir/cust_main.$fuzzy")
5544 or die "can't open $dir/cust_main.$fuzzy: $!";
5546 or die "can't lock $dir/cust_main.$fuzzy: $!";
5548 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
5549 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
5551 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
5552 my $sth = dbh->prepare("SELECT $field FROM cust_main".
5553 " WHERE $field != '' AND $field IS NOT NULL");
5554 $sth->execute or die $sth->errstr;
5556 while ( my $row = $sth->fetchrow_arrayref ) {
5557 print CACHE $row->[0]. "\n";
5562 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
5564 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
5575 my( $self, $field ) = @_;
5576 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5577 open(CACHE,"<$dir/cust_main.$field")
5578 or die "can't open $dir/cust_main.$field: $!";
5579 my @array = map { chomp; $_; } <CACHE>;
5584 =item append_fuzzyfiles LASTNAME COMPANY
5588 sub append_fuzzyfiles {
5589 #my( $first, $last, $company ) = @_;
5591 &check_and_rebuild_fuzzyfiles;
5593 use Fcntl qw(:flock);
5595 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5597 foreach my $field (qw( first last company )) {
5602 open(CACHE,">>$dir/cust_main.$field")
5603 or die "can't open $dir/cust_main.$field: $!";
5604 flock(CACHE,LOCK_EX)
5605 or die "can't lock $dir/cust_main.$field: $!";
5607 print CACHE "$value\n";
5609 flock(CACHE,LOCK_UN)
5610 or die "can't unlock $dir/cust_main.$field: $!";
5625 #warn join('-',keys %$param);
5626 my $fh = $param->{filehandle};
5627 my $agentnum = $param->{agentnum};
5629 my $refnum = $param->{refnum};
5630 my $pkgpart = $param->{pkgpart};
5632 #my @fields = @{$param->{fields}};
5633 my $format = $param->{'format'};
5636 if ( $format eq 'simple' ) {
5637 @fields = qw( cust_pkg.setup dayphone first last
5638 address1 address2 city state zip comments );
5640 } elsif ( $format eq 'extended' ) {
5641 @fields = qw( agent_custid refnum
5642 last first address1 address2 city state zip country
5644 ship_last ship_first ship_address1 ship_address2
5645 ship_city ship_state ship_zip ship_country
5646 payinfo paycvv paydate
5649 svc_acct.username svc_acct._password
5652 } elsif ( $format eq 'extended-plus_company' ) {
5653 @fields = qw( agent_custid refnum
5654 last first company address1 address2 city state zip country
5656 ship_last ship_first ship_company ship_address1 ship_address2
5657 ship_city ship_state ship_zip ship_country
5658 payinfo paycvv paydate
5661 svc_acct.username svc_acct._password
5665 die "unknown format $format";
5668 eval "use Text::CSV_XS;";
5671 my $csv = new Text::CSV_XS;
5678 local $SIG{HUP} = 'IGNORE';
5679 local $SIG{INT} = 'IGNORE';
5680 local $SIG{QUIT} = 'IGNORE';
5681 local $SIG{TERM} = 'IGNORE';
5682 local $SIG{TSTP} = 'IGNORE';
5683 local $SIG{PIPE} = 'IGNORE';
5685 my $oldAutoCommit = $FS::UID::AutoCommit;
5686 local $FS::UID::AutoCommit = 0;
5689 #while ( $columns = $csv->getline($fh) ) {
5691 while ( defined($line=<$fh>) ) {
5693 $csv->parse($line) or do {
5694 $dbh->rollback if $oldAutoCommit;
5695 return "can't parse: ". $csv->error_input();
5698 my @columns = $csv->fields();
5699 #warn join('-',@columns);
5702 agentnum => $agentnum,
5704 country => $conf->config('countrydefault') || 'US',
5705 payby => $payby, #default
5706 paydate => '12/2037', #default
5708 my $billtime = time;
5709 my %cust_pkg = ( pkgpart => $pkgpart );
5711 foreach my $field ( @fields ) {
5713 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
5715 #$cust_pkg{$1} = str2time( shift @$columns );
5716 if ( $1 eq 'pkgpart' ) {
5717 $cust_pkg{$1} = shift @columns;
5718 } elsif ( $1 eq 'setup' ) {
5719 $billtime = str2time(shift @columns);
5721 $cust_pkg{$1} = str2time( shift @columns );
5724 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
5726 $svc_acct{$1} = shift @columns;
5730 #refnum interception
5731 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
5733 my $referral = $columns[0];
5734 my %hash = ( 'referral' => $referral,
5735 'agentnum' => $agentnum,
5739 my $part_referral = qsearchs('part_referral', \%hash )
5740 || new FS::part_referral \%hash;
5742 unless ( $part_referral->refnum ) {
5743 my $error = $part_referral->insert;
5745 $dbh->rollback if $oldAutoCommit;
5746 return "can't auto-insert advertising source: $referral: $error";
5750 $columns[0] = $part_referral->refnum;
5753 #$cust_main{$field} = shift @$columns;
5754 $cust_main{$field} = shift @columns;
5758 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
5760 my $invoicing_list = $cust_main{'invoicing_list'}
5761 ? [ delete $cust_main{'invoicing_list'} ]
5764 my $cust_main = new FS::cust_main ( \%cust_main );
5767 tie my %hash, 'Tie::RefHash'; #this part is important
5769 if ( $cust_pkg{'pkgpart'} ) {
5770 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
5773 if ( $svc_acct{'username'} ) {
5774 my $part_pkg = $cust_pkg->part_pkg;
5775 unless ( $part_pkg ) {
5776 $dbh->rollback if $oldAutoCommit;
5777 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
5779 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
5780 push @svc_acct, new FS::svc_acct ( \%svc_acct )
5783 $hash{$cust_pkg} = \@svc_acct;
5786 my $error = $cust_main->insert( \%hash, $invoicing_list );
5789 $dbh->rollback if $oldAutoCommit;
5790 return "can't insert customer for $line: $error";
5793 if ( $format eq 'simple' ) {
5795 #false laziness w/bill.cgi
5796 $error = $cust_main->bill( 'time' => $billtime );
5798 $dbh->rollback if $oldAutoCommit;
5799 return "can't bill customer for $line: $error";
5802 $error = $cust_main->apply_payments_and_credits;
5804 $dbh->rollback if $oldAutoCommit;
5805 return "can't bill customer for $line: $error";
5808 $error = $cust_main->collect();
5810 $dbh->rollback if $oldAutoCommit;
5811 return "can't collect customer for $line: $error";
5819 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5821 return "Empty file!" unless $imported;
5833 #warn join('-',keys %$param);
5834 my $fh = $param->{filehandle};
5835 my @fields = @{$param->{fields}};
5837 eval "use Text::CSV_XS;";
5840 my $csv = new Text::CSV_XS;
5847 local $SIG{HUP} = 'IGNORE';
5848 local $SIG{INT} = 'IGNORE';
5849 local $SIG{QUIT} = 'IGNORE';
5850 local $SIG{TERM} = 'IGNORE';
5851 local $SIG{TSTP} = 'IGNORE';
5852 local $SIG{PIPE} = 'IGNORE';
5854 my $oldAutoCommit = $FS::UID::AutoCommit;
5855 local $FS::UID::AutoCommit = 0;
5858 #while ( $columns = $csv->getline($fh) ) {
5860 while ( defined($line=<$fh>) ) {
5862 $csv->parse($line) or do {
5863 $dbh->rollback if $oldAutoCommit;
5864 return "can't parse: ". $csv->error_input();
5867 my @columns = $csv->fields();
5868 #warn join('-',@columns);
5871 foreach my $field ( @fields ) {
5872 $row{$field} = shift @columns;
5875 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
5876 unless ( $cust_main ) {
5877 $dbh->rollback if $oldAutoCommit;
5878 return "unknown custnum $row{'custnum'}";
5881 if ( $row{'amount'} > 0 ) {
5882 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5884 $dbh->rollback if $oldAutoCommit;
5888 } elsif ( $row{'amount'} < 0 ) {
5889 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5892 $dbh->rollback if $oldAutoCommit;
5902 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5904 return "Empty file!" unless $imported;
5910 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5912 Sends a templated email notification to the customer (see L<Text::Template>).
5914 OPTIONS is a hash and may include
5916 I<from> - the email sender (default is invoice_from)
5918 I<to> - comma-separated scalar or arrayref of recipients
5919 (default is invoicing_list)
5921 I<subject> - The subject line of the sent email notification
5922 (default is "Notice from company_name")
5924 I<extra_fields> - a hashref of name/value pairs which will be substituted
5927 The following variables are vavailable in the template.
5929 I<$first> - the customer first name
5930 I<$last> - the customer last name
5931 I<$company> - the customer company
5932 I<$payby> - a description of the method of payment for the customer
5933 # would be nice to use FS::payby::shortname
5934 I<$payinfo> - the account information used to collect for this customer
5935 I<$expdate> - the expiration of the customer payment in seconds from epoch
5940 my ($customer, $template, %options) = @_;
5942 return unless $conf->exists($template);
5944 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
5945 $from = $options{from} if exists($options{from});
5947 my $to = join(',', $customer->invoicing_list_emailonly);
5948 $to = $options{to} if exists($options{to});
5950 my $subject = "Notice from " . $conf->config('company_name')
5951 if $conf->exists('company_name');
5952 $subject = $options{subject} if exists($options{subject});
5954 my $notify_template = new Text::Template (TYPE => 'ARRAY',
5955 SOURCE => [ map "$_\n",
5956 $conf->config($template)]
5958 or die "can't create new Text::Template object: Text::Template::ERROR";
5959 $notify_template->compile()
5960 or die "can't compile template: Text::Template::ERROR";
5962 $FS::notify_template::_template::company_name = $conf->config('company_name');
5963 $FS::notify_template::_template::company_address =
5964 join("\n", $conf->config('company_address') ). "\n";
5966 my $paydate = $customer->paydate || '2037-12-31';
5967 $FS::notify_template::_template::first = $customer->first;
5968 $FS::notify_template::_template::last = $customer->last;
5969 $FS::notify_template::_template::company = $customer->company;
5970 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
5971 my $payby = $customer->payby;
5972 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5973 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5975 #credit cards expire at the end of the month/year of their exp date
5976 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5977 $FS::notify_template::_template::payby = 'credit card';
5978 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5979 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5981 }elsif ($payby eq 'COMP') {
5982 $FS::notify_template::_template::payby = 'complimentary account';
5984 $FS::notify_template::_template::payby = 'current method';
5986 $FS::notify_template::_template::expdate = $expire_time;
5988 for (keys %{$options{extra_fields}}){
5990 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5993 send_email(from => $from,
5995 subject => $subject,
5996 body => $notify_template->fill_in( PACKAGE =>
5997 'FS::notify_template::_template' ),
6002 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6004 Generates a templated notification to the customer (see L<Text::Template>).
6006 OPTIONS is a hash and may include
6008 I<extra_fields> - a hashref of name/value pairs which will be substituted
6009 into the template. These values may override values mentioned below
6010 and those from the customer record.
6012 The following variables are available in the template instead of or in addition
6013 to the fields of the customer record.
6015 I<$payby> - a description of the method of payment for the customer
6016 # would be nice to use FS::payby::shortname
6017 I<$payinfo> - the masked account information used to collect for this customer
6018 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6019 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6023 sub generate_letter {
6024 my ($self, $template, %options) = @_;
6026 return unless $conf->exists($template);
6028 my $letter_template = new Text::Template
6030 SOURCE => [ map "$_\n", $conf->config($template)],
6031 DELIMITERS => [ '[@--', '--@]' ],
6033 or die "can't create new Text::Template object: Text::Template::ERROR";
6035 $letter_template->compile()
6036 or die "can't compile template: Text::Template::ERROR";
6038 my %letter_data = map { $_ => $self->$_ } $self->fields;
6039 $letter_data{payinfo} = $self->mask_payinfo;
6041 #my $paydate = $self->paydate || '2037-12-31';
6042 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6044 my $payby = $self->payby;
6045 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6046 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6048 #credit cards expire at the end of the month/year of their exp date
6049 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6050 $letter_data{payby} = 'credit card';
6051 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6052 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6054 }elsif ($payby eq 'COMP') {
6055 $letter_data{payby} = 'complimentary account';
6057 $letter_data{payby} = 'current method';
6059 $letter_data{expdate} = $expire_time;
6061 for (keys %{$options{extra_fields}}){
6062 $letter_data{$_} = $options{extra_fields}->{$_};
6065 unless(exists($letter_data{returnaddress})){
6066 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6067 $self->agent_template)
6069 if ( length($retadd) ) {
6070 $letter_data{returnaddress} = $retadd;
6071 } elsif ( grep /\S/, $conf->config('company_address') ) {
6072 $letter_data{returnaddress} =
6073 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6074 $conf->config('company_address')
6077 $letter_data{returnaddress} = '~';
6081 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6083 $letter_data{company_name} = $conf->config('company_name');
6085 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6086 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6090 ) or die "can't open temp file: $!\n";
6092 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6094 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6098 =item print_ps TEMPLATE
6100 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6106 my $file = $self->generate_letter(@_);
6107 FS::Misc::generate_ps($file);
6110 =item print TEMPLATE
6112 Prints the filled in template.
6114 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6118 sub queueable_print {
6121 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6122 or die "invalid customer number: " . $opt{custvnum};
6124 my $error = $self->print( $opt{template} );
6125 die $error if $error;
6129 my ($self, $template) = (shift, shift);
6130 do_print [ $self->print_ps($template) ];
6133 sub agent_template {
6135 $self->_agent_plandata('agent_templatename');
6138 sub agent_invoice_from {
6140 $self->_agent_plandata('agent_invoice_from');
6143 sub _agent_plandata {
6144 my( $self, $option ) = @_;
6146 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6147 #agent-specific Conf
6149 use FS::part_event::Condition;
6151 my $agentnum = $self->agentnum;
6154 if ( driver_name =~ /^Pg/i ) {
6156 } elsif ( driver_name =~ /^mysql/i ) {
6159 die "don't know how to use regular expressions in ". driver_name. " databases";
6162 my $part_event_option =
6164 'select' => 'part_event_option.*',
6165 'table' => 'part_event_option',
6167 LEFT JOIN part_event USING ( eventpart )
6168 LEFT JOIN part_event_option AS peo_agentnum
6169 ON ( part_event.eventpart = peo_agentnum.eventpart
6170 AND peo_agentnum.optionname = 'agentnum'
6171 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6173 LEFT JOIN part_event_option AS peo_cust_bill_age
6174 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6175 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6178 #'hashref' => { 'optionname' => $option },
6179 #'hashref' => { 'part_event_option.optionname' => $option },
6181 " WHERE part_event_option.optionname = ". dbh->quote($option).
6182 " AND action = 'cust_bill_send_agent' ".
6183 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6184 " AND peo_agentnum.optionname = 'agentnum' ".
6185 " AND agentnum IS NULL OR agentnum = $agentnum ".
6187 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6189 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6191 , part_event.weight".
6195 unless ( $part_event_option ) {
6196 return $self->agent->invoice_template || ''
6197 if $option eq 'agent_templatename';
6201 $part_event_option->optionvalue;
6206 ## actual sub, not a method, designed to be called from the queue.
6207 ## sets up the customer, and calls the bill_and_collect
6208 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6209 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6210 $cust_main->bill_and_collect(
6221 The delete method should possibly take an FS::cust_main object reference
6222 instead of a scalar customer number.
6224 Bill and collect options should probably be passed as references instead of a
6227 There should probably be a configuration file with a list of allowed credit
6230 No multiple currency support (probably a larger project than just this module).
6232 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6234 Birthdates rely on negative epoch values.
6236 The payby for card/check batches is broken. With mixed batching, bad
6239 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
6243 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6244 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6245 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.