5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 use Scalar::Util qw( blessed );
12 use Time::Local qw(timelocal_nocheck);
15 use Digest::MD5 qw(md5_base64);
19 use File::Slurp qw( slurp );
20 use File::Temp qw( tempfile );
21 use String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
24 use FS::UID qw( getotaker dbh driver_name );
25 use FS::Record qw( qsearchs qsearch dbdef );
26 use FS::Misc qw( generate_email send_email generate_ps do_print );
27 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
33 use FS::cust_pay_pending;
34 use FS::cust_pay_void;
35 use FS::cust_pay_batch;
38 use FS::part_referral;
39 use FS::cust_main_county;
40 use FS::cust_tax_location;
42 use FS::cust_main_invoice;
43 use FS::cust_credit_bill;
44 use FS::cust_bill_pay;
45 use FS::prepay_credit;
49 use FS::part_event_condition;
52 use FS::payment_gateway;
53 use FS::agent_payment_gateway;
55 use FS::payinfo_Mixin;
58 @ISA = qw( FS::payinfo_Mixin FS::Record );
60 @EXPORT_OK = qw( smart_search );
62 $realtime_bop_decline_quiet = 0;
64 # 1 is mostly method/subroutine entry and options
65 # 2 traces progress of some operations
66 # 3 is even more information including possibly sensitive data
68 $me = '[FS::cust_main]';
72 $ignore_expired_card = 0;
74 @encrypted_fields = ('payinfo', 'paycvv');
75 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
77 #ask FS::UID to run this stuff for us later
78 #$FS::UID::callback{'FS::cust_main'} = sub {
79 install_callback FS::UID sub {
81 #yes, need it for stuff below (prolly should be cached)
86 my ( $hashref, $cache ) = @_;
87 if ( exists $hashref->{'pkgnum'} ) {
88 #@{ $self->{'_pkgnum'} } = ();
89 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
90 $self->{'_pkgnum'} = $subcache;
91 #push @{ $self->{'_pkgnum'} },
92 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
98 FS::cust_main - Object methods for cust_main records
104 $record = new FS::cust_main \%hash;
105 $record = new FS::cust_main { 'column' => 'value' };
107 $error = $record->insert;
109 $error = $new_record->replace($old_record);
111 $error = $record->delete;
113 $error = $record->check;
115 @cust_pkg = $record->all_pkgs;
117 @cust_pkg = $record->ncancelled_pkgs;
119 @cust_pkg = $record->suspended_pkgs;
121 $error = $record->bill;
122 $error = $record->bill %options;
123 $error = $record->bill 'time' => $time;
125 $error = $record->collect;
126 $error = $record->collect %options;
127 $error = $record->collect 'invoice_time' => $time,
132 An FS::cust_main object represents a customer. FS::cust_main inherits from
133 FS::Record. The following fields are currently supported:
137 =item custnum - primary key (assigned automatically for new customers)
139 =item agentnum - agent (see L<FS::agent>)
141 =item refnum - Advertising source (see L<FS::part_referral>)
147 =item ss - social security number (optional)
149 =item company - (optional)
153 =item address2 - (optional)
157 =item county - (optional, see L<FS::cust_main_county>)
159 =item state - (see L<FS::cust_main_county>)
163 =item country - (see L<FS::cust_main_county>)
165 =item daytime - phone (optional)
167 =item night - phone (optional)
169 =item fax - phone (optional)
171 =item ship_first - name
173 =item ship_last - name
175 =item ship_company - (optional)
179 =item ship_address2 - (optional)
183 =item ship_county - (optional, see L<FS::cust_main_county>)
185 =item ship_state - (see L<FS::cust_main_county>)
189 =item ship_country - (see L<FS::cust_main_county>)
191 =item ship_daytime - phone (optional)
193 =item ship_night - phone (optional)
195 =item ship_fax - phone (optional)
197 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
199 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
201 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
205 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
207 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
209 =item paystart_month - start date month (maestro/solo cards only)
211 =item paystart_year - start date year (maestro/solo cards only)
213 =item payissue - issue number (maestro/solo cards only)
215 =item payname - name on card or billing name
217 =item payip - IP address from which payment information was received
219 =item tax - tax exempt, empty or `Y'
221 =item otaker - order taker (assigned automatically, see L<FS::UID>)
223 =item comments - comments (optional)
225 =item referral_custnum - referring customer number
227 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
229 =item squelch_cdr - Discourage individual CDR printing, empty or `Y'
239 Creates a new customer. To add the customer to the database, see L<"insert">.
241 Note that this stores the hash reference, not a distinct copy of the hash it
242 points to. You can ask the object for a copy with the I<hash> method.
246 sub table { 'cust_main'; }
248 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
250 Adds this customer to the database. If there is an error, returns the error,
251 otherwise returns false.
253 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
254 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
255 are inserted atomicly, or the transaction is rolled back. Passing an empty
256 hash reference is equivalent to not supplying this parameter. There should be
257 a better explanation of this, but until then, here's an example:
260 tie %hash, 'Tie::RefHash'; #this part is important
262 $cust_pkg => [ $svc_acct ],
265 $cust_main->insert( \%hash );
267 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
268 be set as the invoicing list (see L<"invoicing_list">). Errors return as
269 expected and rollback the entire transaction; it is not necessary to call
270 check_invoicing_list first. The invoicing_list is set after the records in the
271 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
272 invoicing_list destination to the newly-created svc_acct. Here's an example:
274 $cust_main->insert( {}, [ $email, 'POST' ] );
276 Currently available options are: I<depend_jobnum> and I<noexport>.
278 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
279 on the supplied jobnum (they will not run until the specific job completes).
280 This can be used to defer provisioning until some action completes (such
281 as running the customer's credit card successfully).
283 The I<noexport> option is deprecated. If I<noexport> is set true, no
284 provisioning jobs (exports) are scheduled. (You can schedule them later with
285 the B<reexport> method.)
291 my $cust_pkgs = @_ ? shift : {};
292 my $invoicing_list = @_ ? shift : '';
294 warn "$me insert called with options ".
295 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
298 local $SIG{HUP} = 'IGNORE';
299 local $SIG{INT} = 'IGNORE';
300 local $SIG{QUIT} = 'IGNORE';
301 local $SIG{TERM} = 'IGNORE';
302 local $SIG{TSTP} = 'IGNORE';
303 local $SIG{PIPE} = 'IGNORE';
305 my $oldAutoCommit = $FS::UID::AutoCommit;
306 local $FS::UID::AutoCommit = 0;
309 my $prepay_identifier = '';
310 my( $amount, $seconds ) = ( 0, 0 );
312 if ( $self->payby eq 'PREPAY' ) {
314 $self->payby('BILL');
315 $prepay_identifier = $self->payinfo;
318 warn " looking up prepaid card $prepay_identifier\n"
321 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
323 $dbh->rollback if $oldAutoCommit;
324 #return "error applying prepaid card (transaction rolled back): $error";
328 $payby = 'PREP' if $amount;
330 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
333 $self->payby('BILL');
334 $amount = $self->paid;
338 warn " inserting $self\n"
341 $self->signupdate(time) unless $self->signupdate;
343 my $error = $self->SUPER::insert;
345 $dbh->rollback if $oldAutoCommit;
346 #return "inserting cust_main record (transaction rolled back): $error";
350 warn " setting invoicing list\n"
353 if ( $invoicing_list ) {
354 $error = $self->check_invoicing_list( $invoicing_list );
356 $dbh->rollback if $oldAutoCommit;
357 #return "checking invoicing_list (transaction rolled back): $error";
360 $self->invoicing_list( $invoicing_list );
363 if ( $conf->config('cust_main-skeleton_tables')
364 && $conf->config('cust_main-skeleton_custnum') ) {
366 warn " inserting skeleton records\n"
369 my $error = $self->start_copy_skel;
371 $dbh->rollback if $oldAutoCommit;
377 warn " ordering packages\n"
380 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
382 $dbh->rollback if $oldAutoCommit;
387 $dbh->rollback if $oldAutoCommit;
388 return "No svc_acct record to apply pre-paid time";
392 warn " inserting initial $payby payment of $amount\n"
394 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
396 $dbh->rollback if $oldAutoCommit;
397 return "inserting payment (transaction rolled back): $error";
401 unless ( $import || $skip_fuzzyfiles ) {
402 warn " queueing fuzzyfiles update\n"
404 $error = $self->queue_fuzzyfiles_update;
406 $dbh->rollback if $oldAutoCommit;
407 return "updating fuzzy search cache: $error";
411 warn " insert complete; committing transaction\n"
414 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
419 sub start_copy_skel {
422 #'mg_user_preference' => {},
423 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
424 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
425 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
426 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
427 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
430 _copy_skel( 'cust_main', #tablename
431 $conf->config('cust_main-skeleton_custnum'), #sourceid
432 $self->custnum, #destid
433 @tables, #child tables
437 #recursive subroutine, not a method
439 my( $table, $sourceid, $destid, %child_tables ) = @_;
442 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
443 ( $table, $primary_key ) = ( $1, $2 );
445 my $dbdef_table = dbdef->table($table);
446 $primary_key = $dbdef_table->primary_key
447 or return "$table has no primary key".
448 " (or do you need to run dbdef-create?)";
451 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
452 join (', ', keys %child_tables). "\n"
455 foreach my $child_table_def ( keys %child_tables ) {
459 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
460 ( $child_table, $child_pkey ) = ( $1, $2 );
462 $child_table = $child_table_def;
464 $child_pkey = dbdef->table($child_table)->primary_key;
465 # or return "$table has no primary key".
466 # " (or do you need to run dbdef-create?)\n";
470 if ( keys %{ $child_tables{$child_table_def} } ) {
472 return "$child_table has no primary key".
473 " (run dbdef-create or try specifying it?)\n"
476 #false laziness w/Record::insert and only works on Pg
477 #refactor the proper last-inserted-id stuff out of Record::insert if this
478 # ever gets use for anything besides a quick kludge for one customer
479 my $default = dbdef->table($child_table)->column($child_pkey)->default;
480 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
481 or return "can't parse $child_table.$child_pkey default value ".
482 " for sequence name: $default";
487 my @sel_columns = grep { $_ ne $primary_key }
488 dbdef->table($child_table)->columns;
489 my $sel_columns = join(', ', @sel_columns );
491 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
492 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
493 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
495 my $sel_st = "SELECT $sel_columns FROM $child_table".
496 " WHERE $primary_key = $sourceid";
499 my $sel_sth = dbh->prepare( $sel_st )
500 or return dbh->errstr;
502 $sel_sth->execute or return $sel_sth->errstr;
504 while ( my $row = $sel_sth->fetchrow_hashref ) {
506 warn " selected row: ".
507 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
511 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
512 my $ins_sth =dbh->prepare($statement)
513 or return dbh->errstr;
514 my @param = ( $destid, map $row->{$_}, @ins_columns );
515 warn " $statement: [ ". join(', ', @param). " ]\n"
517 $ins_sth->execute( @param )
518 or return $ins_sth->errstr;
520 #next unless keys %{ $child_tables{$child_table} };
521 next unless $sequence;
523 #another section of that laziness
524 my $seq_sql = "SELECT currval('$sequence')";
525 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
526 $seq_sth->execute or return $seq_sth->errstr;
527 my $insertid = $seq_sth->fetchrow_arrayref->[0];
529 # don't drink soap! recurse! recurse! okay!
531 _copy_skel( $child_table_def,
532 $row->{$child_pkey}, #sourceid
534 %{ $child_tables{$child_table_def} },
536 return $error if $error;
546 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
548 Like the insert method on an existing record, this method orders a package
549 and included services atomicaly. Pass a Tie::RefHash data structure to this
550 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
551 be a better explanation of this, but until then, here's an example:
554 tie %hash, 'Tie::RefHash'; #this part is important
556 $cust_pkg => [ $svc_acct ],
559 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
561 Services can be new, in which case they are inserted, or existing unaudited
562 services, in which case they are linked to the newly-created package.
564 Currently available options are: I<depend_jobnum> and I<noexport>.
566 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
567 on the supplied jobnum (they will not run until the specific job completes).
568 This can be used to defer provisioning until some action completes (such
569 as running the customer's credit card successfully).
571 The I<noexport> option is deprecated. If I<noexport> is set true, no
572 provisioning jobs (exports) are scheduled. (You can schedule them later with
573 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
574 on the cust_main object is not recommended, as existing services will also be
581 my $cust_pkgs = shift;
584 my %svc_options = ();
585 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
586 if exists $options{'depend_jobnum'};
587 warn "$me order_pkgs called with options ".
588 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
591 local $SIG{HUP} = 'IGNORE';
592 local $SIG{INT} = 'IGNORE';
593 local $SIG{QUIT} = 'IGNORE';
594 local $SIG{TERM} = 'IGNORE';
595 local $SIG{TSTP} = 'IGNORE';
596 local $SIG{PIPE} = 'IGNORE';
598 my $oldAutoCommit = $FS::UID::AutoCommit;
599 local $FS::UID::AutoCommit = 0;
602 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
604 foreach my $cust_pkg ( keys %$cust_pkgs ) {
605 $cust_pkg->custnum( $self->custnum );
606 my $error = $cust_pkg->insert;
608 $dbh->rollback if $oldAutoCommit;
609 return "inserting cust_pkg (transaction rolled back): $error";
611 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
612 if ( $svc_something->svcnum ) {
613 my $old_cust_svc = $svc_something->cust_svc;
614 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
615 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
616 $error = $new_cust_svc->replace($old_cust_svc);
618 $svc_something->pkgnum( $cust_pkg->pkgnum );
619 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
620 $svc_something->seconds( $svc_something->seconds + $$seconds );
623 $error = $svc_something->insert(%svc_options);
626 $dbh->rollback if $oldAutoCommit;
627 #return "inserting svc_ (transaction rolled back): $error";
633 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
637 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
639 Recharges this (existing) customer with the specified prepaid card (see
640 L<FS::prepay_credit>), specified either by I<identifier> or as an
641 FS::prepay_credit object. If there is an error, returns the error, otherwise
644 Optionally, four scalar references can be passed as well. They will have their
645 values filled in with the amount, number of seconds, and number of upload and
646 download bytes applied by this prepaid
651 sub recharge_prepay {
652 my( $self, $prepay_credit, $amountref, $secondsref,
653 $upbytesref, $downbytesref, $totalbytesref ) = @_;
655 local $SIG{HUP} = 'IGNORE';
656 local $SIG{INT} = 'IGNORE';
657 local $SIG{QUIT} = 'IGNORE';
658 local $SIG{TERM} = 'IGNORE';
659 local $SIG{TSTP} = 'IGNORE';
660 local $SIG{PIPE} = 'IGNORE';
662 my $oldAutoCommit = $FS::UID::AutoCommit;
663 local $FS::UID::AutoCommit = 0;
666 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
668 my $error = $self->get_prepay($prepay_credit, \$amount,
669 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
670 || $self->increment_seconds($seconds)
671 || $self->increment_upbytes($upbytes)
672 || $self->increment_downbytes($downbytes)
673 || $self->increment_totalbytes($totalbytes)
674 || $self->insert_cust_pay_prepay( $amount,
676 ? $prepay_credit->identifier
681 $dbh->rollback if $oldAutoCommit;
685 if ( defined($amountref) ) { $$amountref = $amount; }
686 if ( defined($secondsref) ) { $$secondsref = $seconds; }
687 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
688 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
689 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
691 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
696 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
698 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
699 specified either by I<identifier> or as an FS::prepay_credit object.
701 References to I<amount> and I<seconds> scalars should be passed as arguments
702 and will be incremented by the values of the prepaid card.
704 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
705 check or set this customer's I<agentnum>.
707 If there is an error, returns the error, otherwise returns false.
713 my( $self, $prepay_credit, $amountref, $secondsref,
714 $upref, $downref, $totalref) = @_;
716 local $SIG{HUP} = 'IGNORE';
717 local $SIG{INT} = 'IGNORE';
718 local $SIG{QUIT} = 'IGNORE';
719 local $SIG{TERM} = 'IGNORE';
720 local $SIG{TSTP} = 'IGNORE';
721 local $SIG{PIPE} = 'IGNORE';
723 my $oldAutoCommit = $FS::UID::AutoCommit;
724 local $FS::UID::AutoCommit = 0;
727 unless ( ref($prepay_credit) ) {
729 my $identifier = $prepay_credit;
731 $prepay_credit = qsearchs(
733 { 'identifier' => $prepay_credit },
738 unless ( $prepay_credit ) {
739 $dbh->rollback if $oldAutoCommit;
740 return "Invalid prepaid card: ". $identifier;
745 if ( $prepay_credit->agentnum ) {
746 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
747 $dbh->rollback if $oldAutoCommit;
748 return "prepaid card not valid for agent ". $self->agentnum;
750 $self->agentnum($prepay_credit->agentnum);
753 my $error = $prepay_credit->delete;
755 $dbh->rollback if $oldAutoCommit;
756 return "removing prepay_credit (transaction rolled back): $error";
759 $$amountref += $prepay_credit->amount;
760 $$secondsref += $prepay_credit->seconds;
761 $$upref += $prepay_credit->upbytes;
762 $$downref += $prepay_credit->downbytes;
763 $$totalref += $prepay_credit->totalbytes;
765 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
770 =item increment_upbytes SECONDS
772 Updates this customer's single or primary account (see L<FS::svc_acct>) by
773 the specified number of upbytes. If there is an error, returns the error,
774 otherwise returns false.
778 sub increment_upbytes {
779 _increment_column( shift, 'upbytes', @_);
782 =item increment_downbytes SECONDS
784 Updates this customer's single or primary account (see L<FS::svc_acct>) by
785 the specified number of downbytes. If there is an error, returns the error,
786 otherwise returns false.
790 sub increment_downbytes {
791 _increment_column( shift, 'downbytes', @_);
794 =item increment_totalbytes SECONDS
796 Updates this customer's single or primary account (see L<FS::svc_acct>) by
797 the specified number of totalbytes. If there is an error, returns the error,
798 otherwise returns false.
802 sub increment_totalbytes {
803 _increment_column( shift, 'totalbytes', @_);
806 =item increment_seconds SECONDS
808 Updates this customer's single or primary account (see L<FS::svc_acct>) by
809 the specified number of seconds. If there is an error, returns the error,
810 otherwise returns false.
814 sub increment_seconds {
815 _increment_column( shift, 'seconds', @_);
818 =item _increment_column AMOUNT
820 Updates this customer's single or primary account (see L<FS::svc_acct>) by
821 the specified number of seconds or bytes. If there is an error, returns
822 the error, otherwise returns false.
826 sub _increment_column {
827 my( $self, $column, $amount ) = @_;
828 warn "$me increment_column called: $column, $amount\n"
831 return '' unless $amount;
833 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
834 $self->ncancelled_pkgs;
837 return 'No packages with primary or single services found'.
838 ' to apply pre-paid time';
839 } elsif ( scalar(@cust_pkg) > 1 ) {
840 #maybe have a way to specify the package/account?
841 return 'Multiple packages found to apply pre-paid time';
844 my $cust_pkg = $cust_pkg[0];
845 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
849 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
852 return 'No account found to apply pre-paid time';
853 } elsif ( scalar(@cust_svc) > 1 ) {
854 return 'Multiple accounts found to apply pre-paid time';
857 my $svc_acct = $cust_svc[0]->svc_x;
858 warn " found service svcnum ". $svc_acct->pkgnum.
859 ' ('. $svc_acct->email. ")\n"
862 $column = "increment_$column";
863 $svc_acct->$column($amount);
867 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
869 Inserts a prepayment in the specified amount for this customer. An optional
870 second argument can specify the prepayment identifier for tracking purposes.
871 If there is an error, returns the error, otherwise returns false.
875 sub insert_cust_pay_prepay {
876 shift->insert_cust_pay('PREP', @_);
879 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
881 Inserts a cash payment in the specified amount for this customer. An optional
882 second argument can specify the payment identifier for tracking purposes.
883 If there is an error, returns the error, otherwise returns false.
887 sub insert_cust_pay_cash {
888 shift->insert_cust_pay('CASH', @_);
891 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
893 Inserts a Western Union payment in the specified amount for this customer. An
894 optional second argument can specify the prepayment identifier for tracking
895 purposes. If there is an error, returns the error, otherwise returns false.
899 sub insert_cust_pay_west {
900 shift->insert_cust_pay('WEST', @_);
903 sub insert_cust_pay {
904 my( $self, $payby, $amount ) = splice(@_, 0, 3);
905 my $payinfo = scalar(@_) ? shift : '';
907 my $cust_pay = new FS::cust_pay {
908 'custnum' => $self->custnum,
909 'paid' => sprintf('%.2f', $amount),
910 #'_date' => #date the prepaid card was purchased???
912 'payinfo' => $payinfo,
920 This method is deprecated. See the I<depend_jobnum> option to the insert and
921 order_pkgs methods for a better way to defer provisioning.
923 Re-schedules all exports by calling the B<reexport> method of all associated
924 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
925 otherwise returns false.
932 carp "WARNING: FS::cust_main::reexport is deprectated; ".
933 "use the depend_jobnum option to insert or order_pkgs to delay export";
935 local $SIG{HUP} = 'IGNORE';
936 local $SIG{INT} = 'IGNORE';
937 local $SIG{QUIT} = 'IGNORE';
938 local $SIG{TERM} = 'IGNORE';
939 local $SIG{TSTP} = 'IGNORE';
940 local $SIG{PIPE} = 'IGNORE';
942 my $oldAutoCommit = $FS::UID::AutoCommit;
943 local $FS::UID::AutoCommit = 0;
946 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
947 my $error = $cust_pkg->reexport;
949 $dbh->rollback if $oldAutoCommit;
954 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
959 =item delete NEW_CUSTNUM
961 This deletes the customer. If there is an error, returns the error, otherwise
964 This will completely remove all traces of the customer record. This is not
965 what you want when a customer cancels service; for that, cancel all of the
966 customer's packages (see L</cancel>).
968 If the customer has any uncancelled packages, you need to pass a new (valid)
969 customer number for those packages to be transferred to. Cancelled packages
970 will be deleted. Did I mention that this is NOT what you want when a customer
971 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
973 You can't delete a customer with invoices (see L<FS::cust_bill>),
974 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
975 refunds (see L<FS::cust_refund>).
982 local $SIG{HUP} = 'IGNORE';
983 local $SIG{INT} = 'IGNORE';
984 local $SIG{QUIT} = 'IGNORE';
985 local $SIG{TERM} = 'IGNORE';
986 local $SIG{TSTP} = 'IGNORE';
987 local $SIG{PIPE} = 'IGNORE';
989 my $oldAutoCommit = $FS::UID::AutoCommit;
990 local $FS::UID::AutoCommit = 0;
993 if ( $self->cust_bill ) {
994 $dbh->rollback if $oldAutoCommit;
995 return "Can't delete a customer with invoices";
997 if ( $self->cust_credit ) {
998 $dbh->rollback if $oldAutoCommit;
999 return "Can't delete a customer with credits";
1001 if ( $self->cust_pay ) {
1002 $dbh->rollback if $oldAutoCommit;
1003 return "Can't delete a customer with payments";
1005 if ( $self->cust_refund ) {
1006 $dbh->rollback if $oldAutoCommit;
1007 return "Can't delete a customer with refunds";
1010 my @cust_pkg = $self->ncancelled_pkgs;
1012 my $new_custnum = shift;
1013 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1014 $dbh->rollback if $oldAutoCommit;
1015 return "Invalid new customer number: $new_custnum";
1017 foreach my $cust_pkg ( @cust_pkg ) {
1018 my %hash = $cust_pkg->hash;
1019 $hash{'custnum'} = $new_custnum;
1020 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1021 my $error = $new_cust_pkg->replace($cust_pkg,
1022 options => { $cust_pkg->options },
1025 $dbh->rollback if $oldAutoCommit;
1030 my @cancelled_cust_pkg = $self->all_pkgs;
1031 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1032 my $error = $cust_pkg->delete;
1034 $dbh->rollback if $oldAutoCommit;
1039 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1040 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1042 my $error = $cust_main_invoice->delete;
1044 $dbh->rollback if $oldAutoCommit;
1049 my $error = $self->SUPER::delete;
1051 $dbh->rollback if $oldAutoCommit;
1055 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1060 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ]
1062 Replaces the OLD_RECORD with this one in the database. If there is an error,
1063 returns the error, otherwise returns false.
1065 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1066 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1067 expected and rollback the entire transaction; it is not necessary to call
1068 check_invoicing_list first. Here's an example:
1070 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1077 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1079 : $self->replace_old;
1083 warn "$me replace called\n"
1086 my $curuser = $FS::CurrentUser::CurrentUser;
1087 if ( $self->payby eq 'COMP'
1088 && $self->payby ne $old->payby
1089 && ! $curuser->access_right('Complimentary customer')
1092 return "You are not permitted to create complimentary accounts.";
1095 local($ignore_expired_card) = 1
1096 if $old->payby =~ /^(CARD|DCRD)$/
1097 && $self->payby =~ /^(CARD|DCRD)$/
1098 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1100 local $SIG{HUP} = 'IGNORE';
1101 local $SIG{INT} = 'IGNORE';
1102 local $SIG{QUIT} = 'IGNORE';
1103 local $SIG{TERM} = 'IGNORE';
1104 local $SIG{TSTP} = 'IGNORE';
1105 local $SIG{PIPE} = 'IGNORE';
1107 my $oldAutoCommit = $FS::UID::AutoCommit;
1108 local $FS::UID::AutoCommit = 0;
1111 my $error = $self->SUPER::replace($old);
1114 $dbh->rollback if $oldAutoCommit;
1118 if ( @param ) { # INVOICING_LIST_ARYREF
1119 my $invoicing_list = shift @param;
1120 $error = $self->check_invoicing_list( $invoicing_list );
1122 $dbh->rollback if $oldAutoCommit;
1125 $self->invoicing_list( $invoicing_list );
1128 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1129 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1130 # card/check/lec info has changed, want to retry realtime_ invoice events
1131 my $error = $self->retry_realtime;
1133 $dbh->rollback if $oldAutoCommit;
1138 unless ( $import || $skip_fuzzyfiles ) {
1139 $error = $self->queue_fuzzyfiles_update;
1141 $dbh->rollback if $oldAutoCommit;
1142 return "updating fuzzy search cache: $error";
1146 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1151 =item queue_fuzzyfiles_update
1153 Used by insert & replace to update the fuzzy search cache
1157 sub queue_fuzzyfiles_update {
1160 local $SIG{HUP} = 'IGNORE';
1161 local $SIG{INT} = 'IGNORE';
1162 local $SIG{QUIT} = 'IGNORE';
1163 local $SIG{TERM} = 'IGNORE';
1164 local $SIG{TSTP} = 'IGNORE';
1165 local $SIG{PIPE} = 'IGNORE';
1167 my $oldAutoCommit = $FS::UID::AutoCommit;
1168 local $FS::UID::AutoCommit = 0;
1171 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1172 my $error = $queue->insert( map $self->getfield($_),
1173 qw(first last company)
1176 $dbh->rollback if $oldAutoCommit;
1177 return "queueing job (transaction rolled back): $error";
1180 if ( $self->ship_last ) {
1181 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1182 $error = $queue->insert( map $self->getfield("ship_$_"),
1183 qw(first last company)
1186 $dbh->rollback if $oldAutoCommit;
1187 return "queueing job (transaction rolled back): $error";
1191 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1198 Checks all fields to make sure this is a valid customer record. If there is
1199 an error, returns the error, otherwise returns false. Called by the insert
1200 and replace methods.
1207 warn "$me check BEFORE: \n". $self->_dump
1211 $self->ut_numbern('custnum')
1212 || $self->ut_number('agentnum')
1213 || $self->ut_textn('agent_custid')
1214 || $self->ut_number('refnum')
1215 || $self->ut_textn('custbatch')
1216 || $self->ut_name('last')
1217 || $self->ut_name('first')
1218 || $self->ut_snumbern('birthdate')
1219 || $self->ut_snumbern('signupdate')
1220 || $self->ut_textn('company')
1221 || $self->ut_text('address1')
1222 || $self->ut_textn('address2')
1223 || $self->ut_text('city')
1224 || $self->ut_textn('county')
1225 || $self->ut_textn('state')
1226 || $self->ut_country('country')
1227 || $self->ut_anything('comments')
1228 || $self->ut_numbern('referral_custnum')
1229 || $self->ut_textn('stateid')
1230 || $self->ut_textn('stateid_state')
1231 || $self->ut_textn('invoice_terms')
1233 #barf. need message catalogs. i18n. etc.
1234 $error .= "Please select an advertising source."
1235 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1236 return $error if $error;
1238 return "Unknown agent"
1239 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1241 return "Unknown refnum"
1242 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1244 return "Unknown referring custnum: ". $self->referral_custnum
1245 unless ! $self->referral_custnum
1246 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1248 if ( $self->ss eq '' ) {
1253 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1254 or return "Illegal social security number: ". $self->ss;
1255 $self->ss("$1-$2-$3");
1259 # bad idea to disable, causes billing to fail because of no tax rates later
1260 # unless ( $import ) {
1261 unless ( qsearch('cust_main_county', {
1262 'country' => $self->country,
1265 return "Unknown state/county/country: ".
1266 $self->state. "/". $self->county. "/". $self->country
1267 unless qsearch('cust_main_county',{
1268 'state' => $self->state,
1269 'county' => $self->county,
1270 'country' => $self->country,
1276 $self->ut_phonen('daytime', $self->country)
1277 || $self->ut_phonen('night', $self->country)
1278 || $self->ut_phonen('fax', $self->country)
1279 || $self->ut_zip('zip', $self->country)
1281 return $error if $error;
1283 if ( $conf->exists('cust_main-require_phone')
1284 && ! length($self->daytime) && ! length($self->night)
1287 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1289 : FS::Msgcat::_gettext('daytime');
1290 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1292 : FS::Msgcat::_gettext('night');
1294 return "$daytime_label or $night_label is required"
1298 if ( $self->has_ship_address
1299 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1300 $self->addr_fields )
1304 $self->ut_name('ship_last')
1305 || $self->ut_name('ship_first')
1306 || $self->ut_textn('ship_company')
1307 || $self->ut_text('ship_address1')
1308 || $self->ut_textn('ship_address2')
1309 || $self->ut_text('ship_city')
1310 || $self->ut_textn('ship_county')
1311 || $self->ut_textn('ship_state')
1312 || $self->ut_country('ship_country')
1314 return $error if $error;
1316 #false laziness with above
1317 unless ( qsearchs('cust_main_county', {
1318 'country' => $self->ship_country,
1321 return "Unknown ship_state/ship_county/ship_country: ".
1322 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1323 unless qsearch('cust_main_county',{
1324 'state' => $self->ship_state,
1325 'county' => $self->ship_county,
1326 'country' => $self->ship_country,
1332 $self->ut_phonen('ship_daytime', $self->ship_country)
1333 || $self->ut_phonen('ship_night', $self->ship_country)
1334 || $self->ut_phonen('ship_fax', $self->ship_country)
1335 || $self->ut_zip('ship_zip', $self->ship_country)
1337 return $error if $error;
1339 return "Unit # is required."
1340 if $self->ship_address2 =~ /^\s*$/
1341 && $conf->exists('cust_main-require_address2');
1343 } else { # ship_ info eq billing info, so don't store dup info in database
1345 $self->setfield("ship_$_", '')
1346 foreach $self->addr_fields;
1348 return "Unit # is required."
1349 if $self->address2 =~ /^\s*$/
1350 && $conf->exists('cust_main-require_address2');
1354 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1355 # or return "Illegal payby: ". $self->payby;
1357 FS::payby->can_payby($self->table, $self->payby)
1358 or return "Illegal payby: ". $self->payby;
1360 $error = $self->ut_numbern('paystart_month')
1361 || $self->ut_numbern('paystart_year')
1362 || $self->ut_numbern('payissue')
1363 || $self->ut_textn('paytype')
1365 return $error if $error;
1367 if ( $self->payip eq '' ) {
1370 $error = $self->ut_ip('payip');
1371 return $error if $error;
1374 # If it is encrypted and the private key is not availaible then we can't
1375 # check the credit card.
1377 my $check_payinfo = 1;
1379 if ($self->is_encrypted($self->payinfo)) {
1383 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1385 my $payinfo = $self->payinfo;
1386 $payinfo =~ s/\D//g;
1387 $payinfo =~ /^(\d{13,16})$/
1388 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1390 $self->payinfo($payinfo);
1392 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1394 return gettext('unknown_card_type')
1395 if cardtype($self->payinfo) eq "Unknown";
1397 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1399 return 'Banned credit card: banned on '.
1400 time2str('%a %h %o at %r', $ban->_date).
1401 ' by '. $ban->otaker.
1402 ' (ban# '. $ban->bannum. ')';
1405 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1406 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1407 $self->paycvv =~ /^(\d{4})$/
1408 or return "CVV2 (CID) for American Express cards is four digits.";
1411 $self->paycvv =~ /^(\d{3})$/
1412 or return "CVV2 (CVC2/CID) is three digits.";
1419 my $cardtype = cardtype($payinfo);
1420 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1422 return "Start date or issue number is required for $cardtype cards"
1423 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1425 return "Start month must be between 1 and 12"
1426 if $self->paystart_month
1427 and $self->paystart_month < 1 || $self->paystart_month > 12;
1429 return "Start year must be 1990 or later"
1430 if $self->paystart_year
1431 and $self->paystart_year < 1990;
1433 return "Issue number must be beween 1 and 99"
1435 and $self->payissue < 1 || $self->payissue > 99;
1438 $self->paystart_month('');
1439 $self->paystart_year('');
1440 $self->payissue('');
1443 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1445 my $payinfo = $self->payinfo;
1446 $payinfo =~ s/[^\d\@]//g;
1447 if ( $conf->exists('echeck-nonus') ) {
1448 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1449 $payinfo = "$1\@$2";
1451 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1452 $payinfo = "$1\@$2";
1454 $self->payinfo($payinfo);
1457 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1459 return 'Banned ACH account: banned on '.
1460 time2str('%a %h %o at %r', $ban->_date).
1461 ' by '. $ban->otaker.
1462 ' (ban# '. $ban->bannum. ')';
1465 } elsif ( $self->payby eq 'LECB' ) {
1467 my $payinfo = $self->payinfo;
1468 $payinfo =~ s/\D//g;
1469 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1471 $self->payinfo($payinfo);
1474 } elsif ( $self->payby eq 'BILL' ) {
1476 $error = $self->ut_textn('payinfo');
1477 return "Illegal P.O. number: ". $self->payinfo if $error;
1480 } elsif ( $self->payby eq 'COMP' ) {
1482 my $curuser = $FS::CurrentUser::CurrentUser;
1483 if ( ! $self->custnum
1484 && ! $curuser->access_right('Complimentary customer')
1487 return "You are not permitted to create complimentary accounts."
1490 $error = $self->ut_textn('payinfo');
1491 return "Illegal comp account issuer: ". $self->payinfo if $error;
1494 } elsif ( $self->payby eq 'PREPAY' ) {
1496 my $payinfo = $self->payinfo;
1497 $payinfo =~ s/\W//g; #anything else would just confuse things
1498 $self->payinfo($payinfo);
1499 $error = $self->ut_alpha('payinfo');
1500 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1501 return "Unknown prepayment identifier"
1502 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1507 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1508 return "Expiration date required"
1509 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1513 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1514 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1515 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1516 ( $m, $y ) = ( $3, "20$2" );
1518 return "Illegal expiration date: ". $self->paydate;
1520 $self->paydate("$y-$m-01");
1521 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1522 return gettext('expired_card')
1524 && !$ignore_expired_card
1525 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1528 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1529 ( ! $conf->exists('require_cardname')
1530 || $self->payby !~ /^(CARD|DCRD)$/ )
1532 $self->payname( $self->first. " ". $self->getfield('last') );
1534 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1535 or return gettext('illegal_name'). " payname: ". $self->payname;
1539 foreach my $flag (qw( tax spool_cdr squelch_cdr )) {
1540 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1544 $self->otaker(getotaker) unless $self->otaker;
1546 warn "$me check AFTER: \n". $self->_dump
1549 $self->SUPER::check;
1554 Returns a list of fields which have ship_ duplicates.
1559 qw( last first company
1560 address1 address2 city county state zip country
1565 =item has_ship_address
1567 Returns true if this customer record has a separate shipping address.
1571 sub has_ship_address {
1573 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1578 Returns all packages (see L<FS::cust_pkg>) for this customer.
1585 return $self->num_pkgs unless wantarray;
1588 if ( $self->{'_pkgnum'} ) {
1589 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1591 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1594 sort sort_packages @cust_pkg;
1599 Synonym for B<all_pkgs>.
1604 shift->all_pkgs(@_);
1607 =item ncancelled_pkgs
1609 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1613 sub ncancelled_pkgs {
1616 return $self->num_ncancelled_pkgs unless wantarray;
1619 if ( $self->{'_pkgnum'} ) {
1621 warn "$me ncancelled_pkgs: returning cached objects"
1624 @cust_pkg = grep { ! $_->getfield('cancel') }
1625 values %{ $self->{'_pkgnum'}->cache };
1629 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1630 $self->custnum. "\n"
1634 qsearch( 'cust_pkg', {
1635 'custnum' => $self->custnum,
1639 qsearch( 'cust_pkg', {
1640 'custnum' => $self->custnum,
1645 sort sort_packages @cust_pkg;
1649 # This should be generalized to use config options to determine order.
1651 if ( $a->get('cancel') and $b->get('cancel') ) {
1652 $a->pkgnum <=> $b->pkgnum;
1653 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1654 return -1 if $b->get('cancel');
1655 return 1 if $a->get('cancel');
1658 $a->pkgnum <=> $b->pkgnum;
1662 =item suspended_pkgs
1664 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1668 sub suspended_pkgs {
1670 grep { $_->susp } $self->ncancelled_pkgs;
1673 =item unflagged_suspended_pkgs
1675 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1676 customer (thouse packages without the `manual_flag' set).
1680 sub unflagged_suspended_pkgs {
1682 return $self->suspended_pkgs
1683 unless dbdef->table('cust_pkg')->column('manual_flag');
1684 grep { ! $_->manual_flag } $self->suspended_pkgs;
1687 =item unsuspended_pkgs
1689 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1694 sub unsuspended_pkgs {
1696 grep { ! $_->susp } $self->ncancelled_pkgs;
1699 =item num_cancelled_pkgs
1701 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1706 sub num_cancelled_pkgs {
1707 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1710 sub num_ncancelled_pkgs {
1711 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1715 my( $self ) = shift;
1716 my $sql = scalar(@_) ? shift : '';
1717 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1718 my $sth = dbh->prepare(
1719 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1720 ) or die dbh->errstr;
1721 $sth->execute($self->custnum) or die $sth->errstr;
1722 $sth->fetchrow_arrayref->[0];
1727 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1728 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1729 on success or a list of errors.
1735 grep { $_->unsuspend } $self->suspended_pkgs;
1740 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1742 Returns a list: an empty list on success or a list of errors.
1748 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1751 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1753 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1754 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1755 of a list of pkgparts; the hashref has the following keys:
1759 =item pkgparts - listref of pkgparts
1761 =item (other options are passed to the suspend method)
1766 Returns a list: an empty list on success or a list of errors.
1770 sub suspend_if_pkgpart {
1772 my (@pkgparts, %opt);
1773 if (ref($_[0]) eq 'HASH'){
1774 @pkgparts = @{$_[0]{pkgparts}};
1779 grep { $_->suspend(%opt) }
1780 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1781 $self->unsuspended_pkgs;
1784 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1786 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1787 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1788 instead of a list of pkgparts; the hashref has the following keys:
1792 =item pkgparts - listref of pkgparts
1794 =item (other options are passed to the suspend method)
1798 Returns a list: an empty list on success or a list of errors.
1802 sub suspend_unless_pkgpart {
1804 my (@pkgparts, %opt);
1805 if (ref($_[0]) eq 'HASH'){
1806 @pkgparts = @{$_[0]{pkgparts}};
1811 grep { $_->suspend(%opt) }
1812 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1813 $self->unsuspended_pkgs;
1816 =item cancel [ OPTION => VALUE ... ]
1818 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1820 Available options are:
1824 =item quiet - can be set true to supress email cancellation notices.
1826 =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.
1828 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1832 Always returns a list: an empty list on success or a list of errors.
1837 my( $self, %opt ) = @_;
1839 warn "$me cancel called on customer ". $self->custnum. " with options ".
1840 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1843 return ( 'access denied' )
1844 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1846 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1848 #should try decryption (we might have the private key)
1849 # and if not maybe queue a job for the server that does?
1850 return ( "Can't (yet) ban encrypted credit cards" )
1851 if $self->is_encrypted($self->payinfo);
1853 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1854 my $error = $ban->insert;
1855 return ( $error ) if $error;
1859 my @pkgs = $self->ncancelled_pkgs;
1861 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1862 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1865 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1868 sub _banned_pay_hashref {
1879 'payby' => $payby2ban{$self->payby},
1880 'payinfo' => md5_base64($self->payinfo),
1881 #don't ever *search* on reason! #'reason' =>
1887 Returns all notes (see L<FS::cust_main_note>) for this customer.
1894 qsearch( 'cust_main_note',
1895 { 'custnum' => $self->custnum },
1897 'ORDER BY _DATE DESC'
1903 Returns the agent (see L<FS::agent>) for this customer.
1909 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1912 =item bill_and_collect
1914 Cancels and suspends any packages due, generates bills, applies payments and
1917 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1919 Options are passed as name-value pairs. Currently available options are:
1925 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:
1929 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1933 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.
1937 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1941 If set true, re-charges setup fees.
1945 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)
1951 sub bill_and_collect {
1952 my( $self, %options ) = @_;
1958 #$options{actual_time} not $options{time} because freeside-daily -d is for
1959 #pre-printing invoices
1960 my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
1961 $self->ncancelled_pkgs;
1963 foreach my $cust_pkg ( @cancel_pkgs ) {
1964 my $error = $cust_pkg->cancel;
1965 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1966 " for custnum ". $self->custnum. ": $error"
1974 #$options{actual_time} not $options{time} because freeside-daily -d is for
1975 #pre-printing invoices
1978 && ( ( $_->part_pkg->is_prepaid
1980 && $_->bill < $options{actual_time}
1983 && $_->adjourn <= $options{actual_time}
1987 $self->ncancelled_pkgs;
1989 foreach my $cust_pkg ( @susp_pkgs ) {
1990 my $error = $cust_pkg->suspend;
1991 warn "Error suspending package ". $cust_pkg->pkgnum.
1992 " for custnum ". $self->custnum. ": $error"
2000 my $error = $self->bill( %options );
2001 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
2003 $self->apply_payments_and_credits;
2005 $error = $self->collect( %options );
2006 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2012 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2013 conjunction with the collect method by calling B<bill_and_collect>.
2015 If there is an error, returns the error, otherwise returns false.
2017 Options are passed as name-value pairs. Currently available options are:
2023 If set true, re-charges setup fees.
2027 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:
2031 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2035 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2037 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2041 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.
2048 my( $self, %options ) = @_;
2049 return '' if $self->payby eq 'COMP';
2050 warn "$me bill customer ". $self->custnum. "\n"
2053 my $time = $options{'time'} || time;
2056 local $SIG{HUP} = 'IGNORE';
2057 local $SIG{INT} = 'IGNORE';
2058 local $SIG{QUIT} = 'IGNORE';
2059 local $SIG{TERM} = 'IGNORE';
2060 local $SIG{TSTP} = 'IGNORE';
2061 local $SIG{PIPE} = 'IGNORE';
2063 my $oldAutoCommit = $FS::UID::AutoCommit;
2064 local $FS::UID::AutoCommit = 0;
2067 $self->select_for_update; #mutex
2069 my @cust_bill_pkg = ();
2072 # find the packages which are due for billing, find out how much they are
2073 # & generate invoice database.
2076 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2080 my @precommit_hooks = ();
2082 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2083 foreach my $cust_pkg (@cust_pkgs) {
2085 #NO!! next if $cust_pkg->cancel;
2086 next if $cust_pkg->getfield('cancel');
2088 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2090 #? to avoid use of uninitialized value errors... ?
2091 $cust_pkg->setfield('bill', '')
2092 unless defined($cust_pkg->bill);
2094 #my $part_pkg = $cust_pkg->part_pkg;
2096 my $real_pkgpart = $cust_pkg->pkgpart;
2097 my %hash = $cust_pkg->hash;
2099 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2101 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2104 $self->_make_lines( 'part_pkg' => $part_pkg,
2105 'cust_pkg' => $cust_pkg,
2106 'precommit_hooks' => \@precommit_hooks,
2107 'line_items' => \@cust_bill_pkg,
2108 'setup' => \$total_setup,
2109 'recur' => \$total_recur,
2110 'tax_matrix' => \%taxlisthash,
2112 'options' => \%options,
2115 $dbh->rollback if $oldAutoCommit;
2119 } #foreach my $part_pkg
2121 } #foreach my $cust_pkg
2123 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2124 #but do commit any package date cycling that happened
2125 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2129 my $postal_pkg = $self->charge_postal_fee();
2130 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2131 $dbh->rollback if $oldAutoCommit;
2132 return "can't charge postal invoice fee for customer ".
2133 $self->custnum. ": $postal_pkg";
2135 if ( $postal_pkg ) {
2136 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2138 $self->_make_lines( 'part_pkg' => $part_pkg,
2139 'cust_pkg' => $postal_pkg,
2140 'precommit_hooks' => \@precommit_hooks,
2141 'line_items' => \@cust_bill_pkg,
2142 'setup' => \$total_setup,
2143 'recur' => \$total_recur,
2144 'tax_matrix' => \%taxlisthash,
2146 'options' => \%options,
2149 $dbh->rollback if $oldAutoCommit;
2155 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2156 foreach my $tax ( keys %taxlisthash ) {
2157 my $tax_object = shift @{ $taxlisthash{$tax} };
2158 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2159 my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2160 unless (ref($listref_or_error)) {
2161 $dbh->rollback if $oldAutoCommit;
2162 return $listref_or_error;
2164 unshift @{ $taxlisthash{$tax} }, $tax_object;
2166 warn "adding ". $listref_or_error->[1].
2167 " as ". $listref_or_error->[0]. "\n"
2169 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2170 if ( $taxname{ $listref_or_error->[0] } ) {
2171 push @{ $taxname{ $listref_or_error->[0] } }, $tax_object->taxname;
2173 $taxname{ $listref_or_error->[0] } = [ $tax_object->taxname ];
2178 #some taxes are taxed
2181 warn "finding taxed taxes...\n" if $DEBUG > 2;
2182 foreach my $tax ( keys %taxlisthash ) {
2183 my $tax_object = shift @{ $taxlisthash{$tax} };
2184 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2186 next unless $tax_object->can('tax_on_tax');
2188 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2189 my $totname = ref( $tot ). ' '. $tot->taxnum;
2191 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2193 next unless exists( $taxlisthash{ $totname } ); # only increase
2195 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2196 if ( exists( $totlisthash{ $totname } ) ) {
2197 push @{ $totlisthash{ $totname } }, $tax{ $tax_object->taxname };
2199 $totlisthash{ $totname } = [ $tot, $tax{ $tax_object->taxname } ];
2204 warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2205 foreach my $tax ( keys %totlisthash ) {
2206 my $tax_object = shift @{ $totlisthash{$tax} };
2207 warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2209 my $listref_or_error = $tax_object->taxline( @{ $totlisthash{$tax} } );
2210 unless (ref($listref_or_error)) {
2211 $dbh->rollback if $oldAutoCommit;
2212 return $listref_or_error;
2215 warn "adding taxed tax amount ". $listref_or_error->[1].
2216 " as ". $tax_object->taxname. "\n"
2218 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2221 #consolidate and create tax line items
2222 warn "consolidating and generating...\n" if $DEBUG > 2;
2223 foreach my $taxname ( keys %taxname ) {
2226 warn "adding $taxname\n" if $DEBUG > 1;
2227 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2228 $tax += $tax{$taxitem} unless $seen{$taxitem};
2229 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2233 $tax = sprintf('%.2f', $tax );
2234 $total_setup = sprintf('%.2f', $total_setup+$tax );
2236 push @cust_bill_pkg, new FS::cust_bill_pkg {
2242 'itemdesc' => $taxname,
2247 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2249 #create the new invoice
2250 my $cust_bill = new FS::cust_bill ( {
2251 'custnum' => $self->custnum,
2252 '_date' => ( $options{'invoice_time'} || $time ),
2253 'charged' => $charged,
2255 my $error = $cust_bill->insert;
2257 $dbh->rollback if $oldAutoCommit;
2258 return "can't create invoice for customer #". $self->custnum. ": $error";
2261 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2262 $cust_bill_pkg->invnum($cust_bill->invnum);
2263 my $error = $cust_bill_pkg->insert;
2265 $dbh->rollback if $oldAutoCommit;
2266 return "can't create invoice line item: $error";
2271 foreach my $hook ( @precommit_hooks ) {
2273 &{$hook}; #($self) ?
2276 $dbh->rollback if $oldAutoCommit;
2277 return "$@ running precommit hook $hook\n";
2281 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2287 my ($self, %params) = @_;
2289 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2290 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2291 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2292 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2293 my $total_setup = $params{setup} or die "no setup accumulator specified";
2294 my $total_recur = $params{recur} or die "no recur accumulator specified";
2295 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2296 my $time = $params{'time'} or die "no time specified";
2297 my (%options) = %{$params{options}}; #hmmm only for 'resetup'
2300 my $real_pkgpart = $cust_pkg->pkgpart;
2301 my %hash = $cust_pkg->hash;
2302 my $old_cust_pkg = new FS::cust_pkg \%hash;
2308 $cust_pkg->pkgpart($part_pkg->pkgpart);
2316 if ( ! $cust_pkg->setup &&
2318 ( $conf->exists('disable_setup_suspended_pkgs') &&
2319 ! $cust_pkg->getfield('susp')
2320 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2322 || $options{'resetup'}
2325 warn " bill setup\n" if $DEBUG > 1;
2328 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2329 return "$@ running calc_setup for $cust_pkg\n"
2332 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2334 $cust_pkg->setfield('setup', $time)
2335 unless $cust_pkg->setup;
2336 #do need it, but it won't get written to the db
2337 #|| $cust_pkg->pkgpart != $real_pkgpart;
2342 # bill recurring fee
2345 #XXX unit stuff here too
2349 if ( $part_pkg->getfield('freq') ne '0' &&
2350 ! $cust_pkg->getfield('susp') &&
2351 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2354 # XXX should this be a package event? probably. events are called
2355 # at collection time at the moment, though...
2356 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2357 if $part_pkg->can('reset_usage');
2358 #don't want to reset usage just cause we want a line item??
2359 #&& $part_pkg->pkgpart == $real_pkgpart;
2361 warn " bill recur\n" if $DEBUG > 1;
2364 # XXX shared with $recur_prog
2365 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2367 #over two params! lets at least switch to a hashref for the rest...
2368 my %param = ( 'precommit_hooks' => $precommit_hooks, );
2370 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2371 return "$@ running calc_recur for $cust_pkg\n"
2375 #change this bit to use Date::Manip? CAREFUL with timezones (see
2376 # mailing list archive)
2377 my ($sec,$min,$hour,$mday,$mon,$year) =
2378 (localtime($sdate) )[0,1,2,3,4,5];
2380 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2381 # only for figuring next bill date, nothing else, so, reset $sdate again
2383 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2384 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2385 $cust_pkg->last_bill($sdate);
2387 if ( $part_pkg->freq =~ /^\d+$/ ) {
2388 $mon += $part_pkg->freq;
2389 until ( $mon < 12 ) { $mon -= 12; $year++; }
2390 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2392 $mday += $weeks * 7;
2393 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2396 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2400 return "unparsable frequency: ". $part_pkg->freq;
2402 $cust_pkg->setfield('bill',
2403 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2407 warn "\$setup is undefined" unless defined($setup);
2408 warn "\$recur is undefined" unless defined($recur);
2409 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2412 # If there's line items, create em cust_bill_pkg records
2413 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2418 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2419 # hmm.. and if just the options are modified in some weird price plan?
2421 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2424 my $error = $cust_pkg->replace( $old_cust_pkg,
2425 'options' => { $cust_pkg->options },
2427 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2428 if $error; #just in case
2431 $setup = sprintf( "%.2f", $setup );
2432 $recur = sprintf( "%.2f", $recur );
2433 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2434 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2436 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2437 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2440 if ( $setup != 0 || $recur != 0 ) {
2442 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2445 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2447 warn " adding customer package invoice detail: $_\n"
2448 foreach @cust_pkg_detail;
2450 push @details, @cust_pkg_detail;
2452 my $cust_bill_pkg = new FS::cust_bill_pkg {
2453 'pkgnum' => $cust_pkg->pkgnum,
2455 'unitsetup' => $unitsetup,
2457 'unitrecur' => $unitrecur,
2458 'quantity' => $cust_pkg->quantity,
2459 'details' => \@details,
2462 if ( $part_pkg->option('recur_temporality') eq 'preceding' ) {
2463 $cust_bill_pkg->sdate( $hash{last_bill} );
2464 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2465 } else { #if ( $part_pkg->option('recur_temporality') eq 'upcoming' ) {
2466 $cust_bill_pkg->sdate( $sdate );
2467 $cust_bill_pkg->edate( $cust_pkg->bill );
2470 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2471 unless $part_pkg->pkgpart == $real_pkgpart;
2473 $$total_setup += $setup;
2474 $$total_recur += $recur;
2481 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg);
2482 return $error if $error;
2484 push @$cust_bill_pkgs, $cust_bill_pkg;
2486 } #if $setup != 0 || $recur != 0
2496 my $part_pkg = shift;
2497 my $taxlisthash = shift;
2498 my $cust_bill_pkg = shift;
2499 my $cust_pkg = shift;
2501 my %cust_bill_pkg = ();
2505 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2510 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
2511 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
2512 push @classes, 'setup' if $cust_bill_pkg->setup;
2513 push @classes, 'recur' if $cust_bill_pkg->recur;
2515 if ( $conf->exists('enable_taxproducts')
2516 && (scalar($part_pkg->part_pkg_taxoverride) || $part_pkg->has_taxproduct)
2517 && ( $self->tax !~ /Y/i && $self->payby ne 'COMP' )
2521 foreach my $class (@classes) {
2522 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $prefix );
2523 return $err_or_ref unless ref($err_or_ref);
2524 $taxes{$class} = $err_or_ref;
2527 unless (exists $taxes{''}) {
2528 my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $prefix );
2529 return $err_or_ref unless ref($err_or_ref);
2530 $taxes{''} = $err_or_ref;
2533 } elsif ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
2535 my %taxhash = map { $_ => $self->get("$prefix$_") }
2536 qw( state county country );
2538 $taxhash{'taxclass'} = $part_pkg->taxclass;
2540 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2543 $taxhash{'taxclass'} = '';
2544 @taxes = qsearch( 'cust_main_county', \%taxhash );
2547 #one more try at a whole-country tax rate
2549 $taxhash{$_} = '' foreach qw( state county );
2550 @taxes = qsearch( 'cust_main_county', \%taxhash );
2553 $taxes{''} = [ @taxes ];
2554 $taxes{'setup'} = [ @taxes ];
2555 $taxes{'recur'} = [ @taxes ];
2556 $taxes{$_} = [ @taxes ] foreach (@classes);
2558 # maybe eliminate this entirely, along with all the 0% records
2561 "fatal: can't find tax rate for state/county/country/taxclass ".
2562 join('/', ( map $self->get("$prefix$_"),
2563 qw(state county country)
2565 $part_pkg->taxclass ). "\n";
2568 } #if $conf->exists('enable_taxproducts') ...
2570 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!')
2571 if $cust_pkg->part_pkg->option('separate_usage', 'Hush!' );
2572 my $want_duplicate =
2573 $cust_pkg->part_pkg->option('summarize_usage', 'Hush!') &&
2574 $cust_pkg->part_pkg->option('usage_section', 'Hush!');
2576 #BUNK. DO NOT CREATE DUPLICATE cust_bill_pkg!!!!!!!!!!!!
2578 # # XXX this mostly goes away with cust_bill_pkg refactor
2580 # $cust_bill_pkg{setup} = $cust_bill_pkg if $cust_bill_pkg->setup;
2581 # $cust_bill_pkg{recur} = $cust_bill_pkg if $cust_bill_pkg->recur;
2584 # #split setup and recur
2585 # if ($cust_bill_pkg->setup && $cust_bill_pkg->recur) {
2586 # my $cust_bill_pkg_recur = new FS::cust_bill_pkg { $cust_bill_pkg->hash };
2587 # $cust_bill_pkg_recur->details($cust_bill_pkg->
2588 # $cust_bill_pkg_recur->setup(0);
2589 # $cust_bill_pkg_recur->unitsetup(0);
2590 # $cust_bill_pkg{recur} = $cust_bill_pkg_recur;
2592 # $cust_bill_pkg->set('details', []);
2593 # $cust_bill_pkg->recur(0);
2594 # $cust_bill_pkg->unitrecur(0);
2595 # $cust_bill_pkg->type('');
2598 # #split usage from recur
2599 # my $usage = sprintf( "%.2f", $cust_bill_pkg{recur}->usage );
2600 # warn "usage is $usage\n" if $DEBUG;
2602 # my $cust_bill_pkg_usage =
2603 # new FS::cust_bill_pkg { $cust_bill_pkg{recur}->hash };
2604 # $cust_bill_pkg_usage->recur( $usage );
2605 # $cust_bill_pkg_usage->type( 'U' );
2606 # $cust_bill_pkg_usage->duplicate( $want_duplicate ? 'Y' : '' );
2607 # $cust_bill_pkg_usage->section( $section );
2608 # $cust_bill_pkg_usage->post_total( $want_duplicate ? 'Y' : '' );
2609 # my $recur = sprintf( "%.2f", $cust_bill_pkg{recur}->recur - $usage );
2610 # $cust_bill_pkg{recur}->recur( $recur );
2611 # $cust_bill_pkg{recur}->type( '' );
2612 # $cust_bill_pkg{recur}->set('details', []);
2613 # $cust_bill_pkg{''} = $cust_bill_pkg_usage;
2616 # #subdivide usage by usage_class
2617 # if (exists($cust_bill_pkg{''})) {
2618 # foreach my $class (grep {$_ && $_ ne 'setup' && $_ ne 'recur' } @classes) {
2619 # my $usage = sprintf( "%.2f", $cust_bill_pkg{''}->usage($class) );
2620 # my $cust_bill_pkg_usage =
2621 # new FS::cust_bill_pkg { $cust_bill_pkg{''}->hash };
2622 # $cust_bill_pkg_usage->recur( $usage );
2623 # $cust_bill_pkg_usage->set('details', []);
2624 # my $classless = sprintf( "%.2f", $cust_bill_pkg{''}->recur - $usage );
2625 # $cust_bill_pkg{''}->recur( $classless );
2626 # $cust_bill_pkg{$class} = $cust_bill_pkg_usage;
2628 # delete $cust_bill_pkg{''} unless $cust_bill_pkg{''}->recur;
2631 # foreach my $key (keys %cust_bill_pkg) {
2632 # my @taxes = @{ $taxes{$key} };
2633 # my $cust_bill_pkg = $cust_bill_pkg{$key};
2635 # foreach my $tax ( @taxes ) {
2636 # my $taxname = ref( $tax ). ' '. $tax->taxnum;
2637 # if ( exists( $taxlisthash->{ $taxname } ) ) {
2638 # push @{ $taxlisthash->{ $taxname } }, $cust_bill_pkg;
2640 # $taxlisthash->{ $taxname } = [ $tax, $cust_bill_pkg ];
2645 # # sort setup,recur,'', and the rest numeric && return
2646 # my @result = map { $cust_bill_pkg{$_} }
2647 # sort { my $ad = ($a=~/^\d+$/); my $bd = ($b=~/^\d+$/);
2648 # ( $ad cmp $bd ) || ( $ad ? $a<=>$b : $b cmp $a )
2650 # keys %cust_bill_pkg;
2657 my $part_pkg = shift;
2662 my $geocode = $self->geocode('cch');
2664 my @taxclassnums = map { $_->taxclassnum }
2665 $part_pkg->part_pkg_taxoverride($class);
2667 unless (@taxclassnums) {
2668 @taxclassnums = map { $_->taxclassnum }
2669 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
2671 warn "Found taxclassnum values of ". join(',', @taxclassnums)
2676 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2678 @taxes = qsearch({ 'table' => 'tax_rate',
2679 'hashref' => { 'geocode' => $geocode, },
2680 'extra_sql' => $extra_sql,
2682 if scalar(@taxclassnums);
2684 # maybe eliminate this entirely, along with all the 0% records
2687 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2688 join('/', ( map $self->get("$prefix$_"),
2691 $part_pkg->taxproduct_description,
2692 $part_pkg->pkgpart ). "\n";
2695 warn "Found taxes ".
2696 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
2703 =item collect OPTIONS
2705 (Attempt to) collect money for this customer's outstanding invoices (see
2706 L<FS::cust_bill>). Usually used after the bill method.
2708 Actions are now triggered by billing events; see L<FS::part_event> and the
2709 billing events web interface. Old-style invoice events (see
2710 L<FS::part_bill_event>) have been deprecated.
2712 If there is an error, returns the error, otherwise returns false.
2714 Options are passed as name-value pairs.
2716 Currently available options are:
2722 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.
2726 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2730 set true to surpress email card/ACH decline notices.
2734 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2738 allows for one time override of normal customer billing method
2742 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)
2750 my( $self, %options ) = @_;
2751 my $invoice_time = $options{'invoice_time'} || time;
2754 local $SIG{HUP} = 'IGNORE';
2755 local $SIG{INT} = 'IGNORE';
2756 local $SIG{QUIT} = 'IGNORE';
2757 local $SIG{TERM} = 'IGNORE';
2758 local $SIG{TSTP} = 'IGNORE';
2759 local $SIG{PIPE} = 'IGNORE';
2761 my $oldAutoCommit = $FS::UID::AutoCommit;
2762 local $FS::UID::AutoCommit = 0;
2765 $self->select_for_update; #mutex
2768 my $balance = $self->balance;
2769 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2772 if ( exists($options{'retry_card'}) ) {
2773 carp 'retry_card option passed to collect is deprecated; use retry';
2774 $options{'retry'} ||= $options{'retry_card'};
2776 if ( exists($options{'retry'}) && $options{'retry'} ) {
2777 my $error = $self->retry_realtime;
2779 $dbh->rollback if $oldAutoCommit;
2784 # false laziness w/pay_batch::import_results
2786 my $due_cust_event = $self->due_cust_event(
2787 'debug' => ( $options{'debug'} || 0 ),
2788 'time' => $invoice_time,
2789 'check_freq' => $options{'check_freq'},
2791 unless( ref($due_cust_event) ) {
2792 $dbh->rollback if $oldAutoCommit;
2793 return $due_cust_event;
2796 foreach my $cust_event ( @$due_cust_event ) {
2800 #re-eval event conditions (a previous event could have changed things)
2801 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2802 #don't leave stray "new/locked" records around
2803 my $error = $cust_event->delete;
2805 #gah, even with transactions
2806 $dbh->commit if $oldAutoCommit; #well.
2813 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2814 warn " running cust_event ". $cust_event->eventnum. "\n"
2818 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2819 if ( my $error = $cust_event->do_event() ) {
2820 #XXX wtf is this? figure out a proper dealio with return value
2822 # gah, even with transactions.
2823 $dbh->commit if $oldAutoCommit; #well.
2830 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2835 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2837 Inserts database records for and returns an ordered listref of new events due
2838 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2839 events are due, an empty listref is returned. If there is an error, returns a
2840 scalar error message.
2842 To actually run the events, call each event's test_condition method, and if
2843 still true, call the event's do_event method.
2845 Options are passed as a hashref or as a list of name-value pairs. Available
2852 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.
2856 "Current time" for the events.
2860 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)
2864 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2868 Explicitly pass the objects to be tested (typically used with eventtable).
2874 sub due_cust_event {
2876 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2879 #my $DEBUG = $opt{'debug'}
2880 local($DEBUG) = $opt{'debug'}
2881 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2883 warn "$me due_cust_event called with options ".
2884 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2887 $opt{'time'} ||= time;
2889 local $SIG{HUP} = 'IGNORE';
2890 local $SIG{INT} = 'IGNORE';
2891 local $SIG{QUIT} = 'IGNORE';
2892 local $SIG{TERM} = 'IGNORE';
2893 local $SIG{TSTP} = 'IGNORE';
2894 local $SIG{PIPE} = 'IGNORE';
2896 my $oldAutoCommit = $FS::UID::AutoCommit;
2897 local $FS::UID::AutoCommit = 0;
2900 $self->select_for_update; #mutex
2903 # 1: find possible events (initial search)
2906 my @cust_event = ();
2908 my @eventtable = $opt{'eventtable'}
2909 ? ( $opt{'eventtable'} )
2910 : FS::part_event->eventtables_runorder;
2912 foreach my $eventtable ( @eventtable ) {
2915 if ( $opt{'objects'} ) {
2917 @objects = @{ $opt{'objects'} };
2921 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2922 @objects = ( $eventtable eq 'cust_main' )
2924 : ( $self->$eventtable() );
2928 my @e_cust_event = ();
2930 my $cross = "CROSS JOIN $eventtable";
2931 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2932 unless $eventtable eq 'cust_main';
2934 foreach my $object ( @objects ) {
2936 #this first search uses the condition_sql magic for optimization.
2937 #the more possible events we can eliminate in this step the better
2939 my $cross_where = '';
2940 my $pkey = $object->primary_key;
2941 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2943 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2945 FS::part_event_condition->where_conditions_sql( $eventtable,
2946 'time'=>$opt{'time'}
2948 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2950 $extra_sql = "AND $extra_sql" if $extra_sql;
2952 #here is the agent virtualization
2953 $extra_sql .= " AND ( part_event.agentnum IS NULL
2954 OR part_event.agentnum = ". $self->agentnum. ' )';
2956 $extra_sql .= " $order";
2958 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2959 if $opt{'debug'} > 2;
2960 my @part_event = qsearch( {
2961 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2962 'select' => 'part_event.*',
2963 'table' => 'part_event',
2964 'addl_from' => "$cross $join",
2965 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2966 'eventtable' => $eventtable,
2969 'extra_sql' => "AND $cross_where $extra_sql",
2973 my $pkey = $object->primary_key;
2974 warn " ". scalar(@part_event).
2975 " possible events found for $eventtable ". $object->$pkey(). "\n";
2978 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2982 warn " ". scalar(@e_cust_event).
2983 " subtotal possible cust events found for $eventtable\n"
2986 push @cust_event, @e_cust_event;
2990 warn " ". scalar(@cust_event).
2991 " total possible cust events found in initial search\n"
2995 # 2: test conditions
3000 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
3001 'stats_hashref' => \%unsat ),
3004 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
3007 warn " invalid conditions not eliminated with condition_sql:\n".
3008 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
3015 foreach my $cust_event ( @cust_event ) {
3017 my $error = $cust_event->insert();
3019 $dbh->rollback if $oldAutoCommit;
3025 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3031 warn " returning events: ". Dumper(@cust_event). "\n"
3038 =item retry_realtime
3040 Schedules realtime / batch credit card / electronic check / LEC billing
3041 events for for retry. Useful if card information has changed or manual
3042 retry is desired. The 'collect' method must be called to actually retry
3045 Implementation details: For either this customer, or for each of this
3046 customer's open invoices, changes the status of the first "done" (with
3047 statustext error) realtime processing event to "failed".
3051 sub retry_realtime {
3054 local $SIG{HUP} = 'IGNORE';
3055 local $SIG{INT} = 'IGNORE';
3056 local $SIG{QUIT} = 'IGNORE';
3057 local $SIG{TERM} = 'IGNORE';
3058 local $SIG{TSTP} = 'IGNORE';
3059 local $SIG{PIPE} = 'IGNORE';
3061 my $oldAutoCommit = $FS::UID::AutoCommit;
3062 local $FS::UID::AutoCommit = 0;
3065 #a little false laziness w/due_cust_event (not too bad, really)
3067 my $join = FS::part_event_condition->join_conditions_sql;
3068 my $order = FS::part_event_condition->order_conditions_sql;
3071 . join ( ' OR ' , map {
3072 "( part_event.eventtable = " . dbh->quote($_)
3073 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3074 } FS::part_event->eventtables)
3077 #here is the agent virtualization
3078 my $agent_virt = " ( part_event.agentnum IS NULL
3079 OR part_event.agentnum = ". $self->agentnum. ' )';
3081 #XXX this shouldn't be hardcoded, actions should declare it...
3082 my @realtime_events = qw(
3083 cust_bill_realtime_card
3084 cust_bill_realtime_check
3085 cust_bill_realtime_lec
3089 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3094 my @cust_event = qsearchs({
3095 'table' => 'cust_event',
3096 'select' => 'cust_event.*',
3097 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3098 'hashref' => { 'status' => 'done' },
3099 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3100 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3103 my %seen_invnum = ();
3104 foreach my $cust_event (@cust_event) {
3106 #max one for the customer, one for each open invoice
3107 my $cust_X = $cust_event->cust_X;
3108 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3112 or $cust_event->part_event->eventtable eq 'cust_bill'
3115 my $error = $cust_event->retry;
3117 $dbh->rollback if $oldAutoCommit;
3118 return "error scheduling event for retry: $error";
3123 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3128 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3130 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3131 via a Business::OnlinePayment realtime gateway. See
3132 L<http://420.am/business-onlinepayment> for supported gateways.
3134 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3136 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3138 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3139 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3140 if set, will override the value from the customer record.
3142 I<description> is a free-text field passed to the gateway. It defaults to
3143 "Internet services".
3145 If an I<invnum> is specified, this payment (if successful) is applied to the
3146 specified invoice. If you don't specify an I<invnum> you might want to
3147 call the B<apply_payments> method.
3149 I<quiet> can be set true to surpress email decline notices.
3151 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3152 resulting paynum, if any.
3154 I<payunique> is a unique identifier for this payment.
3156 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3161 my( $self, $method, $amount, %options ) = @_;
3163 warn "$me realtime_bop: $method $amount\n";
3164 warn " $_ => $options{$_}\n" foreach keys %options;
3167 $options{'description'} ||= 'Internet services';
3169 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3171 eval "use Business::OnlinePayment";
3174 my $payinfo = exists($options{'payinfo'})
3175 ? $options{'payinfo'}
3178 my %method2payby = (
3185 # check for banned credit card/ACH
3188 my $ban = qsearchs('banned_pay', {
3189 'payby' => $method2payby{$method},
3190 'payinfo' => md5_base64($payinfo),
3192 return "Banned credit card" if $ban;
3199 if ( $options{'invnum'} ) {
3200 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3201 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3203 map { $_->part_pkg->taxclass }
3205 map { $_->cust_pkg }
3206 $cust_bill->cust_bill_pkg;
3207 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3208 #different taxclasses
3209 $taxclass = $taxclasses[0];
3213 #look for an agent gateway override first
3215 if ( $method eq 'CC' ) {
3216 $cardtype = cardtype($payinfo);
3217 } elsif ( $method eq 'ECHECK' ) {
3220 $cardtype = $method;
3224 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3225 cardtype => $cardtype,
3226 taxclass => $taxclass, } )
3227 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3229 taxclass => $taxclass, } )
3230 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3231 cardtype => $cardtype,
3233 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3235 taxclass => '', } );
3237 my $payment_gateway = '';
3238 my( $processor, $login, $password, $action, @bop_options );
3239 if ( $override ) { #use a payment gateway override
3241 $payment_gateway = $override->payment_gateway;
3243 $processor = $payment_gateway->gateway_module;
3244 $login = $payment_gateway->gateway_username;
3245 $password = $payment_gateway->gateway_password;
3246 $action = $payment_gateway->gateway_action;
3247 @bop_options = $payment_gateway->options;
3249 } else { #use the standard settings from the config
3251 ( $processor, $login, $password, $action, @bop_options ) =
3252 $self->default_payment_gateway($method);
3260 my $address = exists($options{'address1'})
3261 ? $options{'address1'}
3263 my $address2 = exists($options{'address2'})
3264 ? $options{'address2'}
3266 $address .= ", ". $address2 if length($address2);
3268 my $o_payname = exists($options{'payname'})
3269 ? $options{'payname'}
3271 my($payname, $payfirst, $paylast);
3272 if ( $o_payname && $method ne 'ECHECK' ) {
3273 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3274 or return "Illegal payname $payname";
3275 ($payfirst, $paylast) = ($1, $2);
3277 $payfirst = $self->getfield('first');
3278 $paylast = $self->getfield('last');
3279 $payname = "$payfirst $paylast";
3282 my @invoicing_list = $self->invoicing_list_emailonly;
3283 if ( $conf->exists('emailinvoiceautoalways')
3284 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3285 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3286 push @invoicing_list, $self->all_emails;
3289 my $email = ($conf->exists('business-onlinepayment-email-override'))
3290 ? $conf->config('business-onlinepayment-email-override')
3291 : $invoicing_list[0];
3295 my $payip = exists($options{'payip'})
3298 $content{customer_ip} = $payip
3301 $content{invoice_number} = $options{'invnum'}
3302 if exists($options{'invnum'}) && length($options{'invnum'});
3304 $content{email_customer} =
3305 ( $conf->exists('business-onlinepayment-email_customer')
3306 || $conf->exists('business-onlinepayment-email-override') );
3309 if ( $method eq 'CC' ) {
3311 $content{card_number} = $payinfo;
3312 $paydate = exists($options{'paydate'})
3313 ? $options{'paydate'}
3315 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3316 $content{expiration} = "$2/$1";
3318 my $paycvv = exists($options{'paycvv'})
3319 ? $options{'paycvv'}
3321 $content{cvv2} = $paycvv
3324 my $paystart_month = exists($options{'paystart_month'})
3325 ? $options{'paystart_month'}
3326 : $self->paystart_month;
3328 my $paystart_year = exists($options{'paystart_year'})
3329 ? $options{'paystart_year'}
3330 : $self->paystart_year;
3332 $content{card_start} = "$paystart_month/$paystart_year"
3333 if $paystart_month && $paystart_year;
3335 my $payissue = exists($options{'payissue'})
3336 ? $options{'payissue'}
3338 $content{issue_number} = $payissue if $payissue;
3340 $content{recurring_billing} = 'YES'
3341 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3343 'payinfo' => $payinfo,
3345 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3347 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3351 } elsif ( $method eq 'ECHECK' ) {
3352 ( $content{account_number}, $content{routing_code} ) =
3353 split('@', $payinfo);
3354 $content{bank_name} = $o_payname;
3355 $content{bank_state} = exists($options{'paystate'})
3356 ? $options{'paystate'}
3357 : $self->getfield('paystate');
3358 $content{account_type} = exists($options{'paytype'})
3359 ? uc($options{'paytype'}) || 'CHECKING'
3360 : uc($self->getfield('paytype')) || 'CHECKING';
3361 $content{account_name} = $payname;
3362 $content{customer_org} = $self->company ? 'B' : 'I';
3363 $content{state_id} = exists($options{'stateid'})
3364 ? $options{'stateid'}
3365 : $self->getfield('stateid');
3366 $content{state_id_state} = exists($options{'stateid_state'})
3367 ? $options{'stateid_state'}
3368 : $self->getfield('stateid_state');
3369 $content{customer_ssn} = exists($options{'ss'})
3372 } elsif ( $method eq 'LEC' ) {
3373 $content{phone} = $payinfo;
3377 # run transaction(s)
3380 my $balance = exists( $options{'balance'} )
3381 ? $options{'balance'}
3384 $self->select_for_update; #mutex ... just until we get our pending record in
3386 #the checks here are intended to catch concurrent payments
3387 #double-form-submission prevention is taken care of in cust_pay_pending::check
3390 return "The customer's balance has changed; $method transaction aborted."
3391 if $self->balance < $balance;
3392 #&& $self->balance < $amount; #might as well anyway?
3394 #also check and make sure there aren't *other* pending payments for this cust
3396 my @pending = qsearch('cust_pay_pending', {
3397 'custnum' => $self->custnum,
3398 'status' => { op=>'!=', value=>'done' }
3400 return "A payment is already being processed for this customer (".
3401 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3402 "); $method transaction aborted."
3403 if scalar(@pending);
3405 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3407 my $cust_pay_pending = new FS::cust_pay_pending {
3408 'custnum' => $self->custnum,
3409 #'invnum' => $options{'invnum'},
3412 'payby' => $method2payby{$method},
3413 'payinfo' => $payinfo,
3414 'paydate' => $paydate,
3416 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3418 $cust_pay_pending->payunique( $options{payunique} )
3419 if defined($options{payunique}) && length($options{payunique});
3420 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3421 return $cpp_new_err if $cpp_new_err;
3423 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3425 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3426 $transaction->content(
3429 'password' => $password,
3430 'action' => $action1,
3431 'description' => $options{'description'},
3432 'amount' => $amount,
3433 #'invoice_number' => $options{'invnum'},
3434 'customer_id' => $self->custnum,
3435 'last_name' => $paylast,
3436 'first_name' => $payfirst,
3438 'address' => $address,
3439 'city' => ( exists($options{'city'})
3442 'state' => ( exists($options{'state'})
3445 'zip' => ( exists($options{'zip'})
3448 'country' => ( exists($options{'country'})
3449 ? $options{'country'}
3451 'referer' => 'http://cleanwhisker.420.am/',
3453 'phone' => $self->daytime || $self->night,
3457 $cust_pay_pending->status('pending');
3458 my $cpp_pending_err = $cust_pay_pending->replace;
3459 return $cpp_pending_err if $cpp_pending_err;
3462 my $BOP_TESTING = 0;
3463 my $BOP_TESTING_SUCCESS = 1;
3465 unless ( $BOP_TESTING ) {
3466 $transaction->submit();
3468 if ( $BOP_TESTING_SUCCESS ) {
3469 $transaction->is_success(1);
3470 $transaction->authorization('fake auth');
3472 $transaction->is_success(0);
3473 $transaction->error_message('fake failure');
3477 if ( $transaction->is_success() && $action2 ) {
3479 $cust_pay_pending->status('authorized');
3480 my $cpp_authorized_err = $cust_pay_pending->replace;
3481 return $cpp_authorized_err if $cpp_authorized_err;
3483 my $auth = $transaction->authorization;
3484 my $ordernum = $transaction->can('order_number')
3485 ? $transaction->order_number
3489 new Business::OnlinePayment( $processor, @bop_options );
3496 password => $password,
3497 order_number => $ordernum,
3499 authorization => $auth,
3500 description => $options{'description'},
3503 foreach my $field (qw( authorization_source_code returned_ACI
3504 transaction_identifier validation_code
3505 transaction_sequence_num local_transaction_date
3506 local_transaction_time AVS_result_code )) {
3507 $capture{$field} = $transaction->$field() if $transaction->can($field);
3510 $capture->content( %capture );
3514 unless ( $capture->is_success ) {
3515 my $e = "Authorization successful but capture failed, custnum #".
3516 $self->custnum. ': '. $capture->result_code.
3517 ": ". $capture->error_message;
3524 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3525 my $cpp_captured_err = $cust_pay_pending->replace;
3526 return $cpp_captured_err if $cpp_captured_err;
3529 # remove paycvv after initial transaction
3532 #false laziness w/misc/process/payment.cgi - check both to make sure working
3534 if ( defined $self->dbdef_table->column('paycvv')
3535 && length($self->paycvv)
3536 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3538 my $error = $self->remove_cvv;
3540 warn "WARNING: error removing cvv: $error\n";
3548 if ( $transaction->is_success() ) {
3551 if ( $payment_gateway ) { # agent override
3552 $paybatch = $payment_gateway->gatewaynum. '-';
3555 $paybatch .= "$processor:". $transaction->authorization;
3557 $paybatch .= ':'. $transaction->order_number
3558 if $transaction->can('order_number')
3559 && length($transaction->order_number);
3561 my $cust_pay = new FS::cust_pay ( {
3562 'custnum' => $self->custnum,
3563 'invnum' => $options{'invnum'},
3566 'payby' => $method2payby{$method},
3567 'payinfo' => $payinfo,
3568 'paybatch' => $paybatch,
3569 'paydate' => $paydate,
3571 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3572 $cust_pay->payunique( $options{payunique} )
3573 if defined($options{payunique}) && length($options{payunique});
3575 my $oldAutoCommit = $FS::UID::AutoCommit;
3576 local $FS::UID::AutoCommit = 0;
3579 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3581 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3584 $cust_pay->invnum(''); #try again with no specific invnum
3585 my $error2 = $cust_pay->insert( $options{'manual'} ?
3586 ( 'manual' => 1 ) : ()
3589 # gah. but at least we have a record of the state we had to abort in
3590 # from cust_pay_pending now.
3591 my $e = "WARNING: $method captured but payment not recorded - ".
3592 "error inserting payment ($processor): $error2".
3593 " (previously tried insert with invnum #$options{'invnum'}" .
3594 ": $error ) - pending payment saved as paypendingnum ".
3595 $cust_pay_pending->paypendingnum. "\n";
3601 if ( $options{'paynum_ref'} ) {
3602 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3605 $cust_pay_pending->status('done');
3606 $cust_pay_pending->statustext('captured');
3607 my $cpp_done_err = $cust_pay_pending->replace;
3609 if ( $cpp_done_err ) {
3611 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3612 my $e = "WARNING: $method captured but payment not recorded - ".
3613 "error updating status for paypendingnum ".
3614 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3620 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3621 return ''; #no error
3627 my $perror = "$processor error: ". $transaction->error_message;
3629 unless ( $transaction->error_message ) {
3632 if ( $transaction->can('response_page') ) {
3634 'page' => ( $transaction->can('response_page')
3635 ? $transaction->response_page
3638 'code' => ( $transaction->can('response_code')
3639 ? $transaction->response_code
3642 'headers' => ( $transaction->can('response_headers')
3643 ? $transaction->response_headers
3649 "No additional debugging information available for $processor";
3652 $perror .= "No error_message returned from $processor -- ".
3653 ( ref($t_response) ? Dumper($t_response) : $t_response );
3657 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3658 && $conf->exists('emaildecline')
3659 && grep { $_ ne 'POST' } $self->invoicing_list
3660 && ! grep { $transaction->error_message =~ /$_/ }
3661 $conf->config('emaildecline-exclude')
3663 my @templ = $conf->config('declinetemplate');
3664 my $template = new Text::Template (
3666 SOURCE => [ map "$_\n", @templ ],
3667 ) or return "($perror) can't create template: $Text::Template::ERROR";
3668 $template->compile()
3669 or return "($perror) can't compile template: $Text::Template::ERROR";
3671 my $templ_hash = { error => $transaction->error_message };
3673 my $error = send_email(
3674 'from' => $conf->config('invoice_from'),
3675 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3676 'subject' => 'Your payment could not be processed',
3677 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3680 $perror .= " (also received error sending decline notification: $error)"
3685 $cust_pay_pending->status('done');
3686 $cust_pay_pending->statustext("declined: $perror");
3687 my $cpp_done_err = $cust_pay_pending->replace;
3688 if ( $cpp_done_err ) {
3689 my $e = "WARNING: $method declined but pending payment not resolved - ".
3690 "error updating status for paypendingnum ".
3691 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3693 $perror = "$e ($perror)";
3706 my( $self, $method, $amount, %options ) = @_;
3708 if ( $options{'fake_failure'} ) {
3709 return "Error: No error; test failure requested with fake_failure";
3712 my %method2payby = (
3719 #if ( $payment_gateway ) { # agent override
3720 # $paybatch = $payment_gateway->gatewaynum. '-';
3723 #$paybatch .= "$processor:". $transaction->authorization;
3725 #$paybatch .= ':'. $transaction->order_number
3726 # if $transaction->can('order_number')
3727 # && length($transaction->order_number);
3729 my $paybatch = 'FakeProcessor:54:32';
3731 my $cust_pay = new FS::cust_pay ( {
3732 'custnum' => $self->custnum,
3733 'invnum' => $options{'invnum'},
3736 'payby' => $method2payby{$method},
3737 #'payinfo' => $payinfo,
3738 'payinfo' => '4111111111111111',
3739 'paybatch' => $paybatch,
3740 #'paydate' => $paydate,
3741 'paydate' => '2012-05-01',
3743 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3745 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3748 $cust_pay->invnum(''); #try again with no specific invnum
3749 my $error2 = $cust_pay->insert( $options{'manual'} ?
3750 ( 'manual' => 1 ) : ()
3753 # gah, even with transactions.
3754 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3755 "error inserting (fake!) payment: $error2".
3756 " (previously tried insert with invnum #$options{'invnum'}" .
3763 if ( $options{'paynum_ref'} ) {
3764 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3767 return ''; #no error
3771 =item default_payment_gateway
3775 sub default_payment_gateway {
3776 my( $self, $method ) = @_;
3778 die "Real-time processing not enabled\n"
3779 unless $conf->exists('business-onlinepayment');
3782 my $bop_config = 'business-onlinepayment';
3783 $bop_config .= '-ach'
3784 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3785 my ( $processor, $login, $password, $action, @bop_options ) =
3786 $conf->config($bop_config);
3787 $action ||= 'normal authorization';
3788 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3789 die "No real-time processor is enabled - ".
3790 "did you set the business-onlinepayment configuration value?\n"
3793 ( $processor, $login, $password, $action, @bop_options )
3798 Removes the I<paycvv> field from the database directly.
3800 If there is an error, returns the error, otherwise returns false.
3806 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3807 or return dbh->errstr;
3808 $sth->execute($self->custnum)
3809 or return $sth->errstr;
3814 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3816 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3817 via a Business::OnlinePayment realtime gateway. See
3818 L<http://420.am/business-onlinepayment> for supported gateways.
3820 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3822 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3824 Most gateways require a reference to an original payment transaction to refund,
3825 so you probably need to specify a I<paynum>.
3827 I<amount> defaults to the original amount of the payment if not specified.
3829 I<reason> specifies a reason for the refund.
3831 I<paydate> specifies the expiration date for a credit card overriding the
3832 value from the customer record or the payment record. Specified as yyyy-mm-dd
3834 Implementation note: If I<amount> is unspecified or equal to the amount of the
3835 orignal payment, first an attempt is made to "void" the transaction via
3836 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3837 the normal attempt is made to "refund" ("credit") the transaction via the
3838 gateway is attempted.
3840 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3841 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3842 #if set, will override the value from the customer record.
3844 #If an I<invnum> is specified, this payment (if successful) is applied to the
3845 #specified invoice. If you don't specify an I<invnum> you might want to
3846 #call the B<apply_payments> method.
3850 #some false laziness w/realtime_bop, not enough to make it worth merging
3851 #but some useful small subs should be pulled out
3852 sub realtime_refund_bop {
3853 my( $self, $method, %options ) = @_;
3855 warn "$me realtime_refund_bop: $method refund\n";
3856 warn " $_ => $options{$_}\n" foreach keys %options;
3859 eval "use Business::OnlinePayment";
3863 # look up the original payment and optionally a gateway for that payment
3867 my $amount = $options{'amount'};
3869 my( $processor, $login, $password, @bop_options ) ;
3870 my( $auth, $order_number ) = ( '', '', '' );
3872 if ( $options{'paynum'} ) {
3874 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3875 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3876 or return "Unknown paynum $options{'paynum'}";
3877 $amount ||= $cust_pay->paid;
3879 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3880 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3881 $cust_pay->paybatch;
3882 my $gatewaynum = '';
3883 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3885 if ( $gatewaynum ) { #gateway for the payment to be refunded
3887 my $payment_gateway =
3888 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3889 die "payment gateway $gatewaynum not found"
3890 unless $payment_gateway;
3892 $processor = $payment_gateway->gateway_module;
3893 $login = $payment_gateway->gateway_username;
3894 $password = $payment_gateway->gateway_password;
3895 @bop_options = $payment_gateway->options;
3897 } else { #try the default gateway
3899 my( $conf_processor, $unused_action );
3900 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3901 $self->default_payment_gateway($method);
3903 return "processor of payment $options{'paynum'} $processor does not".
3904 " match default processor $conf_processor"
3905 unless $processor eq $conf_processor;
3910 } else { # didn't specify a paynum, so look for agent gateway overrides
3911 # like a normal transaction
3914 if ( $method eq 'CC' ) {
3915 $cardtype = cardtype($self->payinfo);
3916 } elsif ( $method eq 'ECHECK' ) {
3919 $cardtype = $method;
3922 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3923 cardtype => $cardtype,
3925 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3927 taxclass => '', } );
3929 if ( $override ) { #use a payment gateway override
3931 my $payment_gateway = $override->payment_gateway;
3933 $processor = $payment_gateway->gateway_module;
3934 $login = $payment_gateway->gateway_username;
3935 $password = $payment_gateway->gateway_password;
3936 #$action = $payment_gateway->gateway_action;
3937 @bop_options = $payment_gateway->options;
3939 } else { #use the standard settings from the config
3942 ( $processor, $login, $password, $unused_action, @bop_options ) =
3943 $self->default_payment_gateway($method);
3948 return "neither amount nor paynum specified" unless $amount;
3953 'password' => $password,
3954 'order_number' => $order_number,
3955 'amount' => $amount,
3956 'referer' => 'http://cleanwhisker.420.am/',
3958 $content{authorization} = $auth
3959 if length($auth); #echeck/ACH transactions have an order # but no auth
3960 #(at least with authorize.net)
3962 my $disable_void_after;
3963 if ($conf->exists('disable_void_after')
3964 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3965 $disable_void_after = $1;
3968 #first try void if applicable
3969 if ( $cust_pay && $cust_pay->paid == $amount
3971 ( not defined($disable_void_after) )
3972 || ( time < ($cust_pay->_date + $disable_void_after ) )
3975 warn " attempting void\n" if $DEBUG > 1;
3976 my $void = new Business::OnlinePayment( $processor, @bop_options );
3977 $void->content( 'action' => 'void', %content );
3979 if ( $void->is_success ) {
3980 my $error = $cust_pay->void($options{'reason'});
3982 # gah, even with transactions.
3983 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3984 "error voiding payment: $error";
3988 warn " void successful\n" if $DEBUG > 1;
3993 warn " void unsuccessful, trying refund\n"
3997 my $address = $self->address1;
3998 $address .= ", ". $self->address2 if $self->address2;
4000 my($payname, $payfirst, $paylast);
4001 if ( $self->payname && $method ne 'ECHECK' ) {
4002 $payname = $self->payname;
4003 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4004 or return "Illegal payname $payname";
4005 ($payfirst, $paylast) = ($1, $2);
4007 $payfirst = $self->getfield('first');
4008 $paylast = $self->getfield('last');
4009 $payname = "$payfirst $paylast";
4012 my @invoicing_list = $self->invoicing_list_emailonly;
4013 if ( $conf->exists('emailinvoiceautoalways')
4014 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4015 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4016 push @invoicing_list, $self->all_emails;
4019 my $email = ($conf->exists('business-onlinepayment-email-override'))
4020 ? $conf->config('business-onlinepayment-email-override')
4021 : $invoicing_list[0];
4023 my $payip = exists($options{'payip'})
4026 $content{customer_ip} = $payip
4030 if ( $method eq 'CC' ) {
4033 $content{card_number} = $payinfo = $cust_pay->payinfo;
4034 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
4035 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
4036 ($content{expiration} = "$2/$1"); # where available
4038 $content{card_number} = $payinfo = $self->payinfo;
4039 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
4040 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4041 $content{expiration} = "$2/$1";
4044 } elsif ( $method eq 'ECHECK' ) {
4047 $payinfo = $cust_pay->payinfo;
4049 $payinfo = $self->payinfo;
4051 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
4052 $content{bank_name} = $self->payname;
4053 $content{account_type} = 'CHECKING';
4054 $content{account_name} = $payname;
4055 $content{customer_org} = $self->company ? 'B' : 'I';
4056 $content{customer_ssn} = $self->ss;
4057 } elsif ( $method eq 'LEC' ) {
4058 $content{phone} = $payinfo = $self->payinfo;
4062 my $refund = new Business::OnlinePayment( $processor, @bop_options );
4063 my %sub_content = $refund->content(
4064 'action' => 'credit',
4065 'customer_id' => $self->custnum,
4066 'last_name' => $paylast,
4067 'first_name' => $payfirst,
4069 'address' => $address,
4070 'city' => $self->city,
4071 'state' => $self->state,
4072 'zip' => $self->zip,
4073 'country' => $self->country,
4075 'phone' => $self->daytime || $self->night,
4078 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
4082 return "$processor error: ". $refund->error_message
4083 unless $refund->is_success();
4085 my %method2payby = (
4091 my $paybatch = "$processor:". $refund->authorization;
4092 $paybatch .= ':'. $refund->order_number
4093 if $refund->can('order_number') && $refund->order_number;
4095 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4096 my @cust_bill_pay = $cust_pay->cust_bill_pay;
4097 last unless @cust_bill_pay;
4098 my $cust_bill_pay = pop @cust_bill_pay;
4099 my $error = $cust_bill_pay->delete;
4103 my $cust_refund = new FS::cust_refund ( {
4104 'custnum' => $self->custnum,
4105 'paynum' => $options{'paynum'},
4106 'refund' => $amount,
4108 'payby' => $method2payby{$method},
4109 'payinfo' => $payinfo,
4110 'paybatch' => $paybatch,
4111 'reason' => $options{'reason'} || 'card or ACH refund',
4113 my $error = $cust_refund->insert;
4115 $cust_refund->paynum(''); #try again with no specific paynum
4116 my $error2 = $cust_refund->insert;
4118 # gah, even with transactions.
4119 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4120 "error inserting refund ($processor): $error2".
4121 " (previously tried insert with paynum #$options{'paynum'}" .
4132 =item batch_card OPTION => VALUE...
4134 Adds a payment for this invoice to the pending credit card batch (see
4135 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4136 runs the payment using a realtime gateway.
4141 my ($self, %options) = @_;
4144 if (exists($options{amount})) {
4145 $amount = $options{amount};
4147 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4149 return '' unless $amount > 0;
4151 my $invnum = delete $options{invnum};
4152 my $payby = $options{invnum} || $self->payby; #dubious
4154 if ($options{'realtime'}) {
4155 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4161 my $oldAutoCommit = $FS::UID::AutoCommit;
4162 local $FS::UID::AutoCommit = 0;
4165 #this needs to handle mysql as well as Pg, like svc_acct.pm
4166 #(make it into a common function if folks need to do batching with mysql)
4167 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4168 or return "Cannot lock pay_batch: " . $dbh->errstr;
4172 'payby' => FS::payby->payby2payment($payby),
4175 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4177 unless ( $pay_batch ) {
4178 $pay_batch = new FS::pay_batch \%pay_batch;
4179 my $error = $pay_batch->insert;
4181 $dbh->rollback if $oldAutoCommit;
4182 die "error creating new batch: $error\n";
4186 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4187 'batchnum' => $pay_batch->batchnum,
4188 'custnum' => $self->custnum,
4191 foreach (qw( address1 address2 city state zip country payby payinfo paydate
4193 $options{$_} = '' unless exists($options{$_});
4196 my $cust_pay_batch = new FS::cust_pay_batch ( {
4197 'batchnum' => $pay_batch->batchnum,
4198 'invnum' => $invnum || 0, # is there a better value?
4199 # this field should be
4201 # cust_bill_pay_batch now
4202 'custnum' => $self->custnum,
4203 'last' => $self->getfield('last'),
4204 'first' => $self->getfield('first'),
4205 'address1' => $options{address1} || $self->address1,
4206 'address2' => $options{address2} || $self->address2,
4207 'city' => $options{city} || $self->city,
4208 'state' => $options{state} || $self->state,
4209 'zip' => $options{zip} || $self->zip,
4210 'country' => $options{country} || $self->country,
4211 'payby' => $options{payby} || $self->payby,
4212 'payinfo' => $options{payinfo} || $self->payinfo,
4213 'exp' => $options{paydate} || $self->paydate,
4214 'payname' => $options{payname} || $self->payname,
4215 'amount' => $amount, # consolidating
4218 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4219 if $old_cust_pay_batch;
4222 if ($old_cust_pay_batch) {
4223 $error = $cust_pay_batch->replace($old_cust_pay_batch)
4225 $error = $cust_pay_batch->insert;
4229 $dbh->rollback if $oldAutoCommit;
4233 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
4234 foreach my $cust_bill ($self->open_cust_bill) {
4235 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4236 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4237 'invnum' => $cust_bill->invnum,
4238 'paybatchnum' => $cust_pay_batch->paybatchnum,
4239 'amount' => $cust_bill->owed,
4242 if ($unapplied >= $cust_bill_pay_batch->amount){
4243 $unapplied -= $cust_bill_pay_batch->amount;
4246 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4247 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4249 $error = $cust_bill_pay_batch->insert;
4251 $dbh->rollback if $oldAutoCommit;
4256 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4262 Returns the total owed for this customer on all invoices
4263 (see L<FS::cust_bill/owed>).
4269 $self->total_owed_date(2145859200); #12/31/2037
4272 =item total_owed_date TIME
4274 Returns the total owed for this customer on all invoices with date earlier than
4275 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4276 see L<Time::Local> and L<Date::Parse> for conversion functions.
4280 sub total_owed_date {
4284 foreach my $cust_bill (
4285 grep { $_->_date <= $time }
4286 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4288 $total_bill += $cust_bill->owed;
4290 sprintf( "%.2f", $total_bill );
4293 =item apply_payments_and_credits
4295 Applies unapplied payments and credits.
4297 In most cases, this new method should be used in place of sequential
4298 apply_payments and apply_credits methods.
4300 If there is an error, returns the error, otherwise returns false.
4304 sub apply_payments_and_credits {
4307 local $SIG{HUP} = 'IGNORE';
4308 local $SIG{INT} = 'IGNORE';
4309 local $SIG{QUIT} = 'IGNORE';
4310 local $SIG{TERM} = 'IGNORE';
4311 local $SIG{TSTP} = 'IGNORE';
4312 local $SIG{PIPE} = 'IGNORE';
4314 my $oldAutoCommit = $FS::UID::AutoCommit;
4315 local $FS::UID::AutoCommit = 0;
4318 $self->select_for_update; #mutex
4320 foreach my $cust_bill ( $self->open_cust_bill ) {
4321 my $error = $cust_bill->apply_payments_and_credits;
4323 $dbh->rollback if $oldAutoCommit;
4324 return "Error applying: $error";
4328 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4333 =item apply_credits OPTION => VALUE ...
4335 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4336 to outstanding invoice balances in chronological order (or reverse
4337 chronological order if the I<order> option is set to B<newest>) and returns the
4338 value of any remaining unapplied credits available for refund (see
4339 L<FS::cust_refund>).
4341 Dies if there is an error.
4349 local $SIG{HUP} = 'IGNORE';
4350 local $SIG{INT} = 'IGNORE';
4351 local $SIG{QUIT} = 'IGNORE';
4352 local $SIG{TERM} = 'IGNORE';
4353 local $SIG{TSTP} = 'IGNORE';
4354 local $SIG{PIPE} = 'IGNORE';
4356 my $oldAutoCommit = $FS::UID::AutoCommit;
4357 local $FS::UID::AutoCommit = 0;
4360 $self->select_for_update; #mutex
4362 unless ( $self->total_credited ) {
4363 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4367 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4368 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4370 my @invoices = $self->open_cust_bill;
4371 @invoices = sort { $b->_date <=> $a->_date } @invoices
4372 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4375 foreach my $cust_bill ( @invoices ) {
4378 if ( !defined($credit) || $credit->credited == 0) {
4379 $credit = pop @credits or last;
4382 if ($cust_bill->owed >= $credit->credited) {
4383 $amount=$credit->credited;
4385 $amount=$cust_bill->owed;
4388 my $cust_credit_bill = new FS::cust_credit_bill ( {
4389 'crednum' => $credit->crednum,
4390 'invnum' => $cust_bill->invnum,
4391 'amount' => $amount,
4393 my $error = $cust_credit_bill->insert;
4395 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4399 redo if ($cust_bill->owed > 0);
4403 my $total_credited = $self->total_credited;
4405 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4407 return $total_credited;
4410 =item apply_payments
4412 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4413 to outstanding invoice balances in chronological order.
4415 #and returns the value of any remaining unapplied payments.
4417 Dies if there is an error.
4421 sub apply_payments {
4424 local $SIG{HUP} = 'IGNORE';
4425 local $SIG{INT} = 'IGNORE';
4426 local $SIG{QUIT} = 'IGNORE';
4427 local $SIG{TERM} = 'IGNORE';
4428 local $SIG{TSTP} = 'IGNORE';
4429 local $SIG{PIPE} = 'IGNORE';
4431 my $oldAutoCommit = $FS::UID::AutoCommit;
4432 local $FS::UID::AutoCommit = 0;
4435 $self->select_for_update; #mutex
4439 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4440 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4442 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4443 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4447 foreach my $cust_bill ( @invoices ) {
4450 if ( !defined($payment) || $payment->unapplied == 0 ) {
4451 $payment = pop @payments or last;
4454 if ( $cust_bill->owed >= $payment->unapplied ) {
4455 $amount = $payment->unapplied;
4457 $amount = $cust_bill->owed;
4460 my $cust_bill_pay = new FS::cust_bill_pay ( {
4461 'paynum' => $payment->paynum,
4462 'invnum' => $cust_bill->invnum,
4463 'amount' => $amount,
4465 my $error = $cust_bill_pay->insert;
4467 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4471 redo if ( $cust_bill->owed > 0);
4475 my $total_unapplied_payments = $self->total_unapplied_payments;
4477 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4479 return $total_unapplied_payments;
4482 =item total_credited
4484 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4485 customer. See L<FS::cust_credit/credited>.
4489 sub total_credited {
4491 my $total_credit = 0;
4492 foreach my $cust_credit ( qsearch('cust_credit', {
4493 'custnum' => $self->custnum,
4495 $total_credit += $cust_credit->credited;
4497 sprintf( "%.2f", $total_credit );
4500 =item total_unapplied_payments
4502 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4503 See L<FS::cust_pay/unapplied>.
4507 sub total_unapplied_payments {
4509 my $total_unapplied = 0;
4510 foreach my $cust_pay ( qsearch('cust_pay', {
4511 'custnum' => $self->custnum,
4513 $total_unapplied += $cust_pay->unapplied;
4515 sprintf( "%.2f", $total_unapplied );
4518 =item total_unapplied_refunds
4520 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4521 customer. See L<FS::cust_refund/unapplied>.
4525 sub total_unapplied_refunds {
4527 my $total_unapplied = 0;
4528 foreach my $cust_refund ( qsearch('cust_refund', {
4529 'custnum' => $self->custnum,
4531 $total_unapplied += $cust_refund->unapplied;
4533 sprintf( "%.2f", $total_unapplied );
4538 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4539 total_credited minus total_unapplied_payments).
4547 + $self->total_unapplied_refunds
4548 - $self->total_credited
4549 - $self->total_unapplied_payments
4553 =item balance_date TIME
4555 Returns the balance for this customer, only considering invoices with date
4556 earlier than TIME (total_owed_date minus total_credited minus
4557 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4558 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4567 $self->total_owed_date($time)
4568 + $self->total_unapplied_refunds
4569 - $self->total_credited
4570 - $self->total_unapplied_payments
4574 =item in_transit_payments
4576 Returns the total of requests for payments for this customer pending in
4577 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4581 sub in_transit_payments {
4583 my $in_transit_payments = 0;
4584 foreach my $pay_batch ( qsearch('pay_batch', {
4587 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4588 'batchnum' => $pay_batch->batchnum,
4589 'custnum' => $self->custnum,
4591 $in_transit_payments += $cust_pay_batch->amount;
4594 sprintf( "%.2f", $in_transit_payments );
4597 =item paydate_monthyear
4599 Returns a two-element list consisting of the month and year of this customer's
4600 paydate (credit card expiration date for CARD customers)
4604 sub paydate_monthyear {
4606 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4608 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4615 =item invoicing_list [ ARRAYREF ]
4617 If an arguement is given, sets these email addresses as invoice recipients
4618 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4619 (except as warnings), so use check_invoicing_list first.
4621 Returns a list of email addresses (with svcnum entries expanded).
4623 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4624 check it without disturbing anything by passing nothing.
4626 This interface may change in the future.
4630 sub invoicing_list {
4631 my( $self, $arrayref ) = @_;
4634 my @cust_main_invoice;
4635 if ( $self->custnum ) {
4636 @cust_main_invoice =
4637 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4639 @cust_main_invoice = ();
4641 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4642 #warn $cust_main_invoice->destnum;
4643 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4644 #warn $cust_main_invoice->destnum;
4645 my $error = $cust_main_invoice->delete;
4646 warn $error if $error;
4649 if ( $self->custnum ) {
4650 @cust_main_invoice =
4651 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4653 @cust_main_invoice = ();
4655 my %seen = map { $_->address => 1 } @cust_main_invoice;
4656 foreach my $address ( @{$arrayref} ) {
4657 next if exists $seen{$address} && $seen{$address};
4658 $seen{$address} = 1;
4659 my $cust_main_invoice = new FS::cust_main_invoice ( {
4660 'custnum' => $self->custnum,
4663 my $error = $cust_main_invoice->insert;
4664 warn $error if $error;
4668 if ( $self->custnum ) {
4670 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4677 =item check_invoicing_list ARRAYREF
4679 Checks these arguements as valid input for the invoicing_list method. If there
4680 is an error, returns the error, otherwise returns false.
4684 sub check_invoicing_list {
4685 my( $self, $arrayref ) = @_;
4687 foreach my $address ( @$arrayref ) {
4689 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4690 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4693 my $cust_main_invoice = new FS::cust_main_invoice ( {
4694 'custnum' => $self->custnum,
4697 my $error = $self->custnum
4698 ? $cust_main_invoice->check
4699 : $cust_main_invoice->checkdest
4701 return $error if $error;
4705 return "Email address required"
4706 if $conf->exists('cust_main-require_invoicing_list_email')
4707 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4712 =item set_default_invoicing_list
4714 Sets the invoicing list to all accounts associated with this customer,
4715 overwriting any previous invoicing list.
4719 sub set_default_invoicing_list {
4721 $self->invoicing_list($self->all_emails);
4726 Returns the email addresses of all accounts provisioned for this customer.
4733 foreach my $cust_pkg ( $self->all_pkgs ) {
4734 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4736 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4737 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4739 $list{$_}=1 foreach map { $_->email } @svc_acct;
4744 =item invoicing_list_addpost
4746 Adds postal invoicing to this customer. If this customer is already configured
4747 to receive postal invoices, does nothing.
4751 sub invoicing_list_addpost {
4753 return if grep { $_ eq 'POST' } $self->invoicing_list;
4754 my @invoicing_list = $self->invoicing_list;
4755 push @invoicing_list, 'POST';
4756 $self->invoicing_list(\@invoicing_list);
4759 =item invoicing_list_emailonly
4761 Returns the list of email invoice recipients (invoicing_list without non-email
4762 destinations such as POST and FAX).
4766 sub invoicing_list_emailonly {
4768 warn "$me invoicing_list_emailonly called"
4770 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4773 =item invoicing_list_emailonly_scalar
4775 Returns the list of email invoice recipients (invoicing_list without non-email
4776 destinations such as POST and FAX) as a comma-separated scalar.
4780 sub invoicing_list_emailonly_scalar {
4782 warn "$me invoicing_list_emailonly_scalar called"
4784 join(', ', $self->invoicing_list_emailonly);
4787 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4789 Returns an array of customers referred by this customer (referral_custnum set
4790 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4791 customers referred by customers referred by this customer and so on, inclusive.
4792 The default behavior is DEPTH 1 (no recursion).
4796 sub referral_cust_main {
4798 my $depth = @_ ? shift : 1;
4799 my $exclude = @_ ? shift : {};
4802 map { $exclude->{$_->custnum}++; $_; }
4803 grep { ! $exclude->{ $_->custnum } }
4804 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4808 map { $_->referral_cust_main($depth-1, $exclude) }
4815 =item referral_cust_main_ncancelled
4817 Same as referral_cust_main, except only returns customers with uncancelled
4822 sub referral_cust_main_ncancelled {
4824 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4827 =item referral_cust_pkg [ DEPTH ]
4829 Like referral_cust_main, except returns a flat list of all unsuspended (and
4830 uncancelled) packages for each customer. The number of items in this list may
4831 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4835 sub referral_cust_pkg {
4837 my $depth = @_ ? shift : 1;
4839 map { $_->unsuspended_pkgs }
4840 grep { $_->unsuspended_pkgs }
4841 $self->referral_cust_main($depth);
4844 =item referring_cust_main
4846 Returns the single cust_main record for the customer who referred this customer
4847 (referral_custnum), or false.
4851 sub referring_cust_main {
4853 return '' unless $self->referral_custnum;
4854 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4857 =item credit AMOUNT, REASON
4859 Applies a credit to this customer. If there is an error, returns the error,
4860 otherwise returns false.
4865 my( $self, $amount, $reason, %options ) = @_;
4866 my $cust_credit = new FS::cust_credit {
4867 'custnum' => $self->custnum,
4868 'amount' => $amount,
4869 'reason' => $reason,
4871 $cust_credit->insert(%options);
4874 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4876 Creates a one-time charge for this customer. If there is an error, returns
4877 the error, otherwise returns false.
4883 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4884 my ( $taxproduct, $override );
4885 if ( ref( $_[0] ) ) {
4886 $amount = $_[0]->{amount};
4887 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4888 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4889 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4890 : '$'. sprintf("%.2f",$amount);
4891 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4892 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4893 $additional = $_[0]->{additional};
4894 $taxproduct = $_[0]->{taxproductnum};
4895 $override = { '' => $_[0]->{tax_override} };
4899 $pkg = @_ ? shift : 'One-time charge';
4900 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4901 $taxclass = @_ ? shift : '';
4905 local $SIG{HUP} = 'IGNORE';
4906 local $SIG{INT} = 'IGNORE';
4907 local $SIG{QUIT} = 'IGNORE';
4908 local $SIG{TERM} = 'IGNORE';
4909 local $SIG{TSTP} = 'IGNORE';
4910 local $SIG{PIPE} = 'IGNORE';
4912 my $oldAutoCommit = $FS::UID::AutoCommit;
4913 local $FS::UID::AutoCommit = 0;
4916 my $part_pkg = new FS::part_pkg ( {
4918 'comment' => $comment,
4922 'classnum' => $classnum ? $classnum : '',
4923 'taxclass' => $taxclass,
4924 'taxproductnum' => $taxproduct,
4927 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4928 ( 0 .. @$additional - 1 )
4930 'additional_count' => scalar(@$additional),
4931 'setup_fee' => $amount,
4934 my $error = $part_pkg->insert( options => \%options,
4935 tax_overrides => $override,
4938 $dbh->rollback if $oldAutoCommit;
4942 my $pkgpart = $part_pkg->pkgpart;
4943 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4944 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4945 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4946 $error = $type_pkgs->insert;
4948 $dbh->rollback if $oldAutoCommit;
4953 my $cust_pkg = new FS::cust_pkg ( {
4954 'custnum' => $self->custnum,
4955 'pkgpart' => $pkgpart,
4956 'quantity' => $quantity,
4959 $error = $cust_pkg->insert;
4961 $dbh->rollback if $oldAutoCommit;
4965 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4970 #=item charge_postal_fee
4972 #Applies a one time charge this customer. If there is an error,
4973 #returns the error, returns the cust_pkg charge object or false
4974 #if there was no charge.
4978 # This should be a customer event. For that to work requires that bill
4979 # also be a customer event.
4981 sub charge_postal_fee {
4984 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4985 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4987 my $cust_pkg = new FS::cust_pkg ( {
4988 'custnum' => $self->custnum,
4989 'pkgpart' => $pkgpart,
4993 my $error = $cust_pkg->insert;
4994 $error ? $error : $cust_pkg;
4999 Returns all the invoices (see L<FS::cust_bill>) for this customer.
5005 sort { $a->_date <=> $b->_date }
5006 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
5009 =item open_cust_bill
5011 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
5016 sub open_cust_bill {
5018 grep { $_->owed > 0 } $self->cust_bill;
5023 Returns all the credits (see L<FS::cust_credit>) for this customer.
5029 sort { $a->_date <=> $b->_date }
5030 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
5035 Returns all the payments (see L<FS::cust_pay>) for this customer.
5041 sort { $a->_date <=> $b->_date }
5042 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
5047 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
5053 sort { $a->_date <=> $b->_date }
5054 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
5057 =item cust_pay_batch
5059 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
5063 sub cust_pay_batch {
5065 sort { $a->_date <=> $b->_date }
5066 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
5071 Returns all the refunds (see L<FS::cust_refund>) for this customer.
5077 sort { $a->_date <=> $b->_date }
5078 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
5083 Returns a name string for this customer, either "Company (Last, First)" or
5090 my $name = $self->contact;
5091 $name = $self->company. " ($name)" if $self->company;
5097 Returns a name string for this (service/shipping) contact, either
5098 "Company (Last, First)" or "Last, First".
5104 if ( $self->get('ship_last') ) {
5105 my $name = $self->ship_contact;
5106 $name = $self->ship_company. " ($name)" if $self->ship_company;
5115 Returns this customer's full (billing) contact name only, "Last, First"
5121 $self->get('last'). ', '. $self->first;
5126 Returns this customer's full (shipping) contact name only, "Last, First"
5132 $self->get('ship_last')
5133 ? $self->get('ship_last'). ', '. $self->ship_first
5139 Returns this customer's full country name
5145 code2country($self->country);
5148 =item geocode DATA_VENDOR
5150 Returns a value for the customer location as encoded by DATA_VENDOR.
5151 Currently this only makes sense for "CCH" as DATA_VENDOR.
5156 my ($self, $data_vendor) = (shift, shift); #always cch for now
5158 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5162 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5163 if $self->country eq 'US';
5165 #CCH specific location stuff
5166 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5169 my $cust_tax_location =
5171 'table' => 'cust_tax_location',
5172 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5173 'extra_sql' => $extra_sql,
5176 $geocode = $cust_tax_location->geocode
5177 if $cust_tax_location;
5186 Returns a status string for this customer, currently:
5190 =item prospect - No packages have ever been ordered
5192 =item active - One or more recurring packages is active
5194 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5196 =item suspended - All non-cancelled recurring packages are suspended
5198 =item cancelled - All recurring packages are cancelled
5204 sub status { shift->cust_status(@_); }
5208 for my $status (qw( prospect active inactive suspended cancelled )) {
5209 my $method = $status.'_sql';
5210 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5211 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5212 $sth->execute( ($self->custnum) x $numnum )
5213 or die "Error executing 'SELECT $sql': ". $sth->errstr;
5214 return $status if $sth->fetchrow_arrayref->[0];
5218 =item ucfirst_cust_status
5220 =item ucfirst_status
5222 Returns the status with the first character capitalized.
5226 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5228 sub ucfirst_cust_status {
5230 ucfirst($self->cust_status);
5235 Returns a hex triplet color string for this customer's status.
5239 use vars qw(%statuscolor);
5240 tie %statuscolor, 'Tie::IxHash',
5241 'prospect' => '7e0079', #'000000', #black? naw, purple
5242 'active' => '00CC00', #green
5243 'inactive' => '0000CC', #blue
5244 'suspended' => 'FF9900', #yellow
5245 'cancelled' => 'FF0000', #red
5248 sub statuscolor { shift->cust_statuscolor(@_); }
5250 sub cust_statuscolor {
5252 $statuscolor{$self->cust_status};
5257 Returns an array of hashes representing the customer's RT tickets.
5264 my $num = $conf->config('cust_main-max_tickets') || 10;
5267 unless ( $conf->config('ticket_system-custom_priority_field') ) {
5269 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5273 foreach my $priority (
5274 $conf->config('ticket_system-custom_priority_field-values'), ''
5276 last if scalar(@tickets) >= $num;
5278 @{ FS::TicketSystem->customer_tickets( $self->custnum,
5279 $num - scalar(@tickets),
5288 # Return services representing svc_accts in customer support packages
5289 sub support_services {
5291 my %packages = map { $_ => 1 } $conf->config('support_packages');
5293 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5294 grep { $_->part_svc->svcdb eq 'svc_acct' }
5295 map { $_->cust_svc }
5296 grep { exists $packages{ $_->pkgpart } }
5297 $self->ncancelled_pkgs;
5303 =head1 CLASS METHODS
5309 Class method that returns the list of possible status strings for customers
5310 (see L<the status method|/status>). For example:
5312 @statuses = FS::cust_main->statuses();
5317 #my $self = shift; #could be class...
5323 Returns an SQL expression identifying prospective cust_main records (customers
5324 with no packages ever ordered)
5328 use vars qw($select_count_pkgs);
5329 $select_count_pkgs =
5330 "SELECT COUNT(*) FROM cust_pkg
5331 WHERE cust_pkg.custnum = cust_main.custnum";
5333 sub select_count_pkgs_sql {
5337 sub prospect_sql { "
5338 0 = ( $select_count_pkgs )
5343 Returns an SQL expression identifying active cust_main records (customers with
5344 active recurring packages).
5349 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5355 Returns an SQL expression identifying inactive cust_main records (customers with
5356 no active recurring packages, but otherwise unsuspended/uncancelled).
5360 sub inactive_sql { "
5361 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5363 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5369 Returns an SQL expression identifying suspended cust_main records.
5374 sub suspended_sql { susp_sql(@_); }
5376 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5378 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5384 Returns an SQL expression identifying cancelled cust_main records.
5388 sub cancelled_sql { cancel_sql(@_); }
5391 my $recurring_sql = FS::cust_pkg->recurring_sql;
5392 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5395 0 < ( $select_count_pkgs )
5396 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
5397 AND 0 = ( $select_count_pkgs AND $recurring_sql
5398 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5400 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5406 =item uncancelled_sql
5408 Returns an SQL expression identifying un-cancelled cust_main records.
5412 sub uncancelled_sql { uncancel_sql(@_); }
5413 sub uncancel_sql { "
5414 ( 0 < ( $select_count_pkgs
5415 AND ( cust_pkg.cancel IS NULL
5416 OR cust_pkg.cancel = 0
5419 OR 0 = ( $select_count_pkgs )
5425 Returns an SQL fragment to retreive the balance.
5430 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5431 WHERE cust_bill.custnum = cust_main.custnum )
5432 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5433 WHERE cust_pay.custnum = cust_main.custnum )
5434 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5435 WHERE cust_credit.custnum = cust_main.custnum )
5436 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5437 WHERE cust_refund.custnum = cust_main.custnum )
5440 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5442 Returns an SQL fragment to retreive the balance for this customer, only
5443 considering invoices with date earlier than START_TIME, and optionally not
5444 later than END_TIME (total_owed_date minus total_credited minus
5445 total_unapplied_payments).
5447 Times are specified as SQL fragments or numeric
5448 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5449 L<Date::Parse> for conversion functions. The empty string can be passed
5450 to disable that time constraint completely.
5452 Available options are:
5456 =item unapplied_date
5458 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)
5463 set to true to remove all customer comparison clauses, for totals
5468 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5473 JOIN clause (typically used with the total option)
5479 sub balance_date_sql {
5480 my( $class, $start, $end, %opt ) = @_;
5482 my $owed = FS::cust_bill->owed_sql;
5483 my $unapp_refund = FS::cust_refund->unapplied_sql;
5484 my $unapp_credit = FS::cust_credit->unapplied_sql;
5485 my $unapp_pay = FS::cust_pay->unapplied_sql;
5487 my $j = $opt{'join'} || '';
5489 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5490 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5491 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5492 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5494 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5495 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5496 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5497 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5502 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5504 Helper method for balance_date_sql; name (and usage) subject to change
5505 (suggestions welcome).
5507 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5508 cust_refund, cust_credit or cust_pay).
5510 If TABLE is "cust_bill" or the unapplied_date option is true, only
5511 considers records with date earlier than START_TIME, and optionally not
5512 later than END_TIME .
5516 sub _money_table_where {
5517 my( $class, $table, $start, $end, %opt ) = @_;
5520 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5521 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5522 push @where, "$table._date <= $start" if defined($start) && length($start);
5523 push @where, "$table._date > $end" if defined($end) && length($end);
5525 push @where, @{$opt{'where'}} if $opt{'where'};
5526 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5532 =item search_sql HASHREF
5536 Returns a qsearch hash expression to search for parameters specified in HREF.
5537 Valid parameters are
5545 =item cancelled_pkgs
5551 listref of start date, end date
5557 =item current_balance
5559 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5563 =item flattened_pkgs
5572 my ($class, $params) = @_;
5583 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5585 "cust_main.agentnum = $1";
5592 #prospect active inactive suspended cancelled
5593 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5594 my $method = $params->{'status'}. '_sql';
5595 #push @where, $class->$method();
5596 push @where, FS::cust_main->$method();
5600 # parse cancelled package checkbox
5605 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5606 unless $params->{'cancelled_pkgs'};
5612 foreach my $field (qw( signupdate )) {
5614 next unless exists($params->{$field});
5616 my($beginning, $ending) = @{$params->{$field}};
5619 "cust_main.$field IS NOT NULL",
5620 "cust_main.$field >= $beginning",
5621 "cust_main.$field <= $ending";
5623 $orderby ||= "ORDER BY cust_main.$field";
5631 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5633 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5640 #my $balance_sql = $class->balance_sql();
5641 my $balance_sql = FS::cust_main->balance_sql();
5643 push @where, map { s/current_balance/$balance_sql/; $_ }
5644 @{ $params->{'current_balance'} };
5650 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
5652 "cust_main.custbatch = '$1'";
5656 # setup queries, subs, etc. for the search
5659 $orderby ||= 'ORDER BY custnum';
5661 # here is the agent virtualization
5662 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5664 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5666 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5668 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5670 my $select = join(', ',
5671 'cust_main.custnum',
5672 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5675 my(@extra_headers) = ();
5676 my(@extra_fields) = ();
5678 if ($params->{'flattened_pkgs'}) {
5680 if ($dbh->{Driver}->{Name} eq 'Pg') {
5682 $select .= ", array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
5684 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5685 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5686 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5688 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5689 "omitting packing information from report.";
5692 my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
5694 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5695 $sth->execute() or die $sth->errstr;
5696 my $headerrow = $sth->fetchrow_arrayref;
5697 my $headercount = $headerrow ? $headerrow->[0] : 0;
5698 while($headercount) {
5699 unshift @extra_headers, "Package ". $headercount;
5700 unshift @extra_fields, eval q!sub {my $c = shift;
5701 my @a = split '\|', $c->magic;
5702 my $p = $a[!.--$headercount. q!];
5710 'table' => 'cust_main',
5711 'select' => $select,
5713 'extra_sql' => $extra_sql,
5714 'order_by' => $orderby,
5715 'count_query' => $count_query,
5716 'extra_headers' => \@extra_headers,
5717 'extra_fields' => \@extra_fields,
5722 =item email_search_sql HASHREF
5726 Emails a notice to the specified customers.
5728 Valid parameters are those of the L<search_sql> method, plus the following:
5750 Optional job queue job for status updates.
5754 Returns an error message, or false for success.
5756 If an error occurs during any email, stops the enture send and returns that
5757 error. Presumably if you're getting SMTP errors aborting is better than
5758 retrying everything.
5762 sub email_search_sql {
5763 my($class, $params) = @_;
5765 my $from = delete $params->{from};
5766 my $subject = delete $params->{subject};
5767 my $html_body = delete $params->{html_body};
5768 my $text_body = delete $params->{text_body};
5770 my $job = delete $params->{'job'};
5772 my $sql_query = $class->search_sql($params);
5774 my $count_query = delete($sql_query->{'count_query'});
5775 my $count_sth = dbh->prepare($count_query)
5776 or die "Error preparing $count_query: ". dbh->errstr;
5778 or die "Error executing $count_query: ". $count_sth->errstr;
5779 my $count_arrayref = $count_sth->fetchrow_arrayref;
5780 my $num_cust = $count_arrayref->[0];
5782 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5783 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5786 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5788 #eventually order+limit magic to reduce memory use?
5789 foreach my $cust_main ( qsearch($sql_query) ) {
5791 my $to = $cust_main->invoicing_list_emailonly_scalar;
5794 my $error = send_email(
5798 'subject' => $subject,
5799 'html_body' => $html_body,
5800 'text_body' => $text_body,
5803 return $error if $error;
5805 if ( $job ) { #progressbar foo
5807 if ( time - $min_sec > $last ) {
5808 my $error = $job->update_statustext(
5809 int( 100 * $num / $num_cust )
5811 die $error if $error;
5821 use Storable qw(thaw);
5824 sub process_email_search_sql {
5826 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5828 my $param = thaw(decode_base64(shift));
5829 warn Dumper($param) if $DEBUG;
5831 $param->{'job'} = $job;
5833 my $error = FS::cust_main->email_search_sql( $param );
5834 die $error if $error;
5838 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5840 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5841 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5842 appropriate ship_ field is also searched).
5844 Additional options are the same as FS::Record::qsearch
5849 my( $self, $fuzzy, $hash, @opt) = @_;
5854 check_and_rebuild_fuzzyfiles();
5855 foreach my $field ( keys %$fuzzy ) {
5857 my $all = $self->all_X($field);
5858 next unless scalar(@$all);
5861 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5864 foreach ( keys %match ) {
5865 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5866 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5869 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5872 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5874 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5882 Returns a masked version of the named field
5887 my ($self,$field) = @_;
5891 'x'x(length($self->getfield($field))-4).
5892 substr($self->getfield($field), (length($self->getfield($field))-4));
5902 =item smart_search OPTION => VALUE ...
5904 Accepts the following options: I<search>, the string to search for. The string
5905 will be searched for as a customer number, phone number, name or company name,
5906 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5907 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5908 skip fuzzy matching when an exact match is found.
5910 Any additional options are treated as an additional qualifier on the search
5913 Returns a (possibly empty) array of FS::cust_main objects.
5920 #here is the agent virtualization
5921 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5925 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5926 my $search = delete $options{'search'};
5927 ( my $alphanum_search = $search ) =~ s/\W//g;
5929 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5931 #false laziness w/Record::ut_phone
5932 my $phonen = "$1-$2-$3";
5933 $phonen .= " x$4" if $4;
5935 push @cust_main, qsearch( {
5936 'table' => 'cust_main',
5937 'hashref' => { %options },
5938 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5940 join(' OR ', map "$_ = '$phonen'",
5941 qw( daytime night fax
5942 ship_daytime ship_night ship_fax )
5945 " AND $agentnums_sql", #agent virtualization
5948 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5949 #try looking for matches with extensions unless one was specified
5951 push @cust_main, qsearch( {
5952 'table' => 'cust_main',
5953 'hashref' => { %options },
5954 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5956 join(' OR ', map "$_ LIKE '$phonen\%'",
5958 ship_daytime ship_night )
5961 " AND $agentnums_sql", #agent virtualization
5966 # custnum search (also try agent_custid), with some tweaking options if your
5967 # legacy cust "numbers" have letters
5968 } elsif ( $search =~ /^\s*(\d+)\s*$/
5969 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5970 && $search =~ /^\s*(\w\w?\d+)\s*$/
5975 push @cust_main, qsearch( {
5976 'table' => 'cust_main',
5977 'hashref' => { 'custnum' => $1, %options },
5978 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5981 push @cust_main, qsearch( {
5982 'table' => 'cust_main',
5983 'hashref' => { 'agent_custid' => $1, %options },
5984 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5987 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5989 my($company, $last, $first) = ( $1, $2, $3 );
5991 # "Company (Last, First)"
5992 #this is probably something a browser remembered,
5993 #so just do an exact search
5995 foreach my $prefix ( '', 'ship_' ) {
5996 push @cust_main, qsearch( {
5997 'table' => 'cust_main',
5998 'hashref' => { $prefix.'first' => $first,
5999 $prefix.'last' => $last,
6000 $prefix.'company' => $company,
6003 'extra_sql' => " AND $agentnums_sql",
6007 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
6008 # try (ship_){last,company}
6012 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
6013 # # full strings the browser remembers won't work
6014 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
6016 use Lingua::EN::NameParse;
6017 my $NameParse = new Lingua::EN::NameParse(
6019 allow_reversed => 1,
6022 my($last, $first) = ( '', '' );
6023 #maybe disable this too and just rely on NameParse?
6024 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
6026 ($last, $first) = ( $1, $2 );
6028 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
6029 } elsif ( ! $NameParse->parse($value) ) {
6031 my %name = $NameParse->components;
6032 $first = $name{'given_name_1'};
6033 $last = $name{'surname_1'};
6037 if ( $first && $last ) {
6039 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
6042 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6044 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
6045 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
6048 push @cust_main, qsearch( {
6049 'table' => 'cust_main',
6050 'hashref' => \%options,
6051 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6054 # or it just be something that was typed in... (try that in a sec)
6058 my $q_value = dbh->quote($value);
6061 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6062 $sql .= " ( LOWER(last) = $q_value
6063 OR LOWER(company) = $q_value
6064 OR LOWER(ship_last) = $q_value
6065 OR LOWER(ship_company) = $q_value
6068 push @cust_main, qsearch( {
6069 'table' => 'cust_main',
6070 'hashref' => \%options,
6071 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6074 #no exact match, trying substring/fuzzy
6075 #always do substring & fuzzy (unless they're explicity config'ed off)
6076 #getting complaints searches are not returning enough
6077 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
6079 #still some false laziness w/search_sql (was search/cust_main.cgi)
6084 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
6085 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
6088 if ( $first && $last ) {
6091 { 'first' => { op=>'ILIKE', value=>"%$first%" },
6092 'last' => { op=>'ILIKE', value=>"%$last%" },
6094 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
6095 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
6102 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
6103 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
6107 foreach my $hashref ( @hashrefs ) {
6109 push @cust_main, qsearch( {
6110 'table' => 'cust_main',
6111 'hashref' => { %$hashref,
6114 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6123 " AND $agentnums_sql", #extra_sql #agent virtualization
6126 if ( $first && $last ) {
6127 push @cust_main, FS::cust_main->fuzzy_search(
6128 { 'last' => $last, #fuzzy hashref
6129 'first' => $first }, #
6133 foreach my $field ( 'last', 'company' ) {
6135 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6140 #eliminate duplicates
6142 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6152 Accepts the following options: I<email>, the email address to search for. The
6153 email address will be searched for as an email invoice destination and as an
6156 #Any additional options are treated as an additional qualifier on the search
6157 #(i.e. I<agentnum>).
6159 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6169 my $email = delete $options{'email'};
6171 #we're only being used by RT at the moment... no agent virtualization yet
6172 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6176 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6178 my ( $user, $domain ) = ( $1, $2 );
6180 warn "$me smart_search: searching for $user in domain $domain"
6186 'table' => 'cust_main_invoice',
6187 'hashref' => { 'dest' => $email },
6194 map $_->cust_svc->cust_pkg,
6196 'table' => 'svc_acct',
6197 'hashref' => { 'username' => $user, },
6199 'AND ( SELECT domain FROM svc_domain
6200 WHERE svc_acct.domsvc = svc_domain.svcnum
6201 ) = '. dbh->quote($domain),
6207 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6209 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6216 =item check_and_rebuild_fuzzyfiles
6220 use vars qw(@fuzzyfields);
6221 @fuzzyfields = ( 'last', 'first', 'company' );
6223 sub check_and_rebuild_fuzzyfiles {
6224 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6225 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6228 =item rebuild_fuzzyfiles
6232 sub rebuild_fuzzyfiles {
6234 use Fcntl qw(:flock);
6236 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6237 mkdir $dir, 0700 unless -d $dir;
6239 foreach my $fuzzy ( @fuzzyfields ) {
6241 open(LOCK,">>$dir/cust_main.$fuzzy")
6242 or die "can't open $dir/cust_main.$fuzzy: $!";
6244 or die "can't lock $dir/cust_main.$fuzzy: $!";
6246 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6247 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6249 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6250 my $sth = dbh->prepare("SELECT $field FROM cust_main".
6251 " WHERE $field != '' AND $field IS NOT NULL");
6252 $sth->execute or die $sth->errstr;
6254 while ( my $row = $sth->fetchrow_arrayref ) {
6255 print CACHE $row->[0]. "\n";
6260 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6262 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6273 my( $self, $field ) = @_;
6274 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6275 open(CACHE,"<$dir/cust_main.$field")
6276 or die "can't open $dir/cust_main.$field: $!";
6277 my @array = map { chomp; $_; } <CACHE>;
6282 =item append_fuzzyfiles LASTNAME COMPANY
6286 sub append_fuzzyfiles {
6287 #my( $first, $last, $company ) = @_;
6289 &check_and_rebuild_fuzzyfiles;
6291 use Fcntl qw(:flock);
6293 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6295 foreach my $field (qw( first last company )) {
6300 open(CACHE,">>$dir/cust_main.$field")
6301 or die "can't open $dir/cust_main.$field: $!";
6302 flock(CACHE,LOCK_EX)
6303 or die "can't lock $dir/cust_main.$field: $!";
6305 print CACHE "$value\n";
6307 flock(CACHE,LOCK_UN)
6308 or die "can't unlock $dir/cust_main.$field: $!";
6317 =item process_batch_import
6319 Load a batch import as a queued JSRPC job
6323 use Storable qw(thaw);
6326 sub process_batch_import {
6329 my $param = thaw(decode_base64(shift));
6330 warn Dumper($param) if $DEBUG;
6332 my $files = $param->{'uploaded_files'}
6333 or die "No files provided.\n";
6335 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
6337 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
6338 my $file = $dir. $files{'file'};
6341 if ( $file =~ /\.(\w+)$/i ) {
6345 warn "can't parse file type from filename $file; defaulting to CSV";
6350 FS::cust_main::batch_import( {
6354 custbatch => $param->{custbatch},
6355 agentnum => $param->{'agentnum'},
6356 refnum => $param->{'refnum'},
6357 pkgpart => $param->{'pkgpart'},
6358 #'fields' => [qw( cust_pkg.setup dayphone first last address1 address2
6359 # city state zip comments )],
6360 'format' => $param->{'format'},
6365 die "$error\n" if $error;
6373 #some false laziness w/cdr.pm now
6377 my $job = $param->{job};
6379 my $filename = $param->{file};
6380 my $type = $param->{type} || 'csv';
6382 my $custbatch = $param->{custbatch};
6384 my $agentnum = $param->{agentnum};
6385 my $refnum = $param->{refnum};
6386 my $pkgpart = $param->{pkgpart};
6388 my $format = $param->{'format'};
6392 if ( $format eq 'simple' ) {
6393 @fields = qw( cust_pkg.setup dayphone first last
6394 address1 address2 city state zip comments );
6396 } elsif ( $format eq 'extended' ) {
6397 @fields = qw( agent_custid refnum
6398 last first address1 address2 city state zip country
6400 ship_last ship_first ship_address1 ship_address2
6401 ship_city ship_state ship_zip ship_country
6402 payinfo paycvv paydate
6405 svc_acct.username svc_acct._password
6408 } elsif ( $format eq 'extended-plus_company' ) {
6409 @fields = qw( agent_custid refnum
6410 last first company address1 address2 city state zip country
6412 ship_last ship_first ship_company ship_address1 ship_address2
6413 ship_city ship_state ship_zip ship_country
6414 payinfo paycvv paydate
6417 svc_acct.username svc_acct._password
6421 die "unknown format $format";
6427 if ( $type eq 'csv' ) {
6429 eval "use Text::CSV_XS;";
6432 $parser = new Text::CSV_XS;
6434 @buffer = split(/\r?\n/, slurp($filename) );
6435 $count = scalar(@buffer);
6437 } elsif ( $type eq 'xls' ) {
6439 eval "use Spreadsheet::ParseExcel;";
6442 my $excel = new Spreadsheet::ParseExcel::Workbook->Parse($filename);
6443 $parser = $excel->{Worksheet}[0]; #first sheet
6445 $count = $parser->{MaxRow} || $parser->{MinRow};
6449 die "Unknown file type $type\n";
6454 local $SIG{HUP} = 'IGNORE';
6455 local $SIG{INT} = 'IGNORE';
6456 local $SIG{QUIT} = 'IGNORE';
6457 local $SIG{TERM} = 'IGNORE';
6458 local $SIG{TSTP} = 'IGNORE';
6459 local $SIG{PIPE} = 'IGNORE';
6461 my $oldAutoCommit = $FS::UID::AutoCommit;
6462 local $FS::UID::AutoCommit = 0;
6467 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
6471 if ( $type eq 'csv' ) {
6473 last unless scalar(@buffer);
6474 $line = shift(@buffer);
6476 $parser->parse($line) or do {
6477 $dbh->rollback if $oldAutoCommit;
6478 return "can't parse: ". $parser->error_input();
6480 @columns = $parser->fields();
6482 } elsif ( $type eq 'xls' ) {
6484 last if $row > ($parser->{MaxRow} || $parser->{MinRow});
6486 my @row = @{ $parser->{Cells}[$row] };
6487 @columns = map $_->{Val}, @row;
6490 #warn $z++. ": $_\n" for @columns;
6493 die "Unknown file type $type\n";
6496 #warn join('-',@columns);
6499 custbatch => $custbatch,
6500 agentnum => $agentnum,
6502 country => $conf->config('countrydefault') || 'US',
6503 payby => $payby, #default
6504 paydate => '12/2037', #default
6506 my $billtime = time;
6507 my %cust_pkg = ( pkgpart => $pkgpart );
6509 foreach my $field ( @fields ) {
6511 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
6513 #$cust_pkg{$1} = str2time( shift @$columns );
6514 if ( $1 eq 'pkgpart' ) {
6515 $cust_pkg{$1} = shift @columns;
6516 } elsif ( $1 eq 'setup' ) {
6517 $billtime = str2time(shift @columns);
6519 $cust_pkg{$1} = str2time( shift @columns );
6522 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
6524 $svc_acct{$1} = shift @columns;
6528 #refnum interception
6529 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
6531 my $referral = $columns[0];
6532 my %hash = ( 'referral' => $referral,
6533 'agentnum' => $agentnum,
6537 my $part_referral = qsearchs('part_referral', \%hash )
6538 || new FS::part_referral \%hash;
6540 unless ( $part_referral->refnum ) {
6541 my $error = $part_referral->insert;
6543 $dbh->rollback if $oldAutoCommit;
6544 return "can't auto-insert advertising source: $referral: $error";
6548 $columns[0] = $part_referral->refnum;
6551 my $value = shift @columns;
6552 $cust_main{$field} = $value if length($value);
6556 $cust_main{'payby'} = 'CARD'
6557 if defined $cust_main{'payinfo'}
6558 && length $cust_main{'payinfo'};
6560 my $invoicing_list = $cust_main{'invoicing_list'}
6561 ? [ delete $cust_main{'invoicing_list'} ]
6564 my $cust_main = new FS::cust_main ( \%cust_main );
6567 tie my %hash, 'Tie::RefHash'; #this part is important
6569 if ( $cust_pkg{'pkgpart'} ) {
6570 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
6573 if ( $svc_acct{'username'} ) {
6574 my $part_pkg = $cust_pkg->part_pkg;
6575 unless ( $part_pkg ) {
6576 $dbh->rollback if $oldAutoCommit;
6577 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
6579 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
6580 push @svc_acct, new FS::svc_acct ( \%svc_acct )
6583 $hash{$cust_pkg} = \@svc_acct;
6586 my $error = $cust_main->insert( \%hash, $invoicing_list );
6589 $dbh->rollback if $oldAutoCommit;
6590 return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
6593 if ( $format eq 'simple' ) {
6595 #false laziness w/bill.cgi
6596 $error = $cust_main->bill( 'time' => $billtime );
6598 $dbh->rollback if $oldAutoCommit;
6599 return "can't bill customer for $line: $error";
6602 $error = $cust_main->apply_payments_and_credits;
6604 $dbh->rollback if $oldAutoCommit;
6605 return "can't bill customer for $line: $error";
6608 $error = $cust_main->collect();
6610 $dbh->rollback if $oldAutoCommit;
6611 return "can't collect customer for $line: $error";
6618 if ( $job && time - $min_sec > $last ) { #progress bar
6619 $job->update_statustext( int(100 * $row / $count) );
6625 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
6627 return "Empty file!" unless $row;
6639 #warn join('-',keys %$param);
6640 my $fh = $param->{filehandle};
6641 my @fields = @{$param->{fields}};
6643 eval "use Text::CSV_XS;";
6646 my $csv = new Text::CSV_XS;
6653 local $SIG{HUP} = 'IGNORE';
6654 local $SIG{INT} = 'IGNORE';
6655 local $SIG{QUIT} = 'IGNORE';
6656 local $SIG{TERM} = 'IGNORE';
6657 local $SIG{TSTP} = 'IGNORE';
6658 local $SIG{PIPE} = 'IGNORE';
6660 my $oldAutoCommit = $FS::UID::AutoCommit;
6661 local $FS::UID::AutoCommit = 0;
6664 #while ( $columns = $csv->getline($fh) ) {
6666 while ( defined($line=<$fh>) ) {
6668 $csv->parse($line) or do {
6669 $dbh->rollback if $oldAutoCommit;
6670 return "can't parse: ". $csv->error_input();
6673 my @columns = $csv->fields();
6674 #warn join('-',@columns);
6677 foreach my $field ( @fields ) {
6678 $row{$field} = shift @columns;
6681 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6682 unless ( $cust_main ) {
6683 $dbh->rollback if $oldAutoCommit;
6684 return "unknown custnum $row{'custnum'}";
6687 if ( $row{'amount'} > 0 ) {
6688 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6690 $dbh->rollback if $oldAutoCommit;
6694 } elsif ( $row{'amount'} < 0 ) {
6695 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6698 $dbh->rollback if $oldAutoCommit;
6708 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6710 return "Empty file!" unless $imported;
6716 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6718 Sends a templated email notification to the customer (see L<Text::Template>).
6720 OPTIONS is a hash and may include
6722 I<from> - the email sender (default is invoice_from)
6724 I<to> - comma-separated scalar or arrayref of recipients
6725 (default is invoicing_list)
6727 I<subject> - The subject line of the sent email notification
6728 (default is "Notice from company_name")
6730 I<extra_fields> - a hashref of name/value pairs which will be substituted
6733 The following variables are vavailable in the template.
6735 I<$first> - the customer first name
6736 I<$last> - the customer last name
6737 I<$company> - the customer company
6738 I<$payby> - a description of the method of payment for the customer
6739 # would be nice to use FS::payby::shortname
6740 I<$payinfo> - the account information used to collect for this customer
6741 I<$expdate> - the expiration of the customer payment in seconds from epoch
6746 my ($customer, $template, %options) = @_;
6748 return unless $conf->exists($template);
6750 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6751 $from = $options{from} if exists($options{from});
6753 my $to = join(',', $customer->invoicing_list_emailonly);
6754 $to = $options{to} if exists($options{to});
6756 my $subject = "Notice from " . $conf->config('company_name')
6757 if $conf->exists('company_name');
6758 $subject = $options{subject} if exists($options{subject});
6760 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6761 SOURCE => [ map "$_\n",
6762 $conf->config($template)]
6764 or die "can't create new Text::Template object: Text::Template::ERROR";
6765 $notify_template->compile()
6766 or die "can't compile template: Text::Template::ERROR";
6768 $FS::notify_template::_template::company_name = $conf->config('company_name');
6769 $FS::notify_template::_template::company_address =
6770 join("\n", $conf->config('company_address') ). "\n";
6772 my $paydate = $customer->paydate || '2037-12-31';
6773 $FS::notify_template::_template::first = $customer->first;
6774 $FS::notify_template::_template::last = $customer->last;
6775 $FS::notify_template::_template::company = $customer->company;
6776 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6777 my $payby = $customer->payby;
6778 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6779 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6781 #credit cards expire at the end of the month/year of their exp date
6782 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6783 $FS::notify_template::_template::payby = 'credit card';
6784 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6785 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6787 }elsif ($payby eq 'COMP') {
6788 $FS::notify_template::_template::payby = 'complimentary account';
6790 $FS::notify_template::_template::payby = 'current method';
6792 $FS::notify_template::_template::expdate = $expire_time;
6794 for (keys %{$options{extra_fields}}){
6796 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6799 send_email(from => $from,
6801 subject => $subject,
6802 body => $notify_template->fill_in( PACKAGE =>
6803 'FS::notify_template::_template' ),
6808 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6810 Generates a templated notification to the customer (see L<Text::Template>).
6812 OPTIONS is a hash and may include
6814 I<extra_fields> - a hashref of name/value pairs which will be substituted
6815 into the template. These values may override values mentioned below
6816 and those from the customer record.
6818 The following variables are available in the template instead of or in addition
6819 to the fields of the customer record.
6821 I<$payby> - a description of the method of payment for the customer
6822 # would be nice to use FS::payby::shortname
6823 I<$payinfo> - the masked account information used to collect for this customer
6824 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6825 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6829 sub generate_letter {
6830 my ($self, $template, %options) = @_;
6832 return unless $conf->exists($template);
6834 my $letter_template = new Text::Template
6836 SOURCE => [ map "$_\n", $conf->config($template)],
6837 DELIMITERS => [ '[@--', '--@]' ],
6839 or die "can't create new Text::Template object: Text::Template::ERROR";
6841 $letter_template->compile()
6842 or die "can't compile template: Text::Template::ERROR";
6844 my %letter_data = map { $_ => $self->$_ } $self->fields;
6845 $letter_data{payinfo} = $self->mask_payinfo;
6847 #my $paydate = $self->paydate || '2037-12-31';
6848 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6850 my $payby = $self->payby;
6851 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6852 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6854 #credit cards expire at the end of the month/year of their exp date
6855 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6856 $letter_data{payby} = 'credit card';
6857 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6858 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6860 }elsif ($payby eq 'COMP') {
6861 $letter_data{payby} = 'complimentary account';
6863 $letter_data{payby} = 'current method';
6865 $letter_data{expdate} = $expire_time;
6867 for (keys %{$options{extra_fields}}){
6868 $letter_data{$_} = $options{extra_fields}->{$_};
6871 unless(exists($letter_data{returnaddress})){
6872 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6873 $self->agent_template)
6875 if ( length($retadd) ) {
6876 $letter_data{returnaddress} = $retadd;
6877 } elsif ( grep /\S/, $conf->config('company_address') ) {
6878 $letter_data{returnaddress} =
6879 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6880 $conf->config('company_address')
6883 $letter_data{returnaddress} = '~';
6887 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6889 $letter_data{company_name} = $conf->config('company_name');
6891 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6892 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6896 ) or die "can't open temp file: $!\n";
6898 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6900 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6904 =item print_ps TEMPLATE
6906 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6912 my $file = $self->generate_letter(@_);
6913 FS::Misc::generate_ps($file);
6916 =item print TEMPLATE
6918 Prints the filled in template.
6920 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6924 sub queueable_print {
6927 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6928 or die "invalid customer number: " . $opt{custvnum};
6930 my $error = $self->print( $opt{template} );
6931 die $error if $error;
6935 my ($self, $template) = (shift, shift);
6936 do_print [ $self->print_ps($template) ];
6939 sub agent_template {
6941 $self->_agent_plandata('agent_templatename');
6944 sub agent_invoice_from {
6946 $self->_agent_plandata('agent_invoice_from');
6949 sub _agent_plandata {
6950 my( $self, $option ) = @_;
6952 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6953 #agent-specific Conf
6955 use FS::part_event::Condition;
6957 my $agentnum = $self->agentnum;
6960 if ( driver_name =~ /^Pg/i ) {
6962 } elsif ( driver_name =~ /^mysql/i ) {
6965 die "don't know how to use regular expressions in ". driver_name. " databases";
6968 my $part_event_option =
6970 'select' => 'part_event_option.*',
6971 'table' => 'part_event_option',
6973 LEFT JOIN part_event USING ( eventpart )
6974 LEFT JOIN part_event_option AS peo_agentnum
6975 ON ( part_event.eventpart = peo_agentnum.eventpart
6976 AND peo_agentnum.optionname = 'agentnum'
6977 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6979 LEFT JOIN part_event_option AS peo_cust_bill_age
6980 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6981 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6984 #'hashref' => { 'optionname' => $option },
6985 #'hashref' => { 'part_event_option.optionname' => $option },
6987 " WHERE part_event_option.optionname = ". dbh->quote($option).
6988 " AND action = 'cust_bill_send_agent' ".
6989 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6990 " AND peo_agentnum.optionname = 'agentnum' ".
6991 " AND agentnum IS NULL OR agentnum = $agentnum ".
6993 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6995 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6997 , part_event.weight".
7001 unless ( $part_event_option ) {
7002 return $self->agent->invoice_template || ''
7003 if $option eq 'agent_templatename';
7007 $part_event_option->optionvalue;
7012 ## actual sub, not a method, designed to be called from the queue.
7013 ## sets up the customer, and calls the bill_and_collect
7014 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
7015 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
7016 $cust_main->bill_and_collect(
7027 The delete method should possibly take an FS::cust_main object reference
7028 instead of a scalar customer number.
7030 Bill and collect options should probably be passed as references instead of a
7033 There should probably be a configuration file with a list of allowed credit
7036 No multiple currency support (probably a larger project than just this module).
7038 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
7040 Birthdates rely on negative epoch values.
7042 The payby for card/check batches is broken. With mixed batching, bad
7045 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
7049 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
7050 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
7051 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.