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;
49 use FS::payment_gateway;
50 use FS::agent_payment_gateway;
52 use FS::payinfo_Mixin;
55 @ISA = qw( FS::Record FS::payinfo_Mixin );
57 @EXPORT_OK = qw( smart_search );
59 $realtime_bop_decline_quiet = 0;
61 # 1 is mostly method/subroutine entry and options
62 # 2 traces progress of some operations
63 # 3 is even more information including possibly sensitive data
65 $me = '[FS::cust_main]';
69 $ignore_expired_card = 0;
71 @encrypted_fields = ('payinfo', 'paycvv');
72 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
74 #ask FS::UID to run this stuff for us later
75 #$FS::UID::callback{'FS::cust_main'} = sub {
76 install_callback FS::UID sub {
78 #yes, need it for stuff below (prolly should be cached)
83 my ( $hashref, $cache ) = @_;
84 if ( exists $hashref->{'pkgnum'} ) {
85 #@{ $self->{'_pkgnum'} } = ();
86 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
87 $self->{'_pkgnum'} = $subcache;
88 #push @{ $self->{'_pkgnum'} },
89 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
95 FS::cust_main - Object methods for cust_main records
101 $record = new FS::cust_main \%hash;
102 $record = new FS::cust_main { 'column' => 'value' };
104 $error = $record->insert;
106 $error = $new_record->replace($old_record);
108 $error = $record->delete;
110 $error = $record->check;
112 @cust_pkg = $record->all_pkgs;
114 @cust_pkg = $record->ncancelled_pkgs;
116 @cust_pkg = $record->suspended_pkgs;
118 $error = $record->bill;
119 $error = $record->bill %options;
120 $error = $record->bill 'time' => $time;
122 $error = $record->collect;
123 $error = $record->collect %options;
124 $error = $record->collect 'invoice_time' => $time,
129 An FS::cust_main object represents a customer. FS::cust_main inherits from
130 FS::Record. The following fields are currently supported:
134 =item custnum - primary key (assigned automatically for new customers)
136 =item agentnum - agent (see L<FS::agent>)
138 =item refnum - Advertising source (see L<FS::part_referral>)
144 =item ss - social security number (optional)
146 =item company - (optional)
150 =item address2 - (optional)
154 =item county - (optional, see L<FS::cust_main_county>)
156 =item state - (see L<FS::cust_main_county>)
160 =item country - (see L<FS::cust_main_county>)
162 =item daytime - phone (optional)
164 =item night - phone (optional)
166 =item fax - phone (optional)
168 =item ship_first - name
170 =item ship_last - name
172 =item ship_company - (optional)
176 =item ship_address2 - (optional)
180 =item ship_county - (optional, see L<FS::cust_main_county>)
182 =item ship_state - (see L<FS::cust_main_county>)
186 =item ship_country - (see L<FS::cust_main_county>)
188 =item ship_daytime - phone (optional)
190 =item ship_night - phone (optional)
192 =item ship_fax - phone (optional)
194 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
196 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
198 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
202 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
204 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
206 =item paystart_month - start date month (maestro/solo cards only)
208 =item paystart_year - start date year (maestro/solo cards only)
210 =item payissue - issue number (maestro/solo cards only)
212 =item payname - name on card or billing name
214 =item payip - IP address from which payment information was received
216 =item tax - tax exempt, empty or `Y'
218 =item otaker - order taker (assigned automatically, see L<FS::UID>)
220 =item comments - comments (optional)
222 =item referral_custnum - referring customer number
224 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
234 Creates a new customer. To add the customer to the database, see L<"insert">.
236 Note that this stores the hash reference, not a distinct copy of the hash it
237 points to. You can ask the object for a copy with the I<hash> method.
241 sub table { 'cust_main'; }
243 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
245 Adds this customer to the database. If there is an error, returns the error,
246 otherwise returns false.
248 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
249 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
250 are inserted atomicly, or the transaction is rolled back. Passing an empty
251 hash reference is equivalent to not supplying this parameter. There should be
252 a better explanation of this, but until then, here's an example:
255 tie %hash, 'Tie::RefHash'; #this part is important
257 $cust_pkg => [ $svc_acct ],
260 $cust_main->insert( \%hash );
262 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
263 be set as the invoicing list (see L<"invoicing_list">). Errors return as
264 expected and rollback the entire transaction; it is not necessary to call
265 check_invoicing_list first. The invoicing_list is set after the records in the
266 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
267 invoicing_list destination to the newly-created svc_acct. Here's an example:
269 $cust_main->insert( {}, [ $email, 'POST' ] );
271 Currently available options are: I<depend_jobnum> and I<noexport>.
273 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
274 on the supplied jobnum (they will not run until the specific job completes).
275 This can be used to defer provisioning until some action completes (such
276 as running the customer's credit card successfully).
278 The I<noexport> option is deprecated. If I<noexport> is set true, no
279 provisioning jobs (exports) are scheduled. (You can schedule them later with
280 the B<reexport> method.)
286 my $cust_pkgs = @_ ? shift : {};
287 my $invoicing_list = @_ ? shift : '';
289 warn "$me insert called with options ".
290 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
293 local $SIG{HUP} = 'IGNORE';
294 local $SIG{INT} = 'IGNORE';
295 local $SIG{QUIT} = 'IGNORE';
296 local $SIG{TERM} = 'IGNORE';
297 local $SIG{TSTP} = 'IGNORE';
298 local $SIG{PIPE} = 'IGNORE';
300 my $oldAutoCommit = $FS::UID::AutoCommit;
301 local $FS::UID::AutoCommit = 0;
304 my $prepay_identifier = '';
305 my( $amount, $seconds ) = ( 0, 0 );
307 if ( $self->payby eq 'PREPAY' ) {
309 $self->payby('BILL');
310 $prepay_identifier = $self->payinfo;
313 warn " looking up prepaid card $prepay_identifier\n"
316 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
318 $dbh->rollback if $oldAutoCommit;
319 #return "error applying prepaid card (transaction rolled back): $error";
323 $payby = 'PREP' if $amount;
325 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
328 $self->payby('BILL');
329 $amount = $self->paid;
333 warn " inserting $self\n"
336 $self->signupdate(time) unless $self->signupdate;
338 my $error = $self->SUPER::insert;
340 $dbh->rollback if $oldAutoCommit;
341 #return "inserting cust_main record (transaction rolled back): $error";
345 warn " setting invoicing list\n"
348 if ( $invoicing_list ) {
349 $error = $self->check_invoicing_list( $invoicing_list );
351 $dbh->rollback if $oldAutoCommit;
352 #return "checking invoicing_list (transaction rolled back): $error";
355 $self->invoicing_list( $invoicing_list );
358 if ( $conf->config('cust_main-skeleton_tables')
359 && $conf->config('cust_main-skeleton_custnum') ) {
361 warn " inserting skeleton records\n"
364 my $error = $self->start_copy_skel;
366 $dbh->rollback if $oldAutoCommit;
372 warn " ordering packages\n"
375 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
377 $dbh->rollback if $oldAutoCommit;
382 $dbh->rollback if $oldAutoCommit;
383 return "No svc_acct record to apply pre-paid time";
387 warn " inserting initial $payby payment of $amount\n"
389 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
391 $dbh->rollback if $oldAutoCommit;
392 return "inserting payment (transaction rolled back): $error";
396 unless ( $import || $skip_fuzzyfiles ) {
397 warn " queueing fuzzyfiles update\n"
399 $error = $self->queue_fuzzyfiles_update;
401 $dbh->rollback if $oldAutoCommit;
402 return "updating fuzzy search cache: $error";
406 warn " insert complete; committing transaction\n"
409 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
414 sub start_copy_skel {
417 #'mg_user_preference' => {},
418 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
419 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
420 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
421 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
422 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
425 _copy_skel( 'cust_main', #tablename
426 $conf->config('cust_main-skeleton_custnum'), #sourceid
427 $self->custnum, #destid
428 @tables, #child tables
432 #recursive subroutine, not a method
434 my( $table, $sourceid, $destid, %child_tables ) = @_;
437 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
438 ( $table, $primary_key ) = ( $1, $2 );
440 my $dbdef_table = dbdef->table($table);
441 $primary_key = $dbdef_table->primary_key
442 or return "$table has no primary key".
443 " (or do you need to run dbdef-create?)";
446 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
447 join (', ', keys %child_tables). "\n"
450 foreach my $child_table_def ( keys %child_tables ) {
454 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
455 ( $child_table, $child_pkey ) = ( $1, $2 );
457 $child_table = $child_table_def;
459 $child_pkey = dbdef->table($child_table)->primary_key;
460 # or return "$table has no primary key".
461 # " (or do you need to run dbdef-create?)\n";
465 if ( keys %{ $child_tables{$child_table_def} } ) {
467 return "$child_table has no primary key".
468 " (run dbdef-create or try specifying it?)\n"
471 #false laziness w/Record::insert and only works on Pg
472 #refactor the proper last-inserted-id stuff out of Record::insert if this
473 # ever gets use for anything besides a quick kludge for one customer
474 my $default = dbdef->table($child_table)->column($child_pkey)->default;
475 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
476 or return "can't parse $child_table.$child_pkey default value ".
477 " for sequence name: $default";
482 my @sel_columns = grep { $_ ne $primary_key }
483 dbdef->table($child_table)->columns;
484 my $sel_columns = join(', ', @sel_columns );
486 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
487 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
488 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
490 my $sel_st = "SELECT $sel_columns FROM $child_table".
491 " WHERE $primary_key = $sourceid";
494 my $sel_sth = dbh->prepare( $sel_st )
495 or return dbh->errstr;
497 $sel_sth->execute or return $sel_sth->errstr;
499 while ( my $row = $sel_sth->fetchrow_hashref ) {
501 warn " selected row: ".
502 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
506 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
507 my $ins_sth =dbh->prepare($statement)
508 or return dbh->errstr;
509 my @param = ( $destid, map $row->{$_}, @ins_columns );
510 warn " $statement: [ ". join(', ', @param). " ]\n"
512 $ins_sth->execute( @param )
513 or return $ins_sth->errstr;
515 #next unless keys %{ $child_tables{$child_table} };
516 next unless $sequence;
518 #another section of that laziness
519 my $seq_sql = "SELECT currval('$sequence')";
520 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
521 $seq_sth->execute or return $seq_sth->errstr;
522 my $insertid = $seq_sth->fetchrow_arrayref->[0];
524 # don't drink soap! recurse! recurse! okay!
526 _copy_skel( $child_table_def,
527 $row->{$child_pkey}, #sourceid
529 %{ $child_tables{$child_table_def} },
531 return $error if $error;
541 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
543 Like the insert method on an existing record, this method orders a package
544 and included services atomicaly. Pass a Tie::RefHash data structure to this
545 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
546 be a better explanation of this, but until then, here's an example:
549 tie %hash, 'Tie::RefHash'; #this part is important
551 $cust_pkg => [ $svc_acct ],
554 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
556 Services can be new, in which case they are inserted, or existing unaudited
557 services, in which case they are linked to the newly-created package.
559 Currently available options are: I<depend_jobnum> and I<noexport>.
561 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
562 on the supplied jobnum (they will not run until the specific job completes).
563 This can be used to defer provisioning until some action completes (such
564 as running the customer's credit card successfully).
566 The I<noexport> option is deprecated. If I<noexport> is set true, no
567 provisioning jobs (exports) are scheduled. (You can schedule them later with
568 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
569 on the cust_main object is not recommended, as existing services will also be
576 my $cust_pkgs = shift;
579 my %svc_options = ();
580 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
581 if exists $options{'depend_jobnum'};
582 warn "$me order_pkgs called with options ".
583 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
586 local $SIG{HUP} = 'IGNORE';
587 local $SIG{INT} = 'IGNORE';
588 local $SIG{QUIT} = 'IGNORE';
589 local $SIG{TERM} = 'IGNORE';
590 local $SIG{TSTP} = 'IGNORE';
591 local $SIG{PIPE} = 'IGNORE';
593 my $oldAutoCommit = $FS::UID::AutoCommit;
594 local $FS::UID::AutoCommit = 0;
597 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
599 foreach my $cust_pkg ( keys %$cust_pkgs ) {
600 $cust_pkg->custnum( $self->custnum );
601 my $error = $cust_pkg->insert;
603 $dbh->rollback if $oldAutoCommit;
604 return "inserting cust_pkg (transaction rolled back): $error";
606 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
607 if ( $svc_something->svcnum ) {
608 my $old_cust_svc = $svc_something->cust_svc;
609 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
610 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
611 $error = $new_cust_svc->replace($old_cust_svc);
613 $svc_something->pkgnum( $cust_pkg->pkgnum );
614 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
615 $svc_something->seconds( $svc_something->seconds + $$seconds );
618 $error = $svc_something->insert(%svc_options);
621 $dbh->rollback if $oldAutoCommit;
622 #return "inserting svc_ (transaction rolled back): $error";
628 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
632 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
634 Recharges this (existing) customer with the specified prepaid card (see
635 L<FS::prepay_credit>), specified either by I<identifier> or as an
636 FS::prepay_credit object. If there is an error, returns the error, otherwise
639 Optionally, four scalar references can be passed as well. They will have their
640 values filled in with the amount, number of seconds, and number of upload and
641 download bytes applied by this prepaid
646 sub recharge_prepay {
647 my( $self, $prepay_credit, $amountref, $secondsref,
648 $upbytesref, $downbytesref, $totalbytesref ) = @_;
650 local $SIG{HUP} = 'IGNORE';
651 local $SIG{INT} = 'IGNORE';
652 local $SIG{QUIT} = 'IGNORE';
653 local $SIG{TERM} = 'IGNORE';
654 local $SIG{TSTP} = 'IGNORE';
655 local $SIG{PIPE} = 'IGNORE';
657 my $oldAutoCommit = $FS::UID::AutoCommit;
658 local $FS::UID::AutoCommit = 0;
661 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
663 my $error = $self->get_prepay($prepay_credit, \$amount,
664 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
665 || $self->increment_seconds($seconds)
666 || $self->increment_upbytes($upbytes)
667 || $self->increment_downbytes($downbytes)
668 || $self->increment_totalbytes($totalbytes)
669 || $self->insert_cust_pay_prepay( $amount,
671 ? $prepay_credit->identifier
676 $dbh->rollback if $oldAutoCommit;
680 if ( defined($amountref) ) { $$amountref = $amount; }
681 if ( defined($secondsref) ) { $$secondsref = $seconds; }
682 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
683 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
684 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
686 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
691 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
693 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
694 specified either by I<identifier> or as an FS::prepay_credit object.
696 References to I<amount> and I<seconds> scalars should be passed as arguments
697 and will be incremented by the values of the prepaid card.
699 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
700 check or set this customer's I<agentnum>.
702 If there is an error, returns the error, otherwise returns false.
708 my( $self, $prepay_credit, $amountref, $secondsref,
709 $upref, $downref, $totalref) = @_;
711 local $SIG{HUP} = 'IGNORE';
712 local $SIG{INT} = 'IGNORE';
713 local $SIG{QUIT} = 'IGNORE';
714 local $SIG{TERM} = 'IGNORE';
715 local $SIG{TSTP} = 'IGNORE';
716 local $SIG{PIPE} = 'IGNORE';
718 my $oldAutoCommit = $FS::UID::AutoCommit;
719 local $FS::UID::AutoCommit = 0;
722 unless ( ref($prepay_credit) ) {
724 my $identifier = $prepay_credit;
726 $prepay_credit = qsearchs(
728 { 'identifier' => $prepay_credit },
733 unless ( $prepay_credit ) {
734 $dbh->rollback if $oldAutoCommit;
735 return "Invalid prepaid card: ". $identifier;
740 if ( $prepay_credit->agentnum ) {
741 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
742 $dbh->rollback if $oldAutoCommit;
743 return "prepaid card not valid for agent ". $self->agentnum;
745 $self->agentnum($prepay_credit->agentnum);
748 my $error = $prepay_credit->delete;
750 $dbh->rollback if $oldAutoCommit;
751 return "removing prepay_credit (transaction rolled back): $error";
754 $$amountref += $prepay_credit->amount;
755 $$secondsref += $prepay_credit->seconds;
756 $$upref += $prepay_credit->upbytes;
757 $$downref += $prepay_credit->downbytes;
758 $$totalref += $prepay_credit->totalbytes;
760 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
765 =item increment_upbytes SECONDS
767 Updates this customer's single or primary account (see L<FS::svc_acct>) by
768 the specified number of upbytes. If there is an error, returns the error,
769 otherwise returns false.
773 sub increment_upbytes {
774 _increment_column( shift, 'upbytes', @_);
777 =item increment_downbytes SECONDS
779 Updates this customer's single or primary account (see L<FS::svc_acct>) by
780 the specified number of downbytes. If there is an error, returns the error,
781 otherwise returns false.
785 sub increment_downbytes {
786 _increment_column( shift, 'downbytes', @_);
789 =item increment_totalbytes SECONDS
791 Updates this customer's single or primary account (see L<FS::svc_acct>) by
792 the specified number of totalbytes. If there is an error, returns the error,
793 otherwise returns false.
797 sub increment_totalbytes {
798 _increment_column( shift, 'totalbytes', @_);
801 =item increment_seconds SECONDS
803 Updates this customer's single or primary account (see L<FS::svc_acct>) by
804 the specified number of seconds. If there is an error, returns the error,
805 otherwise returns false.
809 sub increment_seconds {
810 _increment_column( shift, 'seconds', @_);
813 =item _increment_column AMOUNT
815 Updates this customer's single or primary account (see L<FS::svc_acct>) by
816 the specified number of seconds or bytes. If there is an error, returns
817 the error, otherwise returns false.
821 sub _increment_column {
822 my( $self, $column, $amount ) = @_;
823 warn "$me increment_column called: $column, $amount\n"
826 return '' unless $amount;
828 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
829 $self->ncancelled_pkgs;
832 return 'No packages with primary or single services found'.
833 ' to apply pre-paid time';
834 } elsif ( scalar(@cust_pkg) > 1 ) {
835 #maybe have a way to specify the package/account?
836 return 'Multiple packages found to apply pre-paid time';
839 my $cust_pkg = $cust_pkg[0];
840 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
844 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
847 return 'No account found to apply pre-paid time';
848 } elsif ( scalar(@cust_svc) > 1 ) {
849 return 'Multiple accounts found to apply pre-paid time';
852 my $svc_acct = $cust_svc[0]->svc_x;
853 warn " found service svcnum ". $svc_acct->pkgnum.
854 ' ('. $svc_acct->email. ")\n"
857 $column = "increment_$column";
858 $svc_acct->$column($amount);
862 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
864 Inserts a prepayment in the specified amount for this customer. An optional
865 second argument can specify the prepayment identifier for tracking purposes.
866 If there is an error, returns the error, otherwise returns false.
870 sub insert_cust_pay_prepay {
871 shift->insert_cust_pay('PREP', @_);
874 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
876 Inserts a cash payment in the specified amount for this customer. An optional
877 second argument can specify the payment identifier for tracking purposes.
878 If there is an error, returns the error, otherwise returns false.
882 sub insert_cust_pay_cash {
883 shift->insert_cust_pay('CASH', @_);
886 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
888 Inserts a Western Union payment in the specified amount for this customer. An
889 optional second argument can specify the prepayment identifier for tracking
890 purposes. If there is an error, returns the error, otherwise returns false.
894 sub insert_cust_pay_west {
895 shift->insert_cust_pay('WEST', @_);
898 sub insert_cust_pay {
899 my( $self, $payby, $amount ) = splice(@_, 0, 3);
900 my $payinfo = scalar(@_) ? shift : '';
902 my $cust_pay = new FS::cust_pay {
903 'custnum' => $self->custnum,
904 'paid' => sprintf('%.2f', $amount),
905 #'_date' => #date the prepaid card was purchased???
907 'payinfo' => $payinfo,
915 This method is deprecated. See the I<depend_jobnum> option to the insert and
916 order_pkgs methods for a better way to defer provisioning.
918 Re-schedules all exports by calling the B<reexport> method of all associated
919 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
920 otherwise returns false.
927 carp "WARNING: FS::cust_main::reexport is deprectated; ".
928 "use the depend_jobnum option to insert or order_pkgs to delay export";
930 local $SIG{HUP} = 'IGNORE';
931 local $SIG{INT} = 'IGNORE';
932 local $SIG{QUIT} = 'IGNORE';
933 local $SIG{TERM} = 'IGNORE';
934 local $SIG{TSTP} = 'IGNORE';
935 local $SIG{PIPE} = 'IGNORE';
937 my $oldAutoCommit = $FS::UID::AutoCommit;
938 local $FS::UID::AutoCommit = 0;
941 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
942 my $error = $cust_pkg->reexport;
944 $dbh->rollback if $oldAutoCommit;
949 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
954 =item delete NEW_CUSTNUM
956 This deletes the customer. If there is an error, returns the error, otherwise
959 This will completely remove all traces of the customer record. This is not
960 what you want when a customer cancels service; for that, cancel all of the
961 customer's packages (see L</cancel>).
963 If the customer has any uncancelled packages, you need to pass a new (valid)
964 customer number for those packages to be transferred to. Cancelled packages
965 will be deleted. Did I mention that this is NOT what you want when a customer
966 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
968 You can't delete a customer with invoices (see L<FS::cust_bill>),
969 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
970 refunds (see L<FS::cust_refund>).
977 local $SIG{HUP} = 'IGNORE';
978 local $SIG{INT} = 'IGNORE';
979 local $SIG{QUIT} = 'IGNORE';
980 local $SIG{TERM} = 'IGNORE';
981 local $SIG{TSTP} = 'IGNORE';
982 local $SIG{PIPE} = 'IGNORE';
984 my $oldAutoCommit = $FS::UID::AutoCommit;
985 local $FS::UID::AutoCommit = 0;
988 if ( $self->cust_bill ) {
989 $dbh->rollback if $oldAutoCommit;
990 return "Can't delete a customer with invoices";
992 if ( $self->cust_credit ) {
993 $dbh->rollback if $oldAutoCommit;
994 return "Can't delete a customer with credits";
996 if ( $self->cust_pay ) {
997 $dbh->rollback if $oldAutoCommit;
998 return "Can't delete a customer with payments";
1000 if ( $self->cust_refund ) {
1001 $dbh->rollback if $oldAutoCommit;
1002 return "Can't delete a customer with refunds";
1005 my @cust_pkg = $self->ncancelled_pkgs;
1007 my $new_custnum = shift;
1008 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1009 $dbh->rollback if $oldAutoCommit;
1010 return "Invalid new customer number: $new_custnum";
1012 foreach my $cust_pkg ( @cust_pkg ) {
1013 my %hash = $cust_pkg->hash;
1014 $hash{'custnum'} = $new_custnum;
1015 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1016 my $error = $new_cust_pkg->replace($cust_pkg,
1017 options => { $cust_pkg->options },
1020 $dbh->rollback if $oldAutoCommit;
1025 my @cancelled_cust_pkg = $self->all_pkgs;
1026 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1027 my $error = $cust_pkg->delete;
1029 $dbh->rollback if $oldAutoCommit;
1034 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1035 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1037 my $error = $cust_main_invoice->delete;
1039 $dbh->rollback if $oldAutoCommit;
1044 my $error = $self->SUPER::delete;
1046 $dbh->rollback if $oldAutoCommit;
1050 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1055 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1057 Replaces the OLD_RECORD with this one in the database. If there is an error,
1058 returns the error, otherwise returns false.
1060 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1061 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1062 expected and rollback the entire transaction; it is not necessary to call
1063 check_invoicing_list first. Here's an example:
1065 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1073 warn "$me replace called\n"
1076 local $SIG{HUP} = 'IGNORE';
1077 local $SIG{INT} = 'IGNORE';
1078 local $SIG{QUIT} = 'IGNORE';
1079 local $SIG{TERM} = 'IGNORE';
1080 local $SIG{TSTP} = 'IGNORE';
1081 local $SIG{PIPE} = 'IGNORE';
1083 # We absolutely have to have an old vs. new record to make this work.
1084 if (!defined($old)) {
1085 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1088 my $curuser = $FS::CurrentUser::CurrentUser;
1089 if ( $self->payby eq 'COMP'
1090 && $self->payby ne $old->payby
1091 && ! $curuser->access_right('Complimentary customer')
1094 return "You are not permitted to create complimentary accounts.";
1097 local($ignore_expired_card) = 1
1098 if $old->payby =~ /^(CARD|DCRD)$/
1099 && $self->payby =~ /^(CARD|DCRD)$/
1100 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1102 my $oldAutoCommit = $FS::UID::AutoCommit;
1103 local $FS::UID::AutoCommit = 0;
1106 my $error = $self->SUPER::replace($old);
1109 $dbh->rollback if $oldAutoCommit;
1113 if ( @param ) { # INVOICING_LIST_ARYREF
1114 my $invoicing_list = shift @param;
1115 $error = $self->check_invoicing_list( $invoicing_list );
1117 $dbh->rollback if $oldAutoCommit;
1120 $self->invoicing_list( $invoicing_list );
1123 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1124 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1125 # card/check/lec info has changed, want to retry realtime_ invoice events
1126 my $error = $self->retry_realtime;
1128 $dbh->rollback if $oldAutoCommit;
1133 unless ( $import || $skip_fuzzyfiles ) {
1134 $error = $self->queue_fuzzyfiles_update;
1136 $dbh->rollback if $oldAutoCommit;
1137 return "updating fuzzy search cache: $error";
1141 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1146 =item queue_fuzzyfiles_update
1148 Used by insert & replace to update the fuzzy search cache
1152 sub queue_fuzzyfiles_update {
1155 local $SIG{HUP} = 'IGNORE';
1156 local $SIG{INT} = 'IGNORE';
1157 local $SIG{QUIT} = 'IGNORE';
1158 local $SIG{TERM} = 'IGNORE';
1159 local $SIG{TSTP} = 'IGNORE';
1160 local $SIG{PIPE} = 'IGNORE';
1162 my $oldAutoCommit = $FS::UID::AutoCommit;
1163 local $FS::UID::AutoCommit = 0;
1166 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1167 my $error = $queue->insert( map $self->getfield($_),
1168 qw(first last company)
1171 $dbh->rollback if $oldAutoCommit;
1172 return "queueing job (transaction rolled back): $error";
1175 if ( $self->ship_last ) {
1176 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1177 $error = $queue->insert( map $self->getfield("ship_$_"),
1178 qw(first last company)
1181 $dbh->rollback if $oldAutoCommit;
1182 return "queueing job (transaction rolled back): $error";
1186 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1193 Checks all fields to make sure this is a valid customer record. If there is
1194 an error, returns the error, otherwise returns false. Called by the insert
1195 and replace methods.
1202 warn "$me check BEFORE: \n". $self->_dump
1206 $self->ut_numbern('custnum')
1207 || $self->ut_number('agentnum')
1208 || $self->ut_textn('agent_custid')
1209 || $self->ut_number('refnum')
1210 || $self->ut_name('last')
1211 || $self->ut_name('first')
1212 || $self->ut_snumbern('birthdate')
1213 || $self->ut_snumbern('signupdate')
1214 || $self->ut_textn('company')
1215 || $self->ut_text('address1')
1216 || $self->ut_textn('address2')
1217 || $self->ut_text('city')
1218 || $self->ut_textn('county')
1219 || $self->ut_textn('state')
1220 || $self->ut_country('country')
1221 || $self->ut_anything('comments')
1222 || $self->ut_numbern('referral_custnum')
1223 || $self->ut_textn('stateid')
1224 || $self->ut_textn('stateid_state')
1225 || $self->ut_textn('invoice_terms')
1227 #barf. need message catalogs. i18n. etc.
1228 $error .= "Please select an advertising source."
1229 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1230 return $error if $error;
1232 return "Unknown agent"
1233 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1235 return "Unknown refnum"
1236 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1238 return "Unknown referring custnum: ". $self->referral_custnum
1239 unless ! $self->referral_custnum
1240 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1242 if ( $self->ss eq '' ) {
1247 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1248 or return "Illegal social security number: ". $self->ss;
1249 $self->ss("$1-$2-$3");
1253 # bad idea to disable, causes billing to fail because of no tax rates later
1254 # unless ( $import ) {
1255 unless ( qsearch('cust_main_county', {
1256 'country' => $self->country,
1259 return "Unknown state/county/country: ".
1260 $self->state. "/". $self->county. "/". $self->country
1261 unless qsearch('cust_main_county',{
1262 'state' => $self->state,
1263 'county' => $self->county,
1264 'country' => $self->country,
1270 $self->ut_phonen('daytime', $self->country)
1271 || $self->ut_phonen('night', $self->country)
1272 || $self->ut_phonen('fax', $self->country)
1273 || $self->ut_zip('zip', $self->country)
1275 return $error if $error;
1277 if ( $conf->exists('cust_main-require_phone')
1278 && ! length($self->daytime) && ! length($self->night)
1281 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1283 : FS::Msgcat::_gettext('daytime');
1284 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1286 : FS::Msgcat::_gettext('night');
1288 return "$daytime_label or $night_label is required"
1292 if ( $self->has_ship_address
1293 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1294 $self->addr_fields )
1298 $self->ut_name('ship_last')
1299 || $self->ut_name('ship_first')
1300 || $self->ut_textn('ship_company')
1301 || $self->ut_text('ship_address1')
1302 || $self->ut_textn('ship_address2')
1303 || $self->ut_text('ship_city')
1304 || $self->ut_textn('ship_county')
1305 || $self->ut_textn('ship_state')
1306 || $self->ut_country('ship_country')
1308 return $error if $error;
1310 #false laziness with above
1311 unless ( qsearchs('cust_main_county', {
1312 'country' => $self->ship_country,
1315 return "Unknown ship_state/ship_county/ship_country: ".
1316 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1317 unless qsearch('cust_main_county',{
1318 'state' => $self->ship_state,
1319 'county' => $self->ship_county,
1320 'country' => $self->ship_country,
1326 $self->ut_phonen('ship_daytime', $self->ship_country)
1327 || $self->ut_phonen('ship_night', $self->ship_country)
1328 || $self->ut_phonen('ship_fax', $self->ship_country)
1329 || $self->ut_zip('ship_zip', $self->ship_country)
1331 return $error if $error;
1333 return "Unit # is required."
1334 if $self->ship_address2 =~ /^\s*$/
1335 && $conf->exists('cust_main-require_address2');
1337 } else { # ship_ info eq billing info, so don't store dup info in database
1339 $self->setfield("ship_$_", '')
1340 foreach $self->addr_fields;
1342 return "Unit # is required."
1343 if $self->address2 =~ /^\s*$/
1344 && $conf->exists('cust_main-require_address2');
1348 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1349 # or return "Illegal payby: ". $self->payby;
1351 FS::payby->can_payby($self->table, $self->payby)
1352 or return "Illegal payby: ". $self->payby;
1354 $error = $self->ut_numbern('paystart_month')
1355 || $self->ut_numbern('paystart_year')
1356 || $self->ut_numbern('payissue')
1357 || $self->ut_textn('paytype')
1359 return $error if $error;
1361 if ( $self->payip eq '' ) {
1364 $error = $self->ut_ip('payip');
1365 return $error if $error;
1368 # If it is encrypted and the private key is not availaible then we can't
1369 # check the credit card.
1371 my $check_payinfo = 1;
1373 if ($self->is_encrypted($self->payinfo)) {
1377 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1379 my $payinfo = $self->payinfo;
1380 $payinfo =~ s/\D//g;
1381 $payinfo =~ /^(\d{13,16})$/
1382 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1384 $self->payinfo($payinfo);
1386 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1388 return gettext('unknown_card_type')
1389 if cardtype($self->payinfo) eq "Unknown";
1391 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1393 return 'Banned credit card: banned on '.
1394 time2str('%a %h %o at %r', $ban->_date).
1395 ' by '. $ban->otaker.
1396 ' (ban# '. $ban->bannum. ')';
1399 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1400 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1401 $self->paycvv =~ /^(\d{4})$/
1402 or return "CVV2 (CID) for American Express cards is four digits.";
1405 $self->paycvv =~ /^(\d{3})$/
1406 or return "CVV2 (CVC2/CID) is three digits.";
1413 my $cardtype = cardtype($payinfo);
1414 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1416 return "Start date or issue number is required for $cardtype cards"
1417 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1419 return "Start month must be between 1 and 12"
1420 if $self->paystart_month
1421 and $self->paystart_month < 1 || $self->paystart_month > 12;
1423 return "Start year must be 1990 or later"
1424 if $self->paystart_year
1425 and $self->paystart_year < 1990;
1427 return "Issue number must be beween 1 and 99"
1429 and $self->payissue < 1 || $self->payissue > 99;
1432 $self->paystart_month('');
1433 $self->paystart_year('');
1434 $self->payissue('');
1437 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1439 my $payinfo = $self->payinfo;
1440 $payinfo =~ s/[^\d\@]//g;
1441 if ( $conf->exists('echeck-nonus') ) {
1442 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1443 $payinfo = "$1\@$2";
1445 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1446 $payinfo = "$1\@$2";
1448 $self->payinfo($payinfo);
1451 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1453 return 'Banned ACH account: banned on '.
1454 time2str('%a %h %o at %r', $ban->_date).
1455 ' by '. $ban->otaker.
1456 ' (ban# '. $ban->bannum. ')';
1459 } elsif ( $self->payby eq 'LECB' ) {
1461 my $payinfo = $self->payinfo;
1462 $payinfo =~ s/\D//g;
1463 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1465 $self->payinfo($payinfo);
1468 } elsif ( $self->payby eq 'BILL' ) {
1470 $error = $self->ut_textn('payinfo');
1471 return "Illegal P.O. number: ". $self->payinfo if $error;
1474 } elsif ( $self->payby eq 'COMP' ) {
1476 my $curuser = $FS::CurrentUser::CurrentUser;
1477 if ( ! $self->custnum
1478 && ! $curuser->access_right('Complimentary customer')
1481 return "You are not permitted to create complimentary accounts."
1484 $error = $self->ut_textn('payinfo');
1485 return "Illegal comp account issuer: ". $self->payinfo if $error;
1488 } elsif ( $self->payby eq 'PREPAY' ) {
1490 my $payinfo = $self->payinfo;
1491 $payinfo =~ s/\W//g; #anything else would just confuse things
1492 $self->payinfo($payinfo);
1493 $error = $self->ut_alpha('payinfo');
1494 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1495 return "Unknown prepayment identifier"
1496 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1501 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1502 return "Expiration date required"
1503 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1507 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1508 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1509 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1510 ( $m, $y ) = ( $3, "20$2" );
1512 return "Illegal expiration date: ". $self->paydate;
1514 $self->paydate("$y-$m-01");
1515 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1516 return gettext('expired_card')
1518 && !$ignore_expired_card
1519 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1522 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1523 ( ! $conf->exists('require_cardname')
1524 || $self->payby !~ /^(CARD|DCRD)$/ )
1526 $self->payname( $self->first. " ". $self->getfield('last') );
1528 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1529 or return gettext('illegal_name'). " payname: ". $self->payname;
1533 foreach my $flag (qw( tax spool_cdr )) {
1534 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1538 $self->otaker(getotaker) unless $self->otaker;
1540 warn "$me check AFTER: \n". $self->_dump
1543 $self->SUPER::check;
1548 Returns a list of fields which have ship_ duplicates.
1553 qw( last first company
1554 address1 address2 city county state zip country
1559 =item has_ship_address
1561 Returns true if this customer record has a separate shipping address.
1565 sub has_ship_address {
1567 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1572 Returns all packages (see L<FS::cust_pkg>) for this customer.
1579 return $self->num_pkgs unless wantarray;
1582 if ( $self->{'_pkgnum'} ) {
1583 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1585 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1588 sort sort_packages @cust_pkg;
1593 Synonym for B<all_pkgs>.
1598 shift->all_pkgs(@_);
1601 =item ncancelled_pkgs
1603 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1607 sub ncancelled_pkgs {
1610 return $self->num_ncancelled_pkgs unless wantarray;
1613 if ( $self->{'_pkgnum'} ) {
1615 warn "$me ncancelled_pkgs: returning cached objects"
1618 @cust_pkg = grep { ! $_->getfield('cancel') }
1619 values %{ $self->{'_pkgnum'}->cache };
1623 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1624 $self->custnum. "\n"
1628 qsearch( 'cust_pkg', {
1629 'custnum' => $self->custnum,
1633 qsearch( 'cust_pkg', {
1634 'custnum' => $self->custnum,
1639 sort sort_packages @cust_pkg;
1643 # This should be generalized to use config options to determine order.
1645 if ( $a->get('cancel') and $b->get('cancel') ) {
1646 $a->pkgnum <=> $b->pkgnum;
1647 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1648 return -1 if $b->get('cancel');
1649 return 1 if $a->get('cancel');
1652 $a->pkgnum <=> $b->pkgnum;
1656 =item suspended_pkgs
1658 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1662 sub suspended_pkgs {
1664 grep { $_->susp } $self->ncancelled_pkgs;
1667 =item unflagged_suspended_pkgs
1669 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1670 customer (thouse packages without the `manual_flag' set).
1674 sub unflagged_suspended_pkgs {
1676 return $self->suspended_pkgs
1677 unless dbdef->table('cust_pkg')->column('manual_flag');
1678 grep { ! $_->manual_flag } $self->suspended_pkgs;
1681 =item unsuspended_pkgs
1683 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1688 sub unsuspended_pkgs {
1690 grep { ! $_->susp } $self->ncancelled_pkgs;
1693 =item num_cancelled_pkgs
1695 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1700 sub num_cancelled_pkgs {
1701 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1704 sub num_ncancelled_pkgs {
1705 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1709 my( $self ) = shift;
1710 my $sql = scalar(@_) ? shift : '';
1711 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1712 my $sth = dbh->prepare(
1713 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1714 ) or die dbh->errstr;
1715 $sth->execute($self->custnum) or die $sth->errstr;
1716 $sth->fetchrow_arrayref->[0];
1721 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1722 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1723 on success or a list of errors.
1729 grep { $_->unsuspend } $self->suspended_pkgs;
1734 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1736 Returns a list: an empty list on success or a list of errors.
1742 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1745 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1747 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1748 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1749 of a list of pkgparts; the hashref has the following keys:
1753 =item pkgparts - listref of pkgparts
1755 =item (other options are passed to the suspend method)
1760 Returns a list: an empty list on success or a list of errors.
1764 sub suspend_if_pkgpart {
1766 my (@pkgparts, %opt);
1767 if (ref($_[0]) eq 'HASH'){
1768 @pkgparts = @{$_[0]{pkgparts}};
1773 grep { $_->suspend(%opt) }
1774 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1775 $self->unsuspended_pkgs;
1778 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1780 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1781 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1782 instead of a list of pkgparts; the hashref has the following keys:
1786 =item pkgparts - listref of pkgparts
1788 =item (other options are passed to the suspend method)
1792 Returns a list: an empty list on success or a list of errors.
1796 sub suspend_unless_pkgpart {
1798 my (@pkgparts, %opt);
1799 if (ref($_[0]) eq 'HASH'){
1800 @pkgparts = @{$_[0]{pkgparts}};
1805 grep { $_->suspend(%opt) }
1806 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1807 $self->unsuspended_pkgs;
1810 =item cancel [ OPTION => VALUE ... ]
1812 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1814 Available options are:
1818 =item quiet - can be set true to supress email cancellation notices.
1820 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
1822 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1826 Always returns a list: an empty list on success or a list of errors.
1831 my( $self, %opt ) = @_;
1833 warn "$me cancel called on customer ". $self->custnum. " with options ".
1834 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1837 return ( 'access denied' )
1838 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1840 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1842 #should try decryption (we might have the private key)
1843 # and if not maybe queue a job for the server that does?
1844 return ( "Can't (yet) ban encrypted credit cards" )
1845 if $self->is_encrypted($self->payinfo);
1847 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1848 my $error = $ban->insert;
1849 return ( $error ) if $error;
1853 my @pkgs = $self->ncancelled_pkgs;
1855 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1856 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1859 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1862 sub _banned_pay_hashref {
1873 'payby' => $payby2ban{$self->payby},
1874 'payinfo' => md5_base64($self->payinfo),
1875 #don't ever *search* on reason! #'reason' =>
1881 Returns all notes (see L<FS::cust_main_note>) for this customer.
1888 qsearch( 'cust_main_note',
1889 { 'custnum' => $self->custnum },
1891 'ORDER BY _DATE DESC'
1897 Returns the agent (see L<FS::agent>) for this customer.
1903 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1906 =item bill_and_collect
1908 Cancels and suspends any packages due, generates bills, applies payments and
1911 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1913 Options are passed as name-value pairs. Currently available options are:
1919 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
1923 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1927 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
1931 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1935 If set true, re-charges setup fees.
1939 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1945 sub bill_and_collect {
1946 my( $self, %options ) = @_;
1952 #$^T not $options{time} because freeside-daily -d is for pre-printing invoices
1953 foreach my $cust_pkg (
1954 grep { $_->expire && $_->expire <= $^T } $self->ncancelled_pkgs
1956 my $error = $cust_pkg->cancel;
1957 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1958 " for custnum ". $self->custnum. ": $error"
1966 #$^T not $options{time} because freeside-daily -d is for pre-printing invoices
1967 foreach my $cust_pkg (
1968 grep { ( $_->part_pkg->is_prepaid && $_->bill && $_->bill < $^T
1969 || $_->adjourn && $_->adjourn <= $^T
1973 $self->ncancelled_pkgs
1975 my $error = $cust_pkg->suspend;
1976 warn "Error suspending package ". $cust_pkg->pkgnum.
1977 " for custnum ". $self->custnum. ": $error"
1985 my $error = $self->bill( %options );
1986 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
1988 $self->apply_payments_and_credits;
1990 $error = $self->collect( %options );
1991 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
1997 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1998 conjunction with the collect method by calling B<bill_and_collect>.
2000 If there is an error, returns the error, otherwise returns false.
2002 Options are passed as name-value pairs. Currently available options are:
2008 If set true, re-charges setup fees.
2012 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:
2016 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2020 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2022 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2026 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.
2033 my( $self, %options ) = @_;
2034 return '' if $self->payby eq 'COMP';
2035 warn "$me bill customer ". $self->custnum. "\n"
2038 my $time = $options{'time'} || time;
2043 local $SIG{HUP} = 'IGNORE';
2044 local $SIG{INT} = 'IGNORE';
2045 local $SIG{QUIT} = 'IGNORE';
2046 local $SIG{TERM} = 'IGNORE';
2047 local $SIG{TSTP} = 'IGNORE';
2048 local $SIG{PIPE} = 'IGNORE';
2050 my $oldAutoCommit = $FS::UID::AutoCommit;
2051 local $FS::UID::AutoCommit = 0;
2054 $self->select_for_update; #mutex
2056 #create a new invoice
2057 #(we'll remove it later if it doesn't actually need to be generated [contains
2058 # no line items] and we're inside a transaciton so nothing else will see it)
2059 my $cust_bill = new FS::cust_bill ( {
2060 'custnum' => $self->custnum,
2061 '_date' => ( $options{'invoice_time'} || $time ),
2062 #'charged' => $charged,
2065 $error = $cust_bill->insert;
2067 $dbh->rollback if $oldAutoCommit;
2068 return "can't create invoice for customer #". $self->custnum. ": $error";
2070 my $invnum = $cust_bill->invnum;
2073 # find the packages which are due for billing, find out how much they are
2074 # & generate invoice database.
2077 my( $total_setup, $total_recur ) = ( 0, 0 );
2080 my @precommit_hooks = ();
2082 foreach my $cust_pkg (
2083 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
2086 #NO!! next if $cust_pkg->cancel;
2087 next if $cust_pkg->getfield('cancel');
2089 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2091 #? to avoid use of uninitialized value errors... ?
2092 $cust_pkg->setfield('bill', '')
2093 unless defined($cust_pkg->bill);
2095 my $part_pkg = $cust_pkg->part_pkg;
2097 my %hash = $cust_pkg->hash;
2098 my $old_cust_pkg = new FS::cust_pkg \%hash;
2107 if ( ! $cust_pkg->setup &&
2109 ( $conf->exists('disable_setup_suspended_pkgs') &&
2110 ! $cust_pkg->getfield('susp')
2111 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2113 || $options{'resetup'}
2116 warn " bill setup\n" if $DEBUG > 1;
2118 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2120 $dbh->rollback if $oldAutoCommit;
2121 return "$@ running calc_setup for $cust_pkg\n";
2124 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
2128 # bill recurring fee
2133 if ( $part_pkg->getfield('freq') ne '0' &&
2134 ! $cust_pkg->getfield('susp') &&
2135 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2138 # XXX should this be a package event? probably. events are called
2139 # at collection time at the moment, though...
2140 if ( $part_pkg->can('reset_usage') ) {
2141 warn " resetting usage counters" if $DEBUG > 1;
2142 $part_pkg->reset_usage($cust_pkg);
2145 warn " bill recur\n" if $DEBUG > 1;
2147 # XXX shared with $recur_prog
2148 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2150 #over two params! lets at least switch to a hashref for the rest...
2151 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
2153 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2155 $dbh->rollback if $oldAutoCommit;
2156 return "$@ running calc_recur for $cust_pkg\n";
2159 #change this bit to use Date::Manip? CAREFUL with timezones (see
2160 # mailing list archive)
2161 my ($sec,$min,$hour,$mday,$mon,$year) =
2162 (localtime($sdate) )[0,1,2,3,4,5];
2164 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2165 # only for figuring next bill date, nothing else, so, reset $sdate again
2167 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2168 $cust_pkg->last_bill($sdate);
2170 if ( $part_pkg->freq =~ /^\d+$/ ) {
2171 $mon += $part_pkg->freq;
2172 until ( $mon < 12 ) { $mon -= 12; $year++; }
2173 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2175 $mday += $weeks * 7;
2176 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2179 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2183 $dbh->rollback if $oldAutoCommit;
2184 return "unparsable frequency: ". $part_pkg->freq;
2186 $cust_pkg->setfield('bill',
2187 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2190 warn "\$setup is undefined" unless defined($setup);
2191 warn "\$recur is undefined" unless defined($recur);
2192 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2195 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2198 if ( $cust_pkg->modified ) { # hmmm.. and if the options are modified?
2200 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2203 $error=$cust_pkg->replace($old_cust_pkg,
2204 options => { $cust_pkg->options },
2206 if ( $error ) { #just in case
2207 $dbh->rollback if $oldAutoCommit;
2208 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2211 $setup = sprintf( "%.2f", $setup );
2212 $recur = sprintf( "%.2f", $recur );
2213 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2214 $dbh->rollback if $oldAutoCommit;
2215 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2217 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2218 $dbh->rollback if $oldAutoCommit;
2219 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2222 if ( $setup != 0 || $recur != 0 ) {
2224 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2226 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2227 'invnum' => $invnum,
2228 'pkgnum' => $cust_pkg->pkgnum,
2232 'edate' => $cust_pkg->bill,
2233 'details' => \@details,
2235 $error = $cust_bill_pkg->insert;
2237 $dbh->rollback if $oldAutoCommit;
2238 return "can't create invoice line item for invoice #$invnum: $error";
2240 $total_setup += $setup;
2241 $total_recur += $recur;
2247 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2250 my @taxoverrides = $part_pkg->part_pkg_taxoverride;
2253 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2257 if ( $conf->exists('enable_taxproducts')
2258 && (scalar(@taxoverrides) || $part_pkg->taxproductnum )
2262 my @taxclassnums = ();
2263 my $geocode = $self->geocode('cch');
2265 if ( scalar( @taxoverrides ) ) {
2266 @taxclassnums = map { $_->taxclassnum } @taxoverrides;
2267 }elsif ( $part_pkg->taxproductnum ) {
2268 @taxclassnums = map { $_->taxclassnum }
2269 $part_pkg->part_pkg_taxrate('cch', $geocode);
2274 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2276 @taxes = qsearch({ 'table' => 'tax_rate',
2277 'hashref' => { 'geocode' => $geocode, },
2278 'extra_sql' => $extra_sql,
2280 if scalar(@taxclassnums);
2285 my %taxhash = map { $_ => $self->get("$prefix$_") }
2286 qw( state county country );
2288 $taxhash{'taxclass'} = $part_pkg->taxclass;
2290 @taxes = qsearch( 'cust_main_county', \%taxhash );
2293 $taxhash{'taxclass'} = '';
2294 @taxes = qsearch( 'cust_main_county', \%taxhash );
2297 #one more try at a whole-country tax rate
2299 $taxhash{$_} = '' foreach qw( state county );
2300 @taxes = qsearch( 'cust_main_county', \%taxhash );
2303 } #if $conf->exists('enable_taxproducts')
2305 # maybe eliminate this entirely, along with all the 0% records
2307 $dbh->rollback if $oldAutoCommit;
2309 if ( $conf->exists('enable_taxproducts') ) {
2311 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2312 join('/', ( map $self->get("$prefix$_"),
2315 $part_pkg->taxproduct_description,
2316 $part_pkg->pkgpart ). "\n";
2319 "fatal: can't find tax rate for state/county/country/taxclass ".
2320 join('/', ( map $self->get("$prefix$_"),
2321 qw(state county country)
2323 $part_pkg->taxclass ). "\n";
2328 foreach my $tax ( @taxes ) {
2329 my $taxname = ref( $tax ). ' '. $tax->taxnum;
2330 if ( exists( $taxlisthash{ $taxname } ) ) {
2331 push @{ $taxlisthash{ $taxname } }, $cust_bill_pkg;
2333 $taxlisthash{ $taxname } = [ $tax, $cust_bill_pkg ];
2338 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2340 } #if $setup != 0 || $recur != 0
2342 } #if $cust_pkg->modified
2344 } #foreach my $cust_pkg
2346 unless ( $cust_bill->cust_bill_pkg ) {
2347 $cust_bill->delete; #don't create an invoice w/o line items
2349 # XXX this seems to be broken
2350 #( DBD::Pg::st execute failed: ERROR: syntax error at or near "hcb" )
2351 # # get rid of our fake history too, waste of unecessary space
2352 # my $h_cleanup_query = q{
2353 # DELETE FROM h_cust_bill hcb
2354 # WHERE hcb.invnum = ?
2355 # AND NOT EXISTS ( SELECT 1 FROM cust_bill cb where cb.invnum = hcb.invnum )
2357 # my $h_sth = $dbh->prepare($h_cleanup_query);
2358 # $h_sth->execute($invnum);
2360 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2364 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2366 foreach my $tax ( keys %taxlisthash ) {
2367 my $tax_object = shift @{ $taxlisthash{$tax} };
2368 my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2369 unless (ref($listref_or_error)) {
2370 $dbh->rollback if $oldAutoCommit;
2371 return $listref_or_error;
2374 $tax{ $listref_or_error->[0] } += $listref_or_error->[1];
2378 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2379 my $tax = sprintf("%.2f", $tax{$taxname} );
2380 $charged = sprintf( "%.2f", $charged+$tax );
2382 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2383 'invnum' => $invnum,
2389 'itemdesc' => $taxname,
2391 $error = $cust_bill_pkg->insert;
2393 $dbh->rollback if $oldAutoCommit;
2394 return "can't create invoice line item for invoice #$invnum: $error";
2396 $total_setup += $tax;
2400 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2401 $error = $cust_bill->replace;
2403 $dbh->rollback if $oldAutoCommit;
2404 return "can't update charged for invoice #$invnum: $error";
2407 foreach my $hook ( @precommit_hooks ) {
2409 &{$hook}; #($self) ?
2412 $dbh->rollback if $oldAutoCommit;
2413 return "$@ running precommit hook $hook\n";
2417 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2421 =item collect OPTIONS
2423 (Attempt to) collect money for this customer's outstanding invoices (see
2424 L<FS::cust_bill>). Usually used after the bill method.
2426 Actions are now triggered by billing events; see L<FS::part_event> and the
2427 billing events web interface. Old-style invoice events (see
2428 L<FS::part_bill_event>) have been deprecated.
2430 If there is an error, returns the error, otherwise returns false.
2432 Options are passed as name-value pairs.
2434 Currently available options are:
2440 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.
2444 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2448 set true to surpress email card/ACH decline notices.
2452 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2456 allows for one time override of normal customer billing method
2460 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)
2468 my( $self, %options ) = @_;
2469 my $invoice_time = $options{'invoice_time'} || time;
2472 local $SIG{HUP} = 'IGNORE';
2473 local $SIG{INT} = 'IGNORE';
2474 local $SIG{QUIT} = 'IGNORE';
2475 local $SIG{TERM} = 'IGNORE';
2476 local $SIG{TSTP} = 'IGNORE';
2477 local $SIG{PIPE} = 'IGNORE';
2479 my $oldAutoCommit = $FS::UID::AutoCommit;
2480 local $FS::UID::AutoCommit = 0;
2483 $self->select_for_update; #mutex
2486 my $balance = $self->balance;
2487 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2490 if ( exists($options{'retry_card'}) ) {
2491 carp 'retry_card option passed to collect is deprecated; use retry';
2492 $options{'retry'} ||= $options{'retry_card'};
2494 if ( exists($options{'retry'}) && $options{'retry'} ) {
2495 my $error = $self->retry_realtime;
2497 $dbh->rollback if $oldAutoCommit;
2502 # false laziness w/pay_batch::import_results
2504 my $due_cust_event = $self->due_cust_event(
2505 'debug' => ( $options{'debug'} || 0 ),
2506 'time' => $invoice_time,
2507 'check_freq' => $options{'check_freq'},
2509 unless( ref($due_cust_event) ) {
2510 $dbh->rollback if $oldAutoCommit;
2511 return $due_cust_event;
2514 foreach my $cust_event ( @$due_cust_event ) {
2518 #re-eval event conditions (a previous event could have changed things)
2519 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2520 #don't leave stray "new/locked" records around
2521 my $error = $cust_event->delete;
2523 #gah, even with transactions
2524 $dbh->commit if $oldAutoCommit; #well.
2531 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2532 warn " running cust_event ". $cust_event->eventnum. "\n"
2536 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2537 if ( my $error = $cust_event->do_event() ) {
2538 #XXX wtf is this? figure out a proper dealio with return value
2540 # gah, even with transactions.
2541 $dbh->commit if $oldAutoCommit; #well.
2548 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2553 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2555 Inserts database records for and returns an ordered listref of new events due
2556 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2557 events are due, an empty listref is returned. If there is an error, returns a
2558 scalar error message.
2560 To actually run the events, call each event's test_condition method, and if
2561 still true, call the event's do_event method.
2563 Options are passed as a hashref or as a list of name-value pairs. Available
2570 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.
2574 "Current time" for the events.
2578 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)
2582 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2586 Explicitly pass the objects to be tested (typically used with eventtable).
2592 sub due_cust_event {
2594 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2597 #my $DEBUG = $opt{'debug'}
2598 local($DEBUG) = $opt{'debug'}
2599 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2601 warn "$me due_cust_event called with options ".
2602 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2605 $opt{'time'} ||= time;
2607 local $SIG{HUP} = 'IGNORE';
2608 local $SIG{INT} = 'IGNORE';
2609 local $SIG{QUIT} = 'IGNORE';
2610 local $SIG{TERM} = 'IGNORE';
2611 local $SIG{TSTP} = 'IGNORE';
2612 local $SIG{PIPE} = 'IGNORE';
2614 my $oldAutoCommit = $FS::UID::AutoCommit;
2615 local $FS::UID::AutoCommit = 0;
2618 $self->select_for_update; #mutex
2621 # 1: find possible events (initial search)
2624 my @cust_event = ();
2626 my @eventtable = $opt{'eventtable'}
2627 ? ( $opt{'eventtable'} )
2628 : FS::part_event->eventtables_runorder;
2630 foreach my $eventtable ( @eventtable ) {
2633 if ( $opt{'objects'} ) {
2635 @objects = @{ $opt{'objects'} };
2639 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2640 @objects = ( $eventtable eq 'cust_main' )
2642 : ( $self->$eventtable() );
2646 my @e_cust_event = ();
2648 my $cross = "CROSS JOIN $eventtable";
2649 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2650 unless $eventtable eq 'cust_main';
2652 foreach my $object ( @objects ) {
2654 #this first search uses the condition_sql magic for optimization.
2655 #the more possible events we can eliminate in this step the better
2657 my $cross_where = '';
2658 my $pkey = $object->primary_key;
2659 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2661 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2663 FS::part_event_condition->where_conditions_sql( $eventtable,
2664 'time'=>$opt{'time'}
2666 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2668 $extra_sql = "AND $extra_sql" if $extra_sql;
2670 #here is the agent virtualization
2671 $extra_sql .= " AND ( part_event.agentnum IS NULL
2672 OR part_event.agentnum = ". $self->agentnum. ' )';
2674 $extra_sql .= " $order";
2676 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2677 if $opt{'debug'} > 2;
2678 my @part_event = qsearch( {
2679 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2680 'select' => 'part_event.*',
2681 'table' => 'part_event',
2682 'addl_from' => "$cross $join",
2683 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2684 'eventtable' => $eventtable,
2687 'extra_sql' => "AND $cross_where $extra_sql",
2691 my $pkey = $object->primary_key;
2692 warn " ". scalar(@part_event).
2693 " possible events found for $eventtable ". $object->$pkey(). "\n";
2696 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2700 warn " ". scalar(@e_cust_event).
2701 " subtotal possible cust events found for $eventtable\n"
2704 push @cust_event, @e_cust_event;
2708 warn " ". scalar(@cust_event).
2709 " total possible cust events found in initial search\n"
2713 # 2: test conditions
2718 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
2719 'stats_hashref' => \%unsat ),
2722 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
2725 warn " invalid conditions not eliminated with condition_sql:\n".
2726 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
2733 foreach my $cust_event ( @cust_event ) {
2735 my $error = $cust_event->insert();
2737 $dbh->rollback if $oldAutoCommit;
2743 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2749 warn " returning events: ". Dumper(@cust_event). "\n"
2756 =item retry_realtime
2758 Schedules realtime / batch credit card / electronic check / LEC billing
2759 events for for retry. Useful if card information has changed or manual
2760 retry is desired. The 'collect' method must be called to actually retry
2763 Implementation details: For either this customer, or for each of this
2764 customer's open invoices, changes the status of the first "done" (with
2765 statustext error) realtime processing event to "failed".
2769 sub retry_realtime {
2772 local $SIG{HUP} = 'IGNORE';
2773 local $SIG{INT} = 'IGNORE';
2774 local $SIG{QUIT} = 'IGNORE';
2775 local $SIG{TERM} = 'IGNORE';
2776 local $SIG{TSTP} = 'IGNORE';
2777 local $SIG{PIPE} = 'IGNORE';
2779 my $oldAutoCommit = $FS::UID::AutoCommit;
2780 local $FS::UID::AutoCommit = 0;
2783 #a little false laziness w/due_cust_event (not too bad, really)
2785 my $join = FS::part_event_condition->join_conditions_sql;
2786 my $order = FS::part_event_condition->order_conditions_sql;
2789 . join ( ' OR ' , map {
2790 "( part_event.eventtable = " . dbh->quote($_)
2791 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
2792 } FS::part_event->eventtables)
2795 #here is the agent virtualization
2796 my $agent_virt = " ( part_event.agentnum IS NULL
2797 OR part_event.agentnum = ". $self->agentnum. ' )';
2799 #XXX this shouldn't be hardcoded, actions should declare it...
2800 my @realtime_events = qw(
2801 cust_bill_realtime_card
2802 cust_bill_realtime_check
2803 cust_bill_realtime_lec
2807 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
2812 my @cust_event = qsearchs({
2813 'table' => 'cust_event',
2814 'select' => 'cust_event.*',
2815 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
2816 'hashref' => { 'status' => 'done' },
2817 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
2818 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
2821 my %seen_invnum = ();
2822 foreach my $cust_event (@cust_event) {
2824 #max one for the customer, one for each open invoice
2825 my $cust_X = $cust_event->cust_X;
2826 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
2830 or $cust_event->part_event->eventtable eq 'cust_bill'
2833 my $error = $cust_event->retry;
2835 $dbh->rollback if $oldAutoCommit;
2836 return "error scheduling event for retry: $error";
2841 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2846 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2848 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2849 via a Business::OnlinePayment realtime gateway. See
2850 L<http://420.am/business-onlinepayment> for supported gateways.
2852 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2854 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
2856 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2857 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2858 if set, will override the value from the customer record.
2860 I<description> is a free-text field passed to the gateway. It defaults to
2861 "Internet services".
2863 If an I<invnum> is specified, this payment (if successful) is applied to the
2864 specified invoice. If you don't specify an I<invnum> you might want to
2865 call the B<apply_payments> method.
2867 I<quiet> can be set true to surpress email decline notices.
2869 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
2870 resulting paynum, if any.
2872 I<payunique> is a unique identifier for this payment.
2874 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2879 my( $self, $method, $amount, %options ) = @_;
2881 warn "$me realtime_bop: $method $amount\n";
2882 warn " $_ => $options{$_}\n" foreach keys %options;
2885 $options{'description'} ||= 'Internet services';
2887 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
2889 eval "use Business::OnlinePayment";
2892 my $payinfo = exists($options{'payinfo'})
2893 ? $options{'payinfo'}
2896 my %method2payby = (
2903 # check for banned credit card/ACH
2906 my $ban = qsearchs('banned_pay', {
2907 'payby' => $method2payby{$method},
2908 'payinfo' => md5_base64($payinfo),
2910 return "Banned credit card" if $ban;
2917 if ( $options{'invnum'} ) {
2918 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2919 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2921 map { $_->part_pkg->taxclass }
2923 map { $_->cust_pkg }
2924 $cust_bill->cust_bill_pkg;
2925 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2926 #different taxclasses
2927 $taxclass = $taxclasses[0];
2931 #look for an agent gateway override first
2933 if ( $method eq 'CC' ) {
2934 $cardtype = cardtype($payinfo);
2935 } elsif ( $method eq 'ECHECK' ) {
2938 $cardtype = $method;
2942 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2943 cardtype => $cardtype,
2944 taxclass => $taxclass, } )
2945 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2947 taxclass => $taxclass, } )
2948 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2949 cardtype => $cardtype,
2951 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2953 taxclass => '', } );
2955 my $payment_gateway = '';
2956 my( $processor, $login, $password, $action, @bop_options );
2957 if ( $override ) { #use a payment gateway override
2959 $payment_gateway = $override->payment_gateway;
2961 $processor = $payment_gateway->gateway_module;
2962 $login = $payment_gateway->gateway_username;
2963 $password = $payment_gateway->gateway_password;
2964 $action = $payment_gateway->gateway_action;
2965 @bop_options = $payment_gateway->options;
2967 } else { #use the standard settings from the config
2969 ( $processor, $login, $password, $action, @bop_options ) =
2970 $self->default_payment_gateway($method);
2978 my $address = exists($options{'address1'})
2979 ? $options{'address1'}
2981 my $address2 = exists($options{'address2'})
2982 ? $options{'address2'}
2984 $address .= ", ". $address2 if length($address2);
2986 my $o_payname = exists($options{'payname'})
2987 ? $options{'payname'}
2989 my($payname, $payfirst, $paylast);
2990 if ( $o_payname && $method ne 'ECHECK' ) {
2991 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2992 or return "Illegal payname $payname";
2993 ($payfirst, $paylast) = ($1, $2);
2995 $payfirst = $self->getfield('first');
2996 $paylast = $self->getfield('last');
2997 $payname = "$payfirst $paylast";
3000 my @invoicing_list = $self->invoicing_list_emailonly;
3001 if ( $conf->exists('emailinvoiceautoalways')
3002 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3003 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3004 push @invoicing_list, $self->all_emails;
3007 my $email = ($conf->exists('business-onlinepayment-email-override'))
3008 ? $conf->config('business-onlinepayment-email-override')
3009 : $invoicing_list[0];
3013 my $payip = exists($options{'payip'})
3016 $content{customer_ip} = $payip
3019 $content{invoice_number} = $options{'invnum'}
3020 if exists($options{'invnum'}) && length($options{'invnum'});
3022 $content{email_customer} =
3023 ( $conf->exists('business-onlinepayment-email_customer')
3024 || $conf->exists('business-onlinepayment-email-override') );
3027 if ( $method eq 'CC' ) {
3029 $content{card_number} = $payinfo;
3030 $paydate = exists($options{'paydate'})
3031 ? $options{'paydate'}
3033 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3034 $content{expiration} = "$2/$1";
3036 my $paycvv = exists($options{'paycvv'})
3037 ? $options{'paycvv'}
3039 $content{cvv2} = $paycvv
3042 my $paystart_month = exists($options{'paystart_month'})
3043 ? $options{'paystart_month'}
3044 : $self->paystart_month;
3046 my $paystart_year = exists($options{'paystart_year'})
3047 ? $options{'paystart_year'}
3048 : $self->paystart_year;
3050 $content{card_start} = "$paystart_month/$paystart_year"
3051 if $paystart_month && $paystart_year;
3053 my $payissue = exists($options{'payissue'})
3054 ? $options{'payissue'}
3056 $content{issue_number} = $payissue if $payissue;
3058 $content{recurring_billing} = 'YES'
3059 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3061 'payinfo' => $payinfo,
3063 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3065 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3069 } elsif ( $method eq 'ECHECK' ) {
3070 ( $content{account_number}, $content{routing_code} ) =
3071 split('@', $payinfo);
3072 $content{bank_name} = $o_payname;
3073 $content{bank_state} = exists($options{'paystate'})
3074 ? $options{'paystate'}
3075 : $self->getfield('paystate');
3076 $content{account_type} = exists($options{'paytype'})
3077 ? uc($options{'paytype'}) || 'CHECKING'
3078 : uc($self->getfield('paytype')) || 'CHECKING';
3079 $content{account_name} = $payname;
3080 $content{customer_org} = $self->company ? 'B' : 'I';
3081 $content{state_id} = exists($options{'stateid'})
3082 ? $options{'stateid'}
3083 : $self->getfield('stateid');
3084 $content{state_id_state} = exists($options{'stateid_state'})
3085 ? $options{'stateid_state'}
3086 : $self->getfield('stateid_state');
3087 $content{customer_ssn} = exists($options{'ss'})
3090 } elsif ( $method eq 'LEC' ) {
3091 $content{phone} = $payinfo;
3095 # run transaction(s)
3098 my $balance = exists( $options{'balance'} )
3099 ? $options{'balance'}
3102 $self->select_for_update; #mutex ... just until we get our pending record in
3104 #the checks here are intended to catch concurrent payments
3105 #double-form-submission prevention is taken care of in cust_pay_pending::check
3108 return "The customer's balance has changed; $method transaction aborted."
3109 if $self->balance < $balance;
3110 #&& $self->balance < $amount; #might as well anyway?
3112 #also check and make sure there aren't *other* pending payments for this cust
3114 my @pending = qsearch('cust_pay_pending', {
3115 'custnum' => $self->custnum,
3116 'status' => { op=>'!=', value=>'done' }
3118 return "A payment is already being processed for this customer (".
3119 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3120 "); $method transaction aborted."
3121 if scalar(@pending);
3123 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3125 my $cust_pay_pending = new FS::cust_pay_pending {
3126 'custnum' => $self->custnum,
3127 #'invnum' => $options{'invnum'},
3130 'payby' => $method2payby{$method},
3131 'payinfo' => $payinfo,
3132 'paydate' => $paydate,
3134 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3136 $cust_pay_pending->payunique( $options{payunique} )
3137 if defined($options{payunique}) && length($options{payunique});
3138 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3139 return $cpp_new_err if $cpp_new_err;
3141 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3143 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3144 $transaction->content(
3147 'password' => $password,
3148 'action' => $action1,
3149 'description' => $options{'description'},
3150 'amount' => $amount,
3151 #'invoice_number' => $options{'invnum'},
3152 'customer_id' => $self->custnum,
3153 'last_name' => $paylast,
3154 'first_name' => $payfirst,
3156 'address' => $address,
3157 'city' => ( exists($options{'city'})
3160 'state' => ( exists($options{'state'})
3163 'zip' => ( exists($options{'zip'})
3166 'country' => ( exists($options{'country'})
3167 ? $options{'country'}
3169 'referer' => 'http://cleanwhisker.420.am/',
3171 'phone' => $self->daytime || $self->night,
3175 $cust_pay_pending->status('pending');
3176 my $cpp_pending_err = $cust_pay_pending->replace;
3177 return $cpp_pending_err if $cpp_pending_err;
3180 my $BOP_TESTING = 0;
3181 my $BOP_TESTING_SUCCESS = 1;
3183 unless ( $BOP_TESTING ) {
3184 $transaction->submit();
3186 if ( $BOP_TESTING_SUCCESS ) {
3187 $transaction->is_success(1);
3188 $transaction->authorization('fake auth');
3190 $transaction->is_success(0);
3191 $transaction->error_message('fake failure');
3195 if ( $transaction->is_success() && $action2 ) {
3197 $cust_pay_pending->status('authorized');
3198 my $cpp_authorized_err = $cust_pay_pending->replace;
3199 return $cpp_authorized_err if $cpp_authorized_err;
3201 my $auth = $transaction->authorization;
3202 my $ordernum = $transaction->can('order_number')
3203 ? $transaction->order_number
3207 new Business::OnlinePayment( $processor, @bop_options );
3214 password => $password,
3215 order_number => $ordernum,
3217 authorization => $auth,
3218 description => $options{'description'},
3221 foreach my $field (qw( authorization_source_code returned_ACI
3222 transaction_identifier validation_code
3223 transaction_sequence_num local_transaction_date
3224 local_transaction_time AVS_result_code )) {
3225 $capture{$field} = $transaction->$field() if $transaction->can($field);
3228 $capture->content( %capture );
3232 unless ( $capture->is_success ) {
3233 my $e = "Authorization successful but capture failed, custnum #".
3234 $self->custnum. ': '. $capture->result_code.
3235 ": ". $capture->error_message;
3242 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3243 my $cpp_captured_err = $cust_pay_pending->replace;
3244 return $cpp_captured_err if $cpp_captured_err;
3247 # remove paycvv after initial transaction
3250 #false laziness w/misc/process/payment.cgi - check both to make sure working
3252 if ( defined $self->dbdef_table->column('paycvv')
3253 && length($self->paycvv)
3254 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3256 my $error = $self->remove_cvv;
3258 warn "WARNING: error removing cvv: $error\n";
3266 if ( $transaction->is_success() ) {
3269 if ( $payment_gateway ) { # agent override
3270 $paybatch = $payment_gateway->gatewaynum. '-';
3273 $paybatch .= "$processor:". $transaction->authorization;
3275 $paybatch .= ':'. $transaction->order_number
3276 if $transaction->can('order_number')
3277 && length($transaction->order_number);
3279 my $cust_pay = new FS::cust_pay ( {
3280 'custnum' => $self->custnum,
3281 'invnum' => $options{'invnum'},
3284 'payby' => $method2payby{$method},
3285 'payinfo' => $payinfo,
3286 'paybatch' => $paybatch,
3287 'paydate' => $paydate,
3289 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3290 $cust_pay->payunique( $options{payunique} )
3291 if defined($options{payunique}) && length($options{payunique});
3293 my $oldAutoCommit = $FS::UID::AutoCommit;
3294 local $FS::UID::AutoCommit = 0;
3297 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3299 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3302 $cust_pay->invnum(''); #try again with no specific invnum
3303 my $error2 = $cust_pay->insert( $options{'manual'} ?
3304 ( 'manual' => 1 ) : ()
3307 # gah. but at least we have a record of the state we had to abort in
3308 # from cust_pay_pending now.
3309 my $e = "WARNING: $method captured but payment not recorded - ".
3310 "error inserting payment ($processor): $error2".
3311 " (previously tried insert with invnum #$options{'invnum'}" .
3312 ": $error ) - pending payment saved as paypendingnum ".
3313 $cust_pay_pending->paypendingnum. "\n";
3319 if ( $options{'paynum_ref'} ) {
3320 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3323 $cust_pay_pending->status('done');
3324 $cust_pay_pending->statustext('captured');
3325 my $cpp_done_err = $cust_pay_pending->replace;
3327 if ( $cpp_done_err ) {
3329 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3330 my $e = "WARNING: $method captured but payment not recorded - ".
3331 "error updating status for paypendingnum ".
3332 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3338 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3339 return ''; #no error
3345 my $perror = "$processor error: ". $transaction->error_message;
3347 unless ( $transaction->error_message ) {
3350 if ( $transaction->can('response_page') ) {
3352 'page' => ( $transaction->can('response_page')
3353 ? $transaction->response_page
3356 'code' => ( $transaction->can('response_code')
3357 ? $transaction->response_code
3360 'headers' => ( $transaction->can('response_headers')
3361 ? $transaction->response_headers
3367 "No additional debugging information available for $processor";
3370 $perror .= "No error_message returned from $processor -- ".
3371 ( ref($t_response) ? Dumper($t_response) : $t_response );
3375 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3376 && $conf->exists('emaildecline')
3377 && grep { $_ ne 'POST' } $self->invoicing_list
3378 && ! grep { $transaction->error_message =~ /$_/ }
3379 $conf->config('emaildecline-exclude')
3381 my @templ = $conf->config('declinetemplate');
3382 my $template = new Text::Template (
3384 SOURCE => [ map "$_\n", @templ ],
3385 ) or return "($perror) can't create template: $Text::Template::ERROR";
3386 $template->compile()
3387 or return "($perror) can't compile template: $Text::Template::ERROR";
3389 my $templ_hash = { error => $transaction->error_message };
3391 my $error = send_email(
3392 'from' => $conf->config('invoice_from'),
3393 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3394 'subject' => 'Your payment could not be processed',
3395 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3398 $perror .= " (also received error sending decline notification: $error)"
3403 $cust_pay_pending->status('done');
3404 $cust_pay_pending->statustext("declined: $perror");
3405 my $cpp_done_err = $cust_pay_pending->replace;
3406 if ( $cpp_done_err ) {
3407 my $e = "WARNING: $method declined but pending payment not resolved - ".
3408 "error updating status for paypendingnum ".
3409 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3411 $perror = "$e ($perror)";
3424 my( $self, $method, $amount, %options ) = @_;
3426 if ( $options{'fake_failure'} ) {
3427 return "Error: No error; test failure requested with fake_failure";
3430 my %method2payby = (
3437 #if ( $payment_gateway ) { # agent override
3438 # $paybatch = $payment_gateway->gatewaynum. '-';
3441 #$paybatch .= "$processor:". $transaction->authorization;
3443 #$paybatch .= ':'. $transaction->order_number
3444 # if $transaction->can('order_number')
3445 # && length($transaction->order_number);
3447 my $paybatch = 'FakeProcessor:54:32';
3449 my $cust_pay = new FS::cust_pay ( {
3450 'custnum' => $self->custnum,
3451 'invnum' => $options{'invnum'},
3454 'payby' => $method2payby{$method},
3455 #'payinfo' => $payinfo,
3456 'payinfo' => '4111111111111111',
3457 'paybatch' => $paybatch,
3458 #'paydate' => $paydate,
3459 'paydate' => '2012-05-01',
3461 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3463 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3466 $cust_pay->invnum(''); #try again with no specific invnum
3467 my $error2 = $cust_pay->insert( $options{'manual'} ?
3468 ( 'manual' => 1 ) : ()
3471 # gah, even with transactions.
3472 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3473 "error inserting (fake!) payment: $error2".
3474 " (previously tried insert with invnum #$options{'invnum'}" .
3481 if ( $options{'paynum_ref'} ) {
3482 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3485 return ''; #no error
3489 =item default_payment_gateway
3493 sub default_payment_gateway {
3494 my( $self, $method ) = @_;
3496 die "Real-time processing not enabled\n"
3497 unless $conf->exists('business-onlinepayment');
3500 my $bop_config = 'business-onlinepayment';
3501 $bop_config .= '-ach'
3502 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3503 my ( $processor, $login, $password, $action, @bop_options ) =
3504 $conf->config($bop_config);
3505 $action ||= 'normal authorization';
3506 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3507 die "No real-time processor is enabled - ".
3508 "did you set the business-onlinepayment configuration value?\n"
3511 ( $processor, $login, $password, $action, @bop_options )
3516 Removes the I<paycvv> field from the database directly.
3518 If there is an error, returns the error, otherwise returns false.
3524 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3525 or return dbh->errstr;
3526 $sth->execute($self->custnum)
3527 or return $sth->errstr;
3532 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3534 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3535 via a Business::OnlinePayment realtime gateway. See
3536 L<http://420.am/business-onlinepayment> for supported gateways.
3538 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3540 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3542 Most gateways require a reference to an original payment transaction to refund,
3543 so you probably need to specify a I<paynum>.
3545 I<amount> defaults to the original amount of the payment if not specified.
3547 I<reason> specifies a reason for the refund.
3549 I<paydate> specifies the expiration date for a credit card overriding the
3550 value from the customer record or the payment record. Specified as yyyy-mm-dd
3552 Implementation note: If I<amount> is unspecified or equal to the amount of the
3553 orignal payment, first an attempt is made to "void" the transaction via
3554 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3555 the normal attempt is made to "refund" ("credit") the transaction via the
3556 gateway is attempted.
3558 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3559 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3560 #if set, will override the value from the customer record.
3562 #If an I<invnum> is specified, this payment (if successful) is applied to the
3563 #specified invoice. If you don't specify an I<invnum> you might want to
3564 #call the B<apply_payments> method.
3568 #some false laziness w/realtime_bop, not enough to make it worth merging
3569 #but some useful small subs should be pulled out
3570 sub realtime_refund_bop {
3571 my( $self, $method, %options ) = @_;
3573 warn "$me realtime_refund_bop: $method refund\n";
3574 warn " $_ => $options{$_}\n" foreach keys %options;
3577 eval "use Business::OnlinePayment";
3581 # look up the original payment and optionally a gateway for that payment
3585 my $amount = $options{'amount'};
3587 my( $processor, $login, $password, @bop_options ) ;
3588 my( $auth, $order_number ) = ( '', '', '' );
3590 if ( $options{'paynum'} ) {
3592 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3593 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3594 or return "Unknown paynum $options{'paynum'}";
3595 $amount ||= $cust_pay->paid;
3597 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3598 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3599 $cust_pay->paybatch;
3600 my $gatewaynum = '';
3601 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3603 if ( $gatewaynum ) { #gateway for the payment to be refunded
3605 my $payment_gateway =
3606 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3607 die "payment gateway $gatewaynum not found"
3608 unless $payment_gateway;
3610 $processor = $payment_gateway->gateway_module;
3611 $login = $payment_gateway->gateway_username;
3612 $password = $payment_gateway->gateway_password;
3613 @bop_options = $payment_gateway->options;
3615 } else { #try the default gateway
3617 my( $conf_processor, $unused_action );
3618 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3619 $self->default_payment_gateway($method);
3621 return "processor of payment $options{'paynum'} $processor does not".
3622 " match default processor $conf_processor"
3623 unless $processor eq $conf_processor;
3628 } else { # didn't specify a paynum, so look for agent gateway overrides
3629 # like a normal transaction
3632 if ( $method eq 'CC' ) {
3633 $cardtype = cardtype($self->payinfo);
3634 } elsif ( $method eq 'ECHECK' ) {
3637 $cardtype = $method;
3640 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3641 cardtype => $cardtype,
3643 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3645 taxclass => '', } );
3647 if ( $override ) { #use a payment gateway override
3649 my $payment_gateway = $override->payment_gateway;
3651 $processor = $payment_gateway->gateway_module;
3652 $login = $payment_gateway->gateway_username;
3653 $password = $payment_gateway->gateway_password;
3654 #$action = $payment_gateway->gateway_action;
3655 @bop_options = $payment_gateway->options;
3657 } else { #use the standard settings from the config
3660 ( $processor, $login, $password, $unused_action, @bop_options ) =
3661 $self->default_payment_gateway($method);
3666 return "neither amount nor paynum specified" unless $amount;
3671 'password' => $password,
3672 'order_number' => $order_number,
3673 'amount' => $amount,
3674 'referer' => 'http://cleanwhisker.420.am/',
3676 $content{authorization} = $auth
3677 if length($auth); #echeck/ACH transactions have an order # but no auth
3678 #(at least with authorize.net)
3680 my $disable_void_after;
3681 if ($conf->exists('disable_void_after')
3682 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3683 $disable_void_after = $1;
3686 #first try void if applicable
3687 if ( $cust_pay && $cust_pay->paid == $amount
3689 ( not defined($disable_void_after) )
3690 || ( time < ($cust_pay->_date + $disable_void_after ) )
3693 warn " attempting void\n" if $DEBUG > 1;
3694 my $void = new Business::OnlinePayment( $processor, @bop_options );
3695 $void->content( 'action' => 'void', %content );
3697 if ( $void->is_success ) {
3698 my $error = $cust_pay->void($options{'reason'});
3700 # gah, even with transactions.
3701 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3702 "error voiding payment: $error";
3706 warn " void successful\n" if $DEBUG > 1;
3711 warn " void unsuccessful, trying refund\n"
3715 my $address = $self->address1;
3716 $address .= ", ". $self->address2 if $self->address2;
3718 my($payname, $payfirst, $paylast);
3719 if ( $self->payname && $method ne 'ECHECK' ) {
3720 $payname = $self->payname;
3721 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3722 or return "Illegal payname $payname";
3723 ($payfirst, $paylast) = ($1, $2);
3725 $payfirst = $self->getfield('first');
3726 $paylast = $self->getfield('last');
3727 $payname = "$payfirst $paylast";
3730 my @invoicing_list = $self->invoicing_list_emailonly;
3731 if ( $conf->exists('emailinvoiceautoalways')
3732 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3733 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3734 push @invoicing_list, $self->all_emails;
3737 my $email = ($conf->exists('business-onlinepayment-email-override'))
3738 ? $conf->config('business-onlinepayment-email-override')
3739 : $invoicing_list[0];
3741 my $payip = exists($options{'payip'})
3744 $content{customer_ip} = $payip
3748 if ( $method eq 'CC' ) {
3751 $content{card_number} = $payinfo = $cust_pay->payinfo;
3752 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3753 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3754 ($content{expiration} = "$2/$1"); # where available
3756 $content{card_number} = $payinfo = $self->payinfo;
3757 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3758 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3759 $content{expiration} = "$2/$1";
3762 } elsif ( $method eq 'ECHECK' ) {
3765 $payinfo = $cust_pay->payinfo;
3767 $payinfo = $self->payinfo;
3769 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3770 $content{bank_name} = $self->payname;
3771 $content{account_type} = 'CHECKING';
3772 $content{account_name} = $payname;
3773 $content{customer_org} = $self->company ? 'B' : 'I';
3774 $content{customer_ssn} = $self->ss;
3775 } elsif ( $method eq 'LEC' ) {
3776 $content{phone} = $payinfo = $self->payinfo;
3780 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3781 my %sub_content = $refund->content(
3782 'action' => 'credit',
3783 'customer_id' => $self->custnum,
3784 'last_name' => $paylast,
3785 'first_name' => $payfirst,
3787 'address' => $address,
3788 'city' => $self->city,
3789 'state' => $self->state,
3790 'zip' => $self->zip,
3791 'country' => $self->country,
3793 'phone' => $self->daytime || $self->night,
3796 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3800 return "$processor error: ". $refund->error_message
3801 unless $refund->is_success();
3803 my %method2payby = (
3809 my $paybatch = "$processor:". $refund->authorization;
3810 $paybatch .= ':'. $refund->order_number
3811 if $refund->can('order_number') && $refund->order_number;
3813 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3814 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3815 last unless @cust_bill_pay;
3816 my $cust_bill_pay = pop @cust_bill_pay;
3817 my $error = $cust_bill_pay->delete;
3821 my $cust_refund = new FS::cust_refund ( {
3822 'custnum' => $self->custnum,
3823 'paynum' => $options{'paynum'},
3824 'refund' => $amount,
3826 'payby' => $method2payby{$method},
3827 'payinfo' => $payinfo,
3828 'paybatch' => $paybatch,
3829 'reason' => $options{'reason'} || 'card or ACH refund',
3831 my $error = $cust_refund->insert;
3833 $cust_refund->paynum(''); #try again with no specific paynum
3834 my $error2 = $cust_refund->insert;
3836 # gah, even with transactions.
3837 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3838 "error inserting refund ($processor): $error2".
3839 " (previously tried insert with paynum #$options{'paynum'}" .
3850 =item batch_card OPTION => VALUE...
3852 Adds a payment for this invoice to the pending credit card batch (see
3853 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3854 runs the payment using a realtime gateway.
3859 my ($self, %options) = @_;
3862 if (exists($options{amount})) {
3863 $amount = $options{amount};
3865 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3867 return '' unless $amount > 0;
3869 my $invnum = delete $options{invnum};
3870 my $payby = $options{invnum} || $self->payby; #dubious
3872 if ($options{'realtime'}) {
3873 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3879 my $oldAutoCommit = $FS::UID::AutoCommit;
3880 local $FS::UID::AutoCommit = 0;
3883 #this needs to handle mysql as well as Pg, like svc_acct.pm
3884 #(make it into a common function if folks need to do batching with mysql)
3885 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3886 or return "Cannot lock pay_batch: " . $dbh->errstr;
3890 'payby' => FS::payby->payby2payment($payby),
3893 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3895 unless ( $pay_batch ) {
3896 $pay_batch = new FS::pay_batch \%pay_batch;
3897 my $error = $pay_batch->insert;
3899 $dbh->rollback if $oldAutoCommit;
3900 die "error creating new batch: $error\n";
3904 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3905 'batchnum' => $pay_batch->batchnum,
3906 'custnum' => $self->custnum,
3909 foreach (qw( address1 address2 city state zip country payby payinfo paydate
3911 $options{$_} = '' unless exists($options{$_});
3914 my $cust_pay_batch = new FS::cust_pay_batch ( {
3915 'batchnum' => $pay_batch->batchnum,
3916 'invnum' => $invnum || 0, # is there a better value?
3917 # this field should be
3919 # cust_bill_pay_batch now
3920 'custnum' => $self->custnum,
3921 'last' => $self->getfield('last'),
3922 'first' => $self->getfield('first'),
3923 'address1' => $options{address1} || $self->address1,
3924 'address2' => $options{address2} || $self->address2,
3925 'city' => $options{city} || $self->city,
3926 'state' => $options{state} || $self->state,
3927 'zip' => $options{zip} || $self->zip,
3928 'country' => $options{country} || $self->country,
3929 'payby' => $options{payby} || $self->payby,
3930 'payinfo' => $options{payinfo} || $self->payinfo,
3931 'exp' => $options{paydate} || $self->paydate,
3932 'payname' => $options{payname} || $self->payname,
3933 'amount' => $amount, # consolidating
3936 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3937 if $old_cust_pay_batch;
3940 if ($old_cust_pay_batch) {
3941 $error = $cust_pay_batch->replace($old_cust_pay_batch)
3943 $error = $cust_pay_batch->insert;
3947 $dbh->rollback if $oldAutoCommit;
3951 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
3952 foreach my $cust_bill ($self->open_cust_bill) {
3953 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3954 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3955 'invnum' => $cust_bill->invnum,
3956 'paybatchnum' => $cust_pay_batch->paybatchnum,
3957 'amount' => $cust_bill->owed,
3960 if ($unapplied >= $cust_bill_pay_batch->amount){
3961 $unapplied -= $cust_bill_pay_batch->amount;
3964 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
3965 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
3967 $error = $cust_bill_pay_batch->insert;
3969 $dbh->rollback if $oldAutoCommit;
3974 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3980 Returns the total owed for this customer on all invoices
3981 (see L<FS::cust_bill/owed>).
3987 $self->total_owed_date(2145859200); #12/31/2037
3990 =item total_owed_date TIME
3992 Returns the total owed for this customer on all invoices with date earlier than
3993 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3994 see L<Time::Local> and L<Date::Parse> for conversion functions.
3998 sub total_owed_date {
4002 foreach my $cust_bill (
4003 grep { $_->_date <= $time }
4004 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4006 $total_bill += $cust_bill->owed;
4008 sprintf( "%.2f", $total_bill );
4011 =item apply_payments_and_credits
4013 Applies unapplied payments and credits.
4015 In most cases, this new method should be used in place of sequential
4016 apply_payments and apply_credits methods.
4018 If there is an error, returns the error, otherwise returns false.
4022 sub apply_payments_and_credits {
4025 local $SIG{HUP} = 'IGNORE';
4026 local $SIG{INT} = 'IGNORE';
4027 local $SIG{QUIT} = 'IGNORE';
4028 local $SIG{TERM} = 'IGNORE';
4029 local $SIG{TSTP} = 'IGNORE';
4030 local $SIG{PIPE} = 'IGNORE';
4032 my $oldAutoCommit = $FS::UID::AutoCommit;
4033 local $FS::UID::AutoCommit = 0;
4036 $self->select_for_update; #mutex
4038 foreach my $cust_bill ( $self->open_cust_bill ) {
4039 my $error = $cust_bill->apply_payments_and_credits;
4041 $dbh->rollback if $oldAutoCommit;
4042 return "Error applying: $error";
4046 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4051 =item apply_credits OPTION => VALUE ...
4053 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4054 to outstanding invoice balances in chronological order (or reverse
4055 chronological order if the I<order> option is set to B<newest>) and returns the
4056 value of any remaining unapplied credits available for refund (see
4057 L<FS::cust_refund>).
4059 Dies if there is an error.
4067 local $SIG{HUP} = 'IGNORE';
4068 local $SIG{INT} = 'IGNORE';
4069 local $SIG{QUIT} = 'IGNORE';
4070 local $SIG{TERM} = 'IGNORE';
4071 local $SIG{TSTP} = 'IGNORE';
4072 local $SIG{PIPE} = 'IGNORE';
4074 my $oldAutoCommit = $FS::UID::AutoCommit;
4075 local $FS::UID::AutoCommit = 0;
4078 $self->select_for_update; #mutex
4080 unless ( $self->total_credited ) {
4081 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4085 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4086 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4088 my @invoices = $self->open_cust_bill;
4089 @invoices = sort { $b->_date <=> $a->_date } @invoices
4090 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4093 foreach my $cust_bill ( @invoices ) {
4096 if ( !defined($credit) || $credit->credited == 0) {
4097 $credit = pop @credits or last;
4100 if ($cust_bill->owed >= $credit->credited) {
4101 $amount=$credit->credited;
4103 $amount=$cust_bill->owed;
4106 my $cust_credit_bill = new FS::cust_credit_bill ( {
4107 'crednum' => $credit->crednum,
4108 'invnum' => $cust_bill->invnum,
4109 'amount' => $amount,
4111 my $error = $cust_credit_bill->insert;
4113 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4117 redo if ($cust_bill->owed > 0);
4121 my $total_credited = $self->total_credited;
4123 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4125 return $total_credited;
4128 =item apply_payments
4130 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4131 to outstanding invoice balances in chronological order.
4133 #and returns the value of any remaining unapplied payments.
4135 Dies if there is an error.
4139 sub apply_payments {
4142 local $SIG{HUP} = 'IGNORE';
4143 local $SIG{INT} = 'IGNORE';
4144 local $SIG{QUIT} = 'IGNORE';
4145 local $SIG{TERM} = 'IGNORE';
4146 local $SIG{TSTP} = 'IGNORE';
4147 local $SIG{PIPE} = 'IGNORE';
4149 my $oldAutoCommit = $FS::UID::AutoCommit;
4150 local $FS::UID::AutoCommit = 0;
4153 $self->select_for_update; #mutex
4157 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4158 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4160 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4161 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4165 foreach my $cust_bill ( @invoices ) {
4168 if ( !defined($payment) || $payment->unapplied == 0 ) {
4169 $payment = pop @payments or last;
4172 if ( $cust_bill->owed >= $payment->unapplied ) {
4173 $amount = $payment->unapplied;
4175 $amount = $cust_bill->owed;
4178 my $cust_bill_pay = new FS::cust_bill_pay ( {
4179 'paynum' => $payment->paynum,
4180 'invnum' => $cust_bill->invnum,
4181 'amount' => $amount,
4183 my $error = $cust_bill_pay->insert;
4185 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4189 redo if ( $cust_bill->owed > 0);
4193 my $total_unapplied_payments = $self->total_unapplied_payments;
4195 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4197 return $total_unapplied_payments;
4200 =item total_credited
4202 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4203 customer. See L<FS::cust_credit/credited>.
4207 sub total_credited {
4209 my $total_credit = 0;
4210 foreach my $cust_credit ( qsearch('cust_credit', {
4211 'custnum' => $self->custnum,
4213 $total_credit += $cust_credit->credited;
4215 sprintf( "%.2f", $total_credit );
4218 =item total_unapplied_payments
4220 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4221 See L<FS::cust_pay/unapplied>.
4225 sub total_unapplied_payments {
4227 my $total_unapplied = 0;
4228 foreach my $cust_pay ( qsearch('cust_pay', {
4229 'custnum' => $self->custnum,
4231 $total_unapplied += $cust_pay->unapplied;
4233 sprintf( "%.2f", $total_unapplied );
4236 =item total_unapplied_refunds
4238 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4239 customer. See L<FS::cust_refund/unapplied>.
4243 sub total_unapplied_refunds {
4245 my $total_unapplied = 0;
4246 foreach my $cust_refund ( qsearch('cust_refund', {
4247 'custnum' => $self->custnum,
4249 $total_unapplied += $cust_refund->unapplied;
4251 sprintf( "%.2f", $total_unapplied );
4256 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4257 total_credited minus total_unapplied_payments).
4265 + $self->total_unapplied_refunds
4266 - $self->total_credited
4267 - $self->total_unapplied_payments
4271 =item balance_date TIME
4273 Returns the balance for this customer, only considering invoices with date
4274 earlier than TIME (total_owed_date minus total_credited minus
4275 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4276 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4285 $self->total_owed_date($time)
4286 + $self->total_unapplied_refunds
4287 - $self->total_credited
4288 - $self->total_unapplied_payments
4292 =item in_transit_payments
4294 Returns the total of requests for payments for this customer pending in
4295 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4299 sub in_transit_payments {
4301 my $in_transit_payments = 0;
4302 foreach my $pay_batch ( qsearch('pay_batch', {
4305 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4306 'batchnum' => $pay_batch->batchnum,
4307 'custnum' => $self->custnum,
4309 $in_transit_payments += $cust_pay_batch->amount;
4312 sprintf( "%.2f", $in_transit_payments );
4315 =item paydate_monthyear
4317 Returns a two-element list consisting of the month and year of this customer's
4318 paydate (credit card expiration date for CARD customers)
4322 sub paydate_monthyear {
4324 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4326 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4333 =item invoicing_list [ ARRAYREF ]
4335 If an arguement is given, sets these email addresses as invoice recipients
4336 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4337 (except as warnings), so use check_invoicing_list first.
4339 Returns a list of email addresses (with svcnum entries expanded).
4341 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4342 check it without disturbing anything by passing nothing.
4344 This interface may change in the future.
4348 sub invoicing_list {
4349 my( $self, $arrayref ) = @_;
4352 my @cust_main_invoice;
4353 if ( $self->custnum ) {
4354 @cust_main_invoice =
4355 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4357 @cust_main_invoice = ();
4359 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4360 #warn $cust_main_invoice->destnum;
4361 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4362 #warn $cust_main_invoice->destnum;
4363 my $error = $cust_main_invoice->delete;
4364 warn $error if $error;
4367 if ( $self->custnum ) {
4368 @cust_main_invoice =
4369 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4371 @cust_main_invoice = ();
4373 my %seen = map { $_->address => 1 } @cust_main_invoice;
4374 foreach my $address ( @{$arrayref} ) {
4375 next if exists $seen{$address} && $seen{$address};
4376 $seen{$address} = 1;
4377 my $cust_main_invoice = new FS::cust_main_invoice ( {
4378 'custnum' => $self->custnum,
4381 my $error = $cust_main_invoice->insert;
4382 warn $error if $error;
4386 if ( $self->custnum ) {
4388 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4395 =item check_invoicing_list ARRAYREF
4397 Checks these arguements as valid input for the invoicing_list method. If there
4398 is an error, returns the error, otherwise returns false.
4402 sub check_invoicing_list {
4403 my( $self, $arrayref ) = @_;
4405 foreach my $address ( @$arrayref ) {
4407 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4408 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4411 my $cust_main_invoice = new FS::cust_main_invoice ( {
4412 'custnum' => $self->custnum,
4415 my $error = $self->custnum
4416 ? $cust_main_invoice->check
4417 : $cust_main_invoice->checkdest
4419 return $error if $error;
4423 return "Email address required"
4424 if $conf->exists('cust_main-require_invoicing_list_email')
4425 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4430 =item set_default_invoicing_list
4432 Sets the invoicing list to all accounts associated with this customer,
4433 overwriting any previous invoicing list.
4437 sub set_default_invoicing_list {
4439 $self->invoicing_list($self->all_emails);
4444 Returns the email addresses of all accounts provisioned for this customer.
4451 foreach my $cust_pkg ( $self->all_pkgs ) {
4452 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4454 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4455 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4457 $list{$_}=1 foreach map { $_->email } @svc_acct;
4462 =item invoicing_list_addpost
4464 Adds postal invoicing to this customer. If this customer is already configured
4465 to receive postal invoices, does nothing.
4469 sub invoicing_list_addpost {
4471 return if grep { $_ eq 'POST' } $self->invoicing_list;
4472 my @invoicing_list = $self->invoicing_list;
4473 push @invoicing_list, 'POST';
4474 $self->invoicing_list(\@invoicing_list);
4477 =item invoicing_list_emailonly
4479 Returns the list of email invoice recipients (invoicing_list without non-email
4480 destinations such as POST and FAX).
4484 sub invoicing_list_emailonly {
4486 warn "$me invoicing_list_emailonly called"
4488 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4491 =item invoicing_list_emailonly_scalar
4493 Returns the list of email invoice recipients (invoicing_list without non-email
4494 destinations such as POST and FAX) as a comma-separated scalar.
4498 sub invoicing_list_emailonly_scalar {
4500 warn "$me invoicing_list_emailonly_scalar called"
4502 join(', ', $self->invoicing_list_emailonly);
4505 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4507 Returns an array of customers referred by this customer (referral_custnum set
4508 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4509 customers referred by customers referred by this customer and so on, inclusive.
4510 The default behavior is DEPTH 1 (no recursion).
4514 sub referral_cust_main {
4516 my $depth = @_ ? shift : 1;
4517 my $exclude = @_ ? shift : {};
4520 map { $exclude->{$_->custnum}++; $_; }
4521 grep { ! $exclude->{ $_->custnum } }
4522 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4526 map { $_->referral_cust_main($depth-1, $exclude) }
4533 =item referral_cust_main_ncancelled
4535 Same as referral_cust_main, except only returns customers with uncancelled
4540 sub referral_cust_main_ncancelled {
4542 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4545 =item referral_cust_pkg [ DEPTH ]
4547 Like referral_cust_main, except returns a flat list of all unsuspended (and
4548 uncancelled) packages for each customer. The number of items in this list may
4549 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4553 sub referral_cust_pkg {
4555 my $depth = @_ ? shift : 1;
4557 map { $_->unsuspended_pkgs }
4558 grep { $_->unsuspended_pkgs }
4559 $self->referral_cust_main($depth);
4562 =item referring_cust_main
4564 Returns the single cust_main record for the customer who referred this customer
4565 (referral_custnum), or false.
4569 sub referring_cust_main {
4571 return '' unless $self->referral_custnum;
4572 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4575 =item credit AMOUNT, REASON
4577 Applies a credit to this customer. If there is an error, returns the error,
4578 otherwise returns false.
4583 my( $self, $amount, $reason, %options ) = @_;
4584 my $cust_credit = new FS::cust_credit {
4585 'custnum' => $self->custnum,
4586 'amount' => $amount,
4587 'reason' => $reason,
4589 $cust_credit->insert(%options);
4592 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4594 Creates a one-time charge for this customer. If there is an error, returns
4595 the error, otherwise returns false.
4601 my ( $amount, $pkg, $comment, $taxclass, $additional, $classnum );
4602 if ( ref( $_[0] ) ) {
4603 $amount = $_[0]->{amount};
4604 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4605 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4606 : '$'. sprintf("%.2f",$amount);
4607 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4608 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4609 $additional = $_[0]->{additional};
4612 $pkg = @_ ? shift : 'One-time charge';
4613 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4614 $taxclass = @_ ? shift : '';
4618 local $SIG{HUP} = 'IGNORE';
4619 local $SIG{INT} = 'IGNORE';
4620 local $SIG{QUIT} = 'IGNORE';
4621 local $SIG{TERM} = 'IGNORE';
4622 local $SIG{TSTP} = 'IGNORE';
4623 local $SIG{PIPE} = 'IGNORE';
4625 my $oldAutoCommit = $FS::UID::AutoCommit;
4626 local $FS::UID::AutoCommit = 0;
4629 my $part_pkg = new FS::part_pkg ( {
4631 'comment' => $comment,
4635 'classnum' => $classnum ? $classnum : '',
4636 'taxclass' => $taxclass,
4639 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4640 ( 0 .. @$additional - 1 )
4642 'additional_count' => scalar(@$additional),
4643 'setup_fee' => $amount,
4646 my $error = $part_pkg->insert( options => \%options );
4648 $dbh->rollback if $oldAutoCommit;
4652 my $pkgpart = $part_pkg->pkgpart;
4653 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4654 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4655 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4656 $error = $type_pkgs->insert;
4658 $dbh->rollback if $oldAutoCommit;
4663 my $cust_pkg = new FS::cust_pkg ( {
4664 'custnum' => $self->custnum,
4665 'pkgpart' => $pkgpart,
4668 $error = $cust_pkg->insert;
4670 $dbh->rollback if $oldAutoCommit;
4674 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4681 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4687 sort { $a->_date <=> $b->_date }
4688 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4691 =item open_cust_bill
4693 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4698 sub open_cust_bill {
4700 grep { $_->owed > 0 } $self->cust_bill;
4705 Returns all the credits (see L<FS::cust_credit>) for this customer.
4711 sort { $a->_date <=> $b->_date }
4712 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4717 Returns all the payments (see L<FS::cust_pay>) for this customer.
4723 sort { $a->_date <=> $b->_date }
4724 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4729 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4735 sort { $a->_date <=> $b->_date }
4736 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4739 =item cust_pay_batch
4741 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
4745 sub cust_pay_batch {
4747 sort { $a->_date <=> $b->_date }
4748 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
4753 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4759 sort { $a->_date <=> $b->_date }
4760 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4765 Returns a name string for this customer, either "Company (Last, First)" or
4772 my $name = $self->contact;
4773 $name = $self->company. " ($name)" if $self->company;
4779 Returns a name string for this (service/shipping) contact, either
4780 "Company (Last, First)" or "Last, First".
4786 if ( $self->get('ship_last') ) {
4787 my $name = $self->ship_contact;
4788 $name = $self->ship_company. " ($name)" if $self->ship_company;
4797 Returns this customer's full (billing) contact name only, "Last, First"
4803 $self->get('last'). ', '. $self->first;
4808 Returns this customer's full (shipping) contact name only, "Last, First"
4814 $self->get('ship_last')
4815 ? $self->get('ship_last'). ', '. $self->ship_first
4821 Returns this customer's full country name
4827 code2country($self->country);
4830 =item geocode DATA_PROVIDER
4832 Returns a value for the customer location as encoded by DATA_PROVIDER.
4833 Currently this only makes sense for "CCH" as DATA_PROVIDER.
4838 my ($self, $data_provider) = (shift, shift); #always cch for now
4840 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
4844 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
4845 if $self->country eq 'US';
4847 #CCH specific location stuff
4848 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
4851 my $cust_tax_location =
4853 'table' => 'cust_tax_location',
4854 'hashref' => { 'zip' => $zip, 'data_provider' => $data_provider },
4855 'extra_sql' => $extra_sql,
4858 $geocode = $cust_tax_location->geocode
4859 if $cust_tax_location;
4868 Returns a status string for this customer, currently:
4872 =item prospect - No packages have ever been ordered
4874 =item active - One or more recurring packages is active
4876 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4878 =item suspended - All non-cancelled recurring packages are suspended
4880 =item cancelled - All recurring packages are cancelled
4886 sub status { shift->cust_status(@_); }
4890 for my $status (qw( prospect active inactive suspended cancelled )) {
4891 my $method = $status.'_sql';
4892 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4893 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4894 $sth->execute( ($self->custnum) x $numnum )
4895 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4896 return $status if $sth->fetchrow_arrayref->[0];
4900 =item ucfirst_cust_status
4902 =item ucfirst_status
4904 Returns the status with the first character capitalized.
4908 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4910 sub ucfirst_cust_status {
4912 ucfirst($self->cust_status);
4917 Returns a hex triplet color string for this customer's status.
4921 use vars qw(%statuscolor);
4922 tie my %statuscolor, 'Tie::IxHash',
4923 'prospect' => '7e0079', #'000000', #black? naw, purple
4924 'active' => '00CC00', #green
4925 'inactive' => '0000CC', #blue
4926 'suspended' => 'FF9900', #yellow
4927 'cancelled' => 'FF0000', #red
4930 sub statuscolor { shift->cust_statuscolor(@_); }
4932 sub cust_statuscolor {
4934 $statuscolor{$self->cust_status};
4939 Returns an array of hashes representing the customer's RT tickets.
4946 my $num = $conf->config('cust_main-max_tickets') || 10;
4949 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4951 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4955 foreach my $priority (
4956 $conf->config('ticket_system-custom_priority_field-values'), ''
4958 last if scalar(@tickets) >= $num;
4960 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4961 $num - scalar(@tickets),
4970 # Return services representing svc_accts in customer support packages
4971 sub support_services {
4973 my %packages = map { $_ => 1 } $conf->config('support_packages');
4975 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4976 grep { $_->part_svc->svcdb eq 'svc_acct' }
4977 map { $_->cust_svc }
4978 grep { exists $packages{ $_->pkgpart } }
4979 $self->ncancelled_pkgs;
4985 =head1 CLASS METHODS
4991 Class method that returns the list of possible status strings for customers
4992 (see L<the status method|/status>). For example:
4994 @statuses = FS::cust_main->statuses();
4999 #my $self = shift; #could be class...
5005 Returns an SQL expression identifying prospective cust_main records (customers
5006 with no packages ever ordered)
5010 use vars qw($select_count_pkgs);
5011 $select_count_pkgs =
5012 "SELECT COUNT(*) FROM cust_pkg
5013 WHERE cust_pkg.custnum = cust_main.custnum";
5015 sub select_count_pkgs_sql {
5019 sub prospect_sql { "
5020 0 = ( $select_count_pkgs )
5025 Returns an SQL expression identifying active cust_main records (customers with
5026 no active recurring packages, but otherwise unsuspended/uncancelled).
5031 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5037 Returns an SQL expression identifying inactive cust_main records (customers with
5038 active recurring packages).
5042 sub inactive_sql { "
5043 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5045 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5051 Returns an SQL expression identifying suspended cust_main records.
5056 sub suspended_sql { susp_sql(@_); }
5058 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5060 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5066 Returns an SQL expression identifying cancelled cust_main records.
5070 sub cancelled_sql { cancel_sql(@_); }
5073 my $recurring_sql = FS::cust_pkg->recurring_sql;
5074 #my $recurring_sql = "
5075 # '0' != ( select freq from part_pkg
5076 # where cust_pkg.pkgpart = part_pkg.pkgpart )
5080 0 < ( $select_count_pkgs )
5081 AND 0 = ( $select_count_pkgs AND $recurring_sql
5082 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5088 =item uncancelled_sql
5090 Returns an SQL expression identifying un-cancelled cust_main records.
5094 sub uncancelled_sql { uncancel_sql(@_); }
5095 sub uncancel_sql { "
5096 ( 0 < ( $select_count_pkgs
5097 AND ( cust_pkg.cancel IS NULL
5098 OR cust_pkg.cancel = 0
5101 OR 0 = ( $select_count_pkgs )
5107 Returns an SQL fragment to retreive the balance.
5112 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5113 WHERE cust_bill.custnum = cust_main.custnum )
5114 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5115 WHERE cust_pay.custnum = cust_main.custnum )
5116 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5117 WHERE cust_credit.custnum = cust_main.custnum )
5118 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5119 WHERE cust_refund.custnum = cust_main.custnum )
5122 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5124 Returns an SQL fragment to retreive the balance for this customer, only
5125 considering invoices with date earlier than START_TIME, and optionally not
5126 later than END_TIME (total_owed_date minus total_credited minus
5127 total_unapplied_payments).
5129 Times are specified as SQL fragments or numeric
5130 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5131 L<Date::Parse> for conversion functions. The empty string can be passed
5132 to disable that time constraint completely.
5134 Available options are:
5138 =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)
5140 =item total - set to true to remove all customer comparison clauses, for totals
5142 =item where - WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5144 =item join - JOIN clause (typically used with the total option)
5152 sub balance_date_sql {
5153 my( $class, $start, $end, %opt ) = @_;
5155 my $owed = FS::cust_bill->owed_sql;
5156 my $unapp_refund = FS::cust_refund->unapplied_sql;
5157 my $unapp_credit = FS::cust_credit->unapplied_sql;
5158 my $unapp_pay = FS::cust_pay->unapplied_sql;
5160 my $j = $opt{'join'} || '';
5162 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5163 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5164 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5165 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5167 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5168 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5169 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5170 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5175 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5177 Helper method for balance_date_sql; name (and usage) subject to change
5178 (suggestions welcome).
5180 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5181 cust_refund, cust_credit or cust_pay).
5183 If TABLE is "cust_bill" or the unapplied_date option is true, only
5184 considers records with date earlier than START_TIME, and optionally not
5185 later than END_TIME .
5189 sub _money_table_where {
5190 my( $class, $table, $start, $end, %opt ) = @_;
5193 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5194 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5195 push @where, "$table._date <= $start" if defined($start) && length($start);
5196 push @where, "$table._date > $end" if defined($end) && length($end);
5198 push @where, @{$opt{'where'}} if $opt{'where'};
5199 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5205 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5207 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5208 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5209 appropriate ship_ field is also searched).
5211 Additional options are the same as FS::Record::qsearch
5216 my( $self, $fuzzy, $hash, @opt) = @_;
5221 check_and_rebuild_fuzzyfiles();
5222 foreach my $field ( keys %$fuzzy ) {
5224 my $all = $self->all_X($field);
5225 next unless scalar(@$all);
5228 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5231 foreach ( keys %match ) {
5232 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5233 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5236 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5239 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5241 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5249 Returns a masked version of the named field
5254 my ($self,$field) = @_;
5258 'x'x(length($self->getfield($field))-4).
5259 substr($self->getfield($field), (length($self->getfield($field))-4));
5269 =item smart_search OPTION => VALUE ...
5271 Accepts the following options: I<search>, the string to search for. The string
5272 will be searched for as a customer number, phone number, name or company name,
5273 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5274 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5275 skip fuzzy matching when an exact match is found.
5277 Any additional options are treated as an additional qualifier on the search
5280 Returns a (possibly empty) array of FS::cust_main objects.
5287 #here is the agent virtualization
5288 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5292 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5293 my $search = delete $options{'search'};
5294 ( my $alphanum_search = $search ) =~ s/\W//g;
5296 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5298 #false laziness w/Record::ut_phone
5299 my $phonen = "$1-$2-$3";
5300 $phonen .= " x$4" if $4;
5302 push @cust_main, qsearch( {
5303 'table' => 'cust_main',
5304 'hashref' => { %options },
5305 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5307 join(' OR ', map "$_ = '$phonen'",
5308 qw( daytime night fax
5309 ship_daytime ship_night ship_fax )
5312 " AND $agentnums_sql", #agent virtualization
5315 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5316 #try looking for matches with extensions unless one was specified
5318 push @cust_main, qsearch( {
5319 'table' => 'cust_main',
5320 'hashref' => { %options },
5321 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5323 join(' OR ', map "$_ LIKE '$phonen\%'",
5325 ship_daytime ship_night )
5328 " AND $agentnums_sql", #agent virtualization
5333 # custnum search (also try agent_custid), with some tweaking options if your
5334 # legacy cust "numbers" have letters
5335 } elsif ( $search =~ /^\s*(\d+)\s*$/
5336 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5337 && $search =~ /^\s*(\w\w?\d+)\s*$/
5342 push @cust_main, qsearch( {
5343 'table' => 'cust_main',
5344 'hashref' => { 'custnum' => $1, %options },
5345 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5348 push @cust_main, qsearch( {
5349 'table' => 'cust_main',
5350 'hashref' => { 'agent_custid' => $1, %options },
5351 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5354 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5356 my($company, $last, $first) = ( $1, $2, $3 );
5358 # "Company (Last, First)"
5359 #this is probably something a browser remembered,
5360 #so just do an exact search
5362 foreach my $prefix ( '', 'ship_' ) {
5363 push @cust_main, qsearch( {
5364 'table' => 'cust_main',
5365 'hashref' => { $prefix.'first' => $first,
5366 $prefix.'last' => $last,
5367 $prefix.'company' => $company,
5370 'extra_sql' => " AND $agentnums_sql",
5374 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5375 # try (ship_){last,company}
5379 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5380 # # full strings the browser remembers won't work
5381 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5383 use Lingua::EN::NameParse;
5384 my $NameParse = new Lingua::EN::NameParse(
5386 allow_reversed => 1,
5389 my($last, $first) = ( '', '' );
5390 #maybe disable this too and just rely on NameParse?
5391 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5393 ($last, $first) = ( $1, $2 );
5395 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5396 } elsif ( ! $NameParse->parse($value) ) {
5398 my %name = $NameParse->components;
5399 $first = $name{'given_name_1'};
5400 $last = $name{'surname_1'};
5404 if ( $first && $last ) {
5406 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5409 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5411 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5412 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5415 push @cust_main, qsearch( {
5416 'table' => 'cust_main',
5417 'hashref' => \%options,
5418 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5421 # or it just be something that was typed in... (try that in a sec)
5425 my $q_value = dbh->quote($value);
5428 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5429 $sql .= " ( LOWER(last) = $q_value
5430 OR LOWER(company) = $q_value
5431 OR LOWER(ship_last) = $q_value
5432 OR LOWER(ship_company) = $q_value
5435 push @cust_main, qsearch( {
5436 'table' => 'cust_main',
5437 'hashref' => \%options,
5438 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5441 #no exact match, trying substring/fuzzy
5442 #always do substring & fuzzy (unless they're explicity config'ed off)
5443 #getting complaints searches are not returning enough
5444 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
5446 #still some false laziness w/ search/cust_main.cgi
5451 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
5452 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5455 if ( $first && $last ) {
5458 { 'first' => { op=>'ILIKE', value=>"%$first%" },
5459 'last' => { op=>'ILIKE', value=>"%$last%" },
5461 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
5462 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
5469 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
5470 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
5474 foreach my $hashref ( @hashrefs ) {
5476 push @cust_main, qsearch( {
5477 'table' => 'cust_main',
5478 'hashref' => { %$hashref,
5481 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
5490 " AND $agentnums_sql", #extra_sql #agent virtualization
5493 if ( $first && $last ) {
5494 push @cust_main, FS::cust_main->fuzzy_search(
5495 { 'last' => $last, #fuzzy hashref
5496 'first' => $first }, #
5500 foreach my $field ( 'last', 'company' ) {
5502 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
5507 #eliminate duplicates
5509 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5519 Accepts the following options: I<email>, the email address to search for. The
5520 email address will be searched for as an email invoice destination and as an
5523 #Any additional options are treated as an additional qualifier on the search
5524 #(i.e. I<agentnum>).
5526 Returns a (possibly empty) array of FS::cust_main objects (but usually just
5536 my $email = delete $options{'email'};
5538 #we're only being used by RT at the moment... no agent virtualization yet
5539 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5543 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
5545 my ( $user, $domain ) = ( $1, $2 );
5547 warn "$me smart_search: searching for $user in domain $domain"
5553 'table' => 'cust_main_invoice',
5554 'hashref' => { 'dest' => $email },
5561 map $_->cust_svc->cust_pkg,
5563 'table' => 'svc_acct',
5564 'hashref' => { 'username' => $user, },
5566 'AND ( SELECT domain FROM svc_domain
5567 WHERE svc_acct.domsvc = svc_domain.svcnum
5568 ) = '. dbh->quote($domain),
5574 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5576 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
5583 =item check_and_rebuild_fuzzyfiles
5587 use vars qw(@fuzzyfields);
5588 @fuzzyfields = ( 'last', 'first', 'company' );
5590 sub check_and_rebuild_fuzzyfiles {
5591 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5592 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
5595 =item rebuild_fuzzyfiles
5599 sub rebuild_fuzzyfiles {
5601 use Fcntl qw(:flock);
5603 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5604 mkdir $dir, 0700 unless -d $dir;
5606 foreach my $fuzzy ( @fuzzyfields ) {
5608 open(LOCK,">>$dir/cust_main.$fuzzy")
5609 or die "can't open $dir/cust_main.$fuzzy: $!";
5611 or die "can't lock $dir/cust_main.$fuzzy: $!";
5613 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
5614 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
5616 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
5617 my $sth = dbh->prepare("SELECT $field FROM cust_main".
5618 " WHERE $field != '' AND $field IS NOT NULL");
5619 $sth->execute or die $sth->errstr;
5621 while ( my $row = $sth->fetchrow_arrayref ) {
5622 print CACHE $row->[0]. "\n";
5627 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
5629 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
5640 my( $self, $field ) = @_;
5641 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5642 open(CACHE,"<$dir/cust_main.$field")
5643 or die "can't open $dir/cust_main.$field: $!";
5644 my @array = map { chomp; $_; } <CACHE>;
5649 =item append_fuzzyfiles LASTNAME COMPANY
5653 sub append_fuzzyfiles {
5654 #my( $first, $last, $company ) = @_;
5656 &check_and_rebuild_fuzzyfiles;
5658 use Fcntl qw(:flock);
5660 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5662 foreach my $field (qw( first last company )) {
5667 open(CACHE,">>$dir/cust_main.$field")
5668 or die "can't open $dir/cust_main.$field: $!";
5669 flock(CACHE,LOCK_EX)
5670 or die "can't lock $dir/cust_main.$field: $!";
5672 print CACHE "$value\n";
5674 flock(CACHE,LOCK_UN)
5675 or die "can't unlock $dir/cust_main.$field: $!";
5690 #warn join('-',keys %$param);
5691 my $fh = $param->{filehandle};
5692 my $agentnum = $param->{agentnum};
5694 my $refnum = $param->{refnum};
5695 my $pkgpart = $param->{pkgpart};
5697 #my @fields = @{$param->{fields}};
5698 my $format = $param->{'format'};
5701 if ( $format eq 'simple' ) {
5702 @fields = qw( cust_pkg.setup dayphone first last
5703 address1 address2 city state zip comments );
5705 } elsif ( $format eq 'extended' ) {
5706 @fields = qw( agent_custid refnum
5707 last first address1 address2 city state zip country
5709 ship_last ship_first ship_address1 ship_address2
5710 ship_city ship_state ship_zip ship_country
5711 payinfo paycvv paydate
5714 svc_acct.username svc_acct._password
5717 } elsif ( $format eq 'extended-plus_company' ) {
5718 @fields = qw( agent_custid refnum
5719 last first company address1 address2 city state zip country
5721 ship_last ship_first ship_company ship_address1 ship_address2
5722 ship_city ship_state ship_zip ship_country
5723 payinfo paycvv paydate
5726 svc_acct.username svc_acct._password
5730 die "unknown format $format";
5733 eval "use Text::CSV_XS;";
5736 my $csv = new Text::CSV_XS;
5743 local $SIG{HUP} = 'IGNORE';
5744 local $SIG{INT} = 'IGNORE';
5745 local $SIG{QUIT} = 'IGNORE';
5746 local $SIG{TERM} = 'IGNORE';
5747 local $SIG{TSTP} = 'IGNORE';
5748 local $SIG{PIPE} = 'IGNORE';
5750 my $oldAutoCommit = $FS::UID::AutoCommit;
5751 local $FS::UID::AutoCommit = 0;
5754 #while ( $columns = $csv->getline($fh) ) {
5756 while ( defined($line=<$fh>) ) {
5758 $csv->parse($line) or do {
5759 $dbh->rollback if $oldAutoCommit;
5760 return "can't parse: ". $csv->error_input();
5763 my @columns = $csv->fields();
5764 #warn join('-',@columns);
5767 agentnum => $agentnum,
5769 country => $conf->config('countrydefault') || 'US',
5770 payby => $payby, #default
5771 paydate => '12/2037', #default
5773 my $billtime = time;
5774 my %cust_pkg = ( pkgpart => $pkgpart );
5776 foreach my $field ( @fields ) {
5778 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
5780 #$cust_pkg{$1} = str2time( shift @$columns );
5781 if ( $1 eq 'pkgpart' ) {
5782 $cust_pkg{$1} = shift @columns;
5783 } elsif ( $1 eq 'setup' ) {
5784 $billtime = str2time(shift @columns);
5786 $cust_pkg{$1} = str2time( shift @columns );
5789 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
5791 $svc_acct{$1} = shift @columns;
5795 #refnum interception
5796 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
5798 my $referral = $columns[0];
5799 my %hash = ( 'referral' => $referral,
5800 'agentnum' => $agentnum,
5804 my $part_referral = qsearchs('part_referral', \%hash )
5805 || new FS::part_referral \%hash;
5807 unless ( $part_referral->refnum ) {
5808 my $error = $part_referral->insert;
5810 $dbh->rollback if $oldAutoCommit;
5811 return "can't auto-insert advertising source: $referral: $error";
5815 $columns[0] = $part_referral->refnum;
5818 #$cust_main{$field} = shift @$columns;
5819 $cust_main{$field} = shift @columns;
5823 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
5825 my $invoicing_list = $cust_main{'invoicing_list'}
5826 ? [ delete $cust_main{'invoicing_list'} ]
5829 my $cust_main = new FS::cust_main ( \%cust_main );
5832 tie my %hash, 'Tie::RefHash'; #this part is important
5834 if ( $cust_pkg{'pkgpart'} ) {
5835 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
5838 if ( $svc_acct{'username'} ) {
5839 my $part_pkg = $cust_pkg->part_pkg;
5840 unless ( $part_pkg ) {
5841 $dbh->rollback if $oldAutoCommit;
5842 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
5844 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
5845 push @svc_acct, new FS::svc_acct ( \%svc_acct )
5848 $hash{$cust_pkg} = \@svc_acct;
5851 my $error = $cust_main->insert( \%hash, $invoicing_list );
5854 $dbh->rollback if $oldAutoCommit;
5855 return "can't insert customer for $line: $error";
5858 if ( $format eq 'simple' ) {
5860 #false laziness w/bill.cgi
5861 $error = $cust_main->bill( 'time' => $billtime );
5863 $dbh->rollback if $oldAutoCommit;
5864 return "can't bill customer for $line: $error";
5867 $error = $cust_main->apply_payments_and_credits;
5869 $dbh->rollback if $oldAutoCommit;
5870 return "can't bill customer for $line: $error";
5873 $error = $cust_main->collect();
5875 $dbh->rollback if $oldAutoCommit;
5876 return "can't collect customer for $line: $error";
5884 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5886 return "Empty file!" unless $imported;
5898 #warn join('-',keys %$param);
5899 my $fh = $param->{filehandle};
5900 my @fields = @{$param->{fields}};
5902 eval "use Text::CSV_XS;";
5905 my $csv = new Text::CSV_XS;
5912 local $SIG{HUP} = 'IGNORE';
5913 local $SIG{INT} = 'IGNORE';
5914 local $SIG{QUIT} = 'IGNORE';
5915 local $SIG{TERM} = 'IGNORE';
5916 local $SIG{TSTP} = 'IGNORE';
5917 local $SIG{PIPE} = 'IGNORE';
5919 my $oldAutoCommit = $FS::UID::AutoCommit;
5920 local $FS::UID::AutoCommit = 0;
5923 #while ( $columns = $csv->getline($fh) ) {
5925 while ( defined($line=<$fh>) ) {
5927 $csv->parse($line) or do {
5928 $dbh->rollback if $oldAutoCommit;
5929 return "can't parse: ". $csv->error_input();
5932 my @columns = $csv->fields();
5933 #warn join('-',@columns);
5936 foreach my $field ( @fields ) {
5937 $row{$field} = shift @columns;
5940 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
5941 unless ( $cust_main ) {
5942 $dbh->rollback if $oldAutoCommit;
5943 return "unknown custnum $row{'custnum'}";
5946 if ( $row{'amount'} > 0 ) {
5947 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5949 $dbh->rollback if $oldAutoCommit;
5953 } elsif ( $row{'amount'} < 0 ) {
5954 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5957 $dbh->rollback if $oldAutoCommit;
5967 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5969 return "Empty file!" unless $imported;
5975 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5977 Sends a templated email notification to the customer (see L<Text::Template>).
5979 OPTIONS is a hash and may include
5981 I<from> - the email sender (default is invoice_from)
5983 I<to> - comma-separated scalar or arrayref of recipients
5984 (default is invoicing_list)
5986 I<subject> - The subject line of the sent email notification
5987 (default is "Notice from company_name")
5989 I<extra_fields> - a hashref of name/value pairs which will be substituted
5992 The following variables are vavailable in the template.
5994 I<$first> - the customer first name
5995 I<$last> - the customer last name
5996 I<$company> - the customer company
5997 I<$payby> - a description of the method of payment for the customer
5998 # would be nice to use FS::payby::shortname
5999 I<$payinfo> - the account information used to collect for this customer
6000 I<$expdate> - the expiration of the customer payment in seconds from epoch
6005 my ($customer, $template, %options) = @_;
6007 return unless $conf->exists($template);
6009 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6010 $from = $options{from} if exists($options{from});
6012 my $to = join(',', $customer->invoicing_list_emailonly);
6013 $to = $options{to} if exists($options{to});
6015 my $subject = "Notice from " . $conf->config('company_name')
6016 if $conf->exists('company_name');
6017 $subject = $options{subject} if exists($options{subject});
6019 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6020 SOURCE => [ map "$_\n",
6021 $conf->config($template)]
6023 or die "can't create new Text::Template object: Text::Template::ERROR";
6024 $notify_template->compile()
6025 or die "can't compile template: Text::Template::ERROR";
6027 $FS::notify_template::_template::company_name = $conf->config('company_name');
6028 $FS::notify_template::_template::company_address =
6029 join("\n", $conf->config('company_address') ). "\n";
6031 my $paydate = $customer->paydate || '2037-12-31';
6032 $FS::notify_template::_template::first = $customer->first;
6033 $FS::notify_template::_template::last = $customer->last;
6034 $FS::notify_template::_template::company = $customer->company;
6035 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6036 my $payby = $customer->payby;
6037 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6038 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6040 #credit cards expire at the end of the month/year of their exp date
6041 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6042 $FS::notify_template::_template::payby = 'credit card';
6043 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6044 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6046 }elsif ($payby eq 'COMP') {
6047 $FS::notify_template::_template::payby = 'complimentary account';
6049 $FS::notify_template::_template::payby = 'current method';
6051 $FS::notify_template::_template::expdate = $expire_time;
6053 for (keys %{$options{extra_fields}}){
6055 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6058 send_email(from => $from,
6060 subject => $subject,
6061 body => $notify_template->fill_in( PACKAGE =>
6062 'FS::notify_template::_template' ),
6067 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6069 Generates a templated notification to the customer (see L<Text::Template>).
6071 OPTIONS is a hash and may include
6073 I<extra_fields> - a hashref of name/value pairs which will be substituted
6074 into the template. These values may override values mentioned below
6075 and those from the customer record.
6077 The following variables are available in the template instead of or in addition
6078 to the fields of the customer record.
6080 I<$payby> - a description of the method of payment for the customer
6081 # would be nice to use FS::payby::shortname
6082 I<$payinfo> - the masked account information used to collect for this customer
6083 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6084 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6088 sub generate_letter {
6089 my ($self, $template, %options) = @_;
6091 return unless $conf->exists($template);
6093 my $letter_template = new Text::Template
6095 SOURCE => [ map "$_\n", $conf->config($template)],
6096 DELIMITERS => [ '[@--', '--@]' ],
6098 or die "can't create new Text::Template object: Text::Template::ERROR";
6100 $letter_template->compile()
6101 or die "can't compile template: Text::Template::ERROR";
6103 my %letter_data = map { $_ => $self->$_ } $self->fields;
6104 $letter_data{payinfo} = $self->mask_payinfo;
6106 #my $paydate = $self->paydate || '2037-12-31';
6107 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6109 my $payby = $self->payby;
6110 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6111 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6113 #credit cards expire at the end of the month/year of their exp date
6114 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6115 $letter_data{payby} = 'credit card';
6116 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6117 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6119 }elsif ($payby eq 'COMP') {
6120 $letter_data{payby} = 'complimentary account';
6122 $letter_data{payby} = 'current method';
6124 $letter_data{expdate} = $expire_time;
6126 for (keys %{$options{extra_fields}}){
6127 $letter_data{$_} = $options{extra_fields}->{$_};
6130 unless(exists($letter_data{returnaddress})){
6131 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6132 $self->agent_template)
6134 if ( length($retadd) ) {
6135 $letter_data{returnaddress} = $retadd;
6136 } elsif ( grep /\S/, $conf->config('company_address') ) {
6137 $letter_data{returnaddress} =
6138 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6139 $conf->config('company_address')
6142 $letter_data{returnaddress} = '~';
6146 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6148 $letter_data{company_name} = $conf->config('company_name');
6150 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6151 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6155 ) or die "can't open temp file: $!\n";
6157 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6159 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6163 =item print_ps TEMPLATE
6165 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6171 my $file = $self->generate_letter(@_);
6172 FS::Misc::generate_ps($file);
6175 =item print TEMPLATE
6177 Prints the filled in template.
6179 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6183 sub queueable_print {
6186 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6187 or die "invalid customer number: " . $opt{custvnum};
6189 my $error = $self->print( $opt{template} );
6190 die $error if $error;
6194 my ($self, $template) = (shift, shift);
6195 do_print [ $self->print_ps($template) ];
6198 sub agent_template {
6200 $self->_agent_plandata('agent_templatename');
6203 sub agent_invoice_from {
6205 $self->_agent_plandata('agent_invoice_from');
6208 sub _agent_plandata {
6209 my( $self, $option ) = @_;
6211 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6212 #agent-specific Conf
6214 use FS::part_event::Condition;
6216 my $agentnum = $self->agentnum;
6219 if ( driver_name =~ /^Pg/i ) {
6221 } elsif ( driver_name =~ /^mysql/i ) {
6224 die "don't know how to use regular expressions in ". driver_name. " databases";
6227 my $part_event_option =
6229 'select' => 'part_event_option.*',
6230 'table' => 'part_event_option',
6232 LEFT JOIN part_event USING ( eventpart )
6233 LEFT JOIN part_event_option AS peo_agentnum
6234 ON ( part_event.eventpart = peo_agentnum.eventpart
6235 AND peo_agentnum.optionname = 'agentnum'
6236 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6238 LEFT JOIN part_event_option AS peo_cust_bill_age
6239 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6240 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6243 #'hashref' => { 'optionname' => $option },
6244 #'hashref' => { 'part_event_option.optionname' => $option },
6246 " WHERE part_event_option.optionname = ". dbh->quote($option).
6247 " AND action = 'cust_bill_send_agent' ".
6248 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6249 " AND peo_agentnum.optionname = 'agentnum' ".
6250 " AND agentnum IS NULL OR agentnum = $agentnum ".
6252 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6254 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6256 , part_event.weight".
6260 unless ( $part_event_option ) {
6261 return $self->agent->invoice_template || ''
6262 if $option eq 'agent_templatename';
6266 $part_event_option->optionvalue;
6271 ## actual sub, not a method, designed to be called from the queue.
6272 ## sets up the customer, and calls the bill_and_collect
6273 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6274 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6275 $cust_main->bill_and_collect(
6286 The delete method should possibly take an FS::cust_main object reference
6287 instead of a scalar customer number.
6289 Bill and collect options should probably be passed as references instead of a
6292 There should probably be a configuration file with a list of allowed credit
6295 No multiple currency support (probably a larger project than just this module).
6297 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6299 Birthdates rely on negative epoch values.
6301 The payby for card/check batches is broken. With mixed batching, bad
6304 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
6308 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6309 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6310 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.