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);
18 use File::Temp qw( tempfile );
19 use String::Approx qw(amatch);
20 use Business::CreditCard 0.28;
22 use FS::UID qw( getotaker dbh driver_name );
23 use FS::Record qw( qsearchs qsearch dbdef );
24 use FS::Misc qw( generate_email send_email generate_ps do_print );
25 use FS::Msgcat qw(gettext);
29 use FS::cust_bill_pkg;
30 use FS::cust_bill_pkg_display;
32 use FS::cust_pay_pending;
33 use FS::cust_pay_void;
34 use FS::cust_pay_batch;
37 use FS::part_referral;
38 use FS::cust_main_county;
40 use FS::cust_tax_location;
41 use FS::part_pkg_taxrate;
43 use FS::cust_main_invoice;
44 use FS::cust_credit_bill;
45 use FS::cust_bill_pay;
46 use FS::prepay_credit;
50 use FS::part_event_condition;
53 use FS::payment_gateway;
54 use FS::agent_payment_gateway;
56 use FS::payinfo_Mixin;
59 @ISA = qw( FS::payinfo_Mixin FS::Record );
61 @EXPORT_OK = qw( smart_search );
63 $realtime_bop_decline_quiet = 0;
65 # 1 is mostly method/subroutine entry and options
66 # 2 traces progress of some operations
67 # 3 is even more information including possibly sensitive data
69 $me = '[FS::cust_main]';
73 $ignore_expired_card = 0;
75 @encrypted_fields = ('payinfo', 'paycvv');
76 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
78 #ask FS::UID to run this stuff for us later
79 #$FS::UID::callback{'FS::cust_main'} = sub {
80 install_callback FS::UID sub {
82 #yes, need it for stuff below (prolly should be cached)
87 my ( $hashref, $cache ) = @_;
88 if ( exists $hashref->{'pkgnum'} ) {
89 #@{ $self->{'_pkgnum'} } = ();
90 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
91 $self->{'_pkgnum'} = $subcache;
92 #push @{ $self->{'_pkgnum'} },
93 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
99 FS::cust_main - Object methods for cust_main records
105 $record = new FS::cust_main \%hash;
106 $record = new FS::cust_main { 'column' => 'value' };
108 $error = $record->insert;
110 $error = $new_record->replace($old_record);
112 $error = $record->delete;
114 $error = $record->check;
116 @cust_pkg = $record->all_pkgs;
118 @cust_pkg = $record->ncancelled_pkgs;
120 @cust_pkg = $record->suspended_pkgs;
122 $error = $record->bill;
123 $error = $record->bill %options;
124 $error = $record->bill 'time' => $time;
126 $error = $record->collect;
127 $error = $record->collect %options;
128 $error = $record->collect 'invoice_time' => $time,
133 An FS::cust_main object represents a customer. FS::cust_main inherits from
134 FS::Record. The following fields are currently supported:
138 =item custnum - primary key (assigned automatically for new customers)
140 =item agentnum - agent (see L<FS::agent>)
142 =item refnum - Advertising source (see L<FS::part_referral>)
148 =item ss - social security number (optional)
150 =item company - (optional)
154 =item address2 - (optional)
158 =item county - (optional, see L<FS::cust_main_county>)
160 =item state - (see L<FS::cust_main_county>)
164 =item country - (see L<FS::cust_main_county>)
166 =item daytime - phone (optional)
168 =item night - phone (optional)
170 =item fax - phone (optional)
172 =item ship_first - name
174 =item ship_last - name
176 =item ship_company - (optional)
180 =item ship_address2 - (optional)
184 =item ship_county - (optional, see L<FS::cust_main_county>)
186 =item ship_state - (see L<FS::cust_main_county>)
190 =item ship_country - (see L<FS::cust_main_county>)
192 =item ship_daytime - phone (optional)
194 =item ship_night - phone (optional)
196 =item ship_fax - phone (optional)
198 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
200 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
202 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
206 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
208 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
210 =item paystart_month - start date month (maestro/solo cards only)
212 =item paystart_year - start date year (maestro/solo cards only)
214 =item payissue - issue number (maestro/solo cards only)
216 =item payname - name on card or billing name
218 =item payip - IP address from which payment information was received
220 =item tax - tax exempt, empty or `Y'
222 =item otaker - order taker (assigned automatically, see L<FS::UID>)
224 =item comments - comments (optional)
226 =item referral_custnum - referring customer number
228 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
230 =item dundate - a suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
232 =item squelch_cdr - Discourage individual CDR printing, empty or `Y'
242 Creates a new customer. To add the customer to the database, see L<"insert">.
244 Note that this stores the hash reference, not a distinct copy of the hash it
245 points to. You can ask the object for a copy with the I<hash> method.
249 sub table { 'cust_main'; }
251 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
253 Adds this customer to the database. If there is an error, returns the error,
254 otherwise returns false.
256 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
257 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
258 are inserted atomicly, or the transaction is rolled back. Passing an empty
259 hash reference is equivalent to not supplying this parameter. There should be
260 a better explanation of this, but until then, here's an example:
263 tie %hash, 'Tie::RefHash'; #this part is important
265 $cust_pkg => [ $svc_acct ],
268 $cust_main->insert( \%hash );
270 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
271 be set as the invoicing list (see L<"invoicing_list">). Errors return as
272 expected and rollback the entire transaction; it is not necessary to call
273 check_invoicing_list first. The invoicing_list is set after the records in the
274 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
275 invoicing_list destination to the newly-created svc_acct. Here's an example:
277 $cust_main->insert( {}, [ $email, 'POST' ] );
279 Currently available options are: I<depend_jobnum> and I<noexport>.
281 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
282 on the supplied jobnum (they will not run until the specific job completes).
283 This can be used to defer provisioning until some action completes (such
284 as running the customer's credit card successfully).
286 The I<noexport> option is deprecated. If I<noexport> is set true, no
287 provisioning jobs (exports) are scheduled. (You can schedule them later with
288 the B<reexport> method.)
294 my $cust_pkgs = @_ ? shift : {};
295 my $invoicing_list = @_ ? shift : '';
297 warn "$me insert called with options ".
298 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
301 local $SIG{HUP} = 'IGNORE';
302 local $SIG{INT} = 'IGNORE';
303 local $SIG{QUIT} = 'IGNORE';
304 local $SIG{TERM} = 'IGNORE';
305 local $SIG{TSTP} = 'IGNORE';
306 local $SIG{PIPE} = 'IGNORE';
308 my $oldAutoCommit = $FS::UID::AutoCommit;
309 local $FS::UID::AutoCommit = 0;
312 my $prepay_identifier = '';
313 my( $amount, $seconds ) = ( 0, 0 );
315 if ( $self->payby eq 'PREPAY' ) {
317 $self->payby('BILL');
318 $prepay_identifier = $self->payinfo;
321 warn " looking up prepaid card $prepay_identifier\n"
324 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
326 $dbh->rollback if $oldAutoCommit;
327 #return "error applying prepaid card (transaction rolled back): $error";
331 $payby = 'PREP' if $amount;
333 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
336 $self->payby('BILL');
337 $amount = $self->paid;
341 warn " inserting $self\n"
344 $self->signupdate(time) unless $self->signupdate;
346 $self->auto_agent_custid()
347 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
349 my $error = $self->SUPER::insert;
351 $dbh->rollback if $oldAutoCommit;
352 #return "inserting cust_main record (transaction rolled back): $error";
356 warn " setting invoicing list\n"
359 if ( $invoicing_list ) {
360 $error = $self->check_invoicing_list( $invoicing_list );
362 $dbh->rollback if $oldAutoCommit;
363 #return "checking invoicing_list (transaction rolled back): $error";
366 $self->invoicing_list( $invoicing_list );
369 if ( $conf->config('cust_main-skeleton_tables')
370 && $conf->config('cust_main-skeleton_custnum') ) {
372 warn " inserting skeleton records\n"
375 my $error = $self->start_copy_skel;
377 $dbh->rollback if $oldAutoCommit;
383 warn " ordering packages\n"
386 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
388 $dbh->rollback if $oldAutoCommit;
393 $dbh->rollback if $oldAutoCommit;
394 return "No svc_acct record to apply pre-paid time";
398 warn " inserting initial $payby payment of $amount\n"
400 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
402 $dbh->rollback if $oldAutoCommit;
403 return "inserting payment (transaction rolled back): $error";
407 unless ( $import || $skip_fuzzyfiles ) {
408 warn " queueing fuzzyfiles update\n"
410 $error = $self->queue_fuzzyfiles_update;
412 $dbh->rollback if $oldAutoCommit;
413 return "updating fuzzy search cache: $error";
417 warn " insert complete; committing transaction\n"
420 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
425 use File::CounterFile;
426 sub auto_agent_custid {
429 my $format = $conf->config('cust_main-auto_agent_custid');
431 if ( $format eq '1YMMXXXXXXXX' ) {
433 my $counter = new File::CounterFile 'cust_main.agent_custid';
436 my $ym = 100000000000 + time2str('%y%m00000000', time);
437 if ( $ym > $counter->value ) {
438 $counter->{'value'} = $agent_custid = $ym;
439 $counter->{'updated'} = 1;
441 $agent_custid = $counter->inc;
447 die "Unknown cust_main-auto_agent_custid format: $format";
450 $self->agent_custid($agent_custid);
454 sub start_copy_skel {
457 #'mg_user_preference' => {},
458 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
459 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
460 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
461 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
462 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
465 _copy_skel( 'cust_main', #tablename
466 $conf->config('cust_main-skeleton_custnum'), #sourceid
467 $self->custnum, #destid
468 @tables, #child tables
472 #recursive subroutine, not a method
474 my( $table, $sourceid, $destid, %child_tables ) = @_;
477 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
478 ( $table, $primary_key ) = ( $1, $2 );
480 my $dbdef_table = dbdef->table($table);
481 $primary_key = $dbdef_table->primary_key
482 or return "$table has no primary key".
483 " (or do you need to run dbdef-create?)";
486 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
487 join (', ', keys %child_tables). "\n"
490 foreach my $child_table_def ( keys %child_tables ) {
494 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
495 ( $child_table, $child_pkey ) = ( $1, $2 );
497 $child_table = $child_table_def;
499 $child_pkey = dbdef->table($child_table)->primary_key;
500 # or return "$table has no primary key".
501 # " (or do you need to run dbdef-create?)\n";
505 if ( keys %{ $child_tables{$child_table_def} } ) {
507 return "$child_table has no primary key".
508 " (run dbdef-create or try specifying it?)\n"
511 #false laziness w/Record::insert and only works on Pg
512 #refactor the proper last-inserted-id stuff out of Record::insert if this
513 # ever gets use for anything besides a quick kludge for one customer
514 my $default = dbdef->table($child_table)->column($child_pkey)->default;
515 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
516 or return "can't parse $child_table.$child_pkey default value ".
517 " for sequence name: $default";
522 my @sel_columns = grep { $_ ne $primary_key }
523 dbdef->table($child_table)->columns;
524 my $sel_columns = join(', ', @sel_columns );
526 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
527 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
528 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
530 my $sel_st = "SELECT $sel_columns FROM $child_table".
531 " WHERE $primary_key = $sourceid";
534 my $sel_sth = dbh->prepare( $sel_st )
535 or return dbh->errstr;
537 $sel_sth->execute or return $sel_sth->errstr;
539 while ( my $row = $sel_sth->fetchrow_hashref ) {
541 warn " selected row: ".
542 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
546 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
547 my $ins_sth =dbh->prepare($statement)
548 or return dbh->errstr;
549 my @param = ( $destid, map $row->{$_}, @ins_columns );
550 warn " $statement: [ ". join(', ', @param). " ]\n"
552 $ins_sth->execute( @param )
553 or return $ins_sth->errstr;
555 #next unless keys %{ $child_tables{$child_table} };
556 next unless $sequence;
558 #another section of that laziness
559 my $seq_sql = "SELECT currval('$sequence')";
560 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
561 $seq_sth->execute or return $seq_sth->errstr;
562 my $insertid = $seq_sth->fetchrow_arrayref->[0];
564 # don't drink soap! recurse! recurse! okay!
566 _copy_skel( $child_table_def,
567 $row->{$child_pkey}, #sourceid
569 %{ $child_tables{$child_table_def} },
571 return $error if $error;
581 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
583 Like the insert method on an existing record, this method orders a package
584 and included services atomicaly. Pass a Tie::RefHash data structure to this
585 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
586 be a better explanation of this, but until then, here's an example:
589 tie %hash, 'Tie::RefHash'; #this part is important
591 $cust_pkg => [ $svc_acct ],
594 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
596 Services can be new, in which case they are inserted, or existing unaudited
597 services, in which case they are linked to the newly-created package.
599 Currently available options are: I<depend_jobnum> and I<noexport>.
601 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
602 on the supplied jobnum (they will not run until the specific job completes).
603 This can be used to defer provisioning until some action completes (such
604 as running the customer's credit card successfully).
606 The I<noexport> option is deprecated. If I<noexport> is set true, no
607 provisioning jobs (exports) are scheduled. (You can schedule them later with
608 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
609 on the cust_main object is not recommended, as existing services will also be
616 my $cust_pkgs = shift;
619 my %svc_options = ();
620 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
621 if exists $options{'depend_jobnum'};
622 warn "$me order_pkgs called with options ".
623 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
626 local $SIG{HUP} = 'IGNORE';
627 local $SIG{INT} = 'IGNORE';
628 local $SIG{QUIT} = 'IGNORE';
629 local $SIG{TERM} = 'IGNORE';
630 local $SIG{TSTP} = 'IGNORE';
631 local $SIG{PIPE} = 'IGNORE';
633 my $oldAutoCommit = $FS::UID::AutoCommit;
634 local $FS::UID::AutoCommit = 0;
637 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
639 foreach my $cust_pkg ( keys %$cust_pkgs ) {
640 $cust_pkg->custnum( $self->custnum );
641 my $error = $cust_pkg->insert;
643 $dbh->rollback if $oldAutoCommit;
644 return "inserting cust_pkg (transaction rolled back): $error";
646 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
647 if ( $svc_something->svcnum ) {
648 my $old_cust_svc = $svc_something->cust_svc;
649 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
650 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
651 $error = $new_cust_svc->replace($old_cust_svc);
653 $svc_something->pkgnum( $cust_pkg->pkgnum );
654 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
655 $svc_something->seconds( $svc_something->seconds + $$seconds );
658 $error = $svc_something->insert(%svc_options);
661 $dbh->rollback if $oldAutoCommit;
662 #return "inserting svc_ (transaction rolled back): $error";
668 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
672 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
674 Recharges this (existing) customer with the specified prepaid card (see
675 L<FS::prepay_credit>), specified either by I<identifier> or as an
676 FS::prepay_credit object. If there is an error, returns the error, otherwise
679 Optionally, four scalar references can be passed as well. They will have their
680 values filled in with the amount, number of seconds, and number of upload and
681 download bytes applied by this prepaid
686 sub recharge_prepay {
687 my( $self, $prepay_credit, $amountref, $secondsref,
688 $upbytesref, $downbytesref, $totalbytesref ) = @_;
690 local $SIG{HUP} = 'IGNORE';
691 local $SIG{INT} = 'IGNORE';
692 local $SIG{QUIT} = 'IGNORE';
693 local $SIG{TERM} = 'IGNORE';
694 local $SIG{TSTP} = 'IGNORE';
695 local $SIG{PIPE} = 'IGNORE';
697 my $oldAutoCommit = $FS::UID::AutoCommit;
698 local $FS::UID::AutoCommit = 0;
701 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
703 my $error = $self->get_prepay($prepay_credit, \$amount,
704 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
705 || $self->increment_seconds($seconds)
706 || $self->increment_upbytes($upbytes)
707 || $self->increment_downbytes($downbytes)
708 || $self->increment_totalbytes($totalbytes)
709 || $self->insert_cust_pay_prepay( $amount,
711 ? $prepay_credit->identifier
716 $dbh->rollback if $oldAutoCommit;
720 if ( defined($amountref) ) { $$amountref = $amount; }
721 if ( defined($secondsref) ) { $$secondsref = $seconds; }
722 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
723 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
724 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
726 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
731 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
733 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
734 specified either by I<identifier> or as an FS::prepay_credit object.
736 References to I<amount> and I<seconds> scalars should be passed as arguments
737 and will be incremented by the values of the prepaid card.
739 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
740 check or set this customer's I<agentnum>.
742 If there is an error, returns the error, otherwise returns false.
748 my( $self, $prepay_credit, $amountref, $secondsref,
749 $upref, $downref, $totalref) = @_;
751 local $SIG{HUP} = 'IGNORE';
752 local $SIG{INT} = 'IGNORE';
753 local $SIG{QUIT} = 'IGNORE';
754 local $SIG{TERM} = 'IGNORE';
755 local $SIG{TSTP} = 'IGNORE';
756 local $SIG{PIPE} = 'IGNORE';
758 my $oldAutoCommit = $FS::UID::AutoCommit;
759 local $FS::UID::AutoCommit = 0;
762 unless ( ref($prepay_credit) ) {
764 my $identifier = $prepay_credit;
766 $prepay_credit = qsearchs(
768 { 'identifier' => $prepay_credit },
773 unless ( $prepay_credit ) {
774 $dbh->rollback if $oldAutoCommit;
775 return "Invalid prepaid card: ". $identifier;
780 if ( $prepay_credit->agentnum ) {
781 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
782 $dbh->rollback if $oldAutoCommit;
783 return "prepaid card not valid for agent ". $self->agentnum;
785 $self->agentnum($prepay_credit->agentnum);
788 my $error = $prepay_credit->delete;
790 $dbh->rollback if $oldAutoCommit;
791 return "removing prepay_credit (transaction rolled back): $error";
794 $$amountref += $prepay_credit->amount;
795 $$secondsref += $prepay_credit->seconds;
796 $$upref += $prepay_credit->upbytes;
797 $$downref += $prepay_credit->downbytes;
798 $$totalref += $prepay_credit->totalbytes;
800 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
805 =item increment_upbytes SECONDS
807 Updates this customer's single or primary account (see L<FS::svc_acct>) by
808 the specified number of upbytes. If there is an error, returns the error,
809 otherwise returns false.
813 sub increment_upbytes {
814 _increment_column( shift, 'upbytes', @_);
817 =item increment_downbytes SECONDS
819 Updates this customer's single or primary account (see L<FS::svc_acct>) by
820 the specified number of downbytes. If there is an error, returns the error,
821 otherwise returns false.
825 sub increment_downbytes {
826 _increment_column( shift, 'downbytes', @_);
829 =item increment_totalbytes SECONDS
831 Updates this customer's single or primary account (see L<FS::svc_acct>) by
832 the specified number of totalbytes. If there is an error, returns the error,
833 otherwise returns false.
837 sub increment_totalbytes {
838 _increment_column( shift, 'totalbytes', @_);
841 =item increment_seconds SECONDS
843 Updates this customer's single or primary account (see L<FS::svc_acct>) by
844 the specified number of seconds. If there is an error, returns the error,
845 otherwise returns false.
849 sub increment_seconds {
850 _increment_column( shift, 'seconds', @_);
853 =item _increment_column AMOUNT
855 Updates this customer's single or primary account (see L<FS::svc_acct>) by
856 the specified number of seconds or bytes. If there is an error, returns
857 the error, otherwise returns false.
861 sub _increment_column {
862 my( $self, $column, $amount ) = @_;
863 warn "$me increment_column called: $column, $amount\n"
866 return '' unless $amount;
868 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
869 $self->ncancelled_pkgs;
872 return 'No packages with primary or single services found'.
873 ' to apply pre-paid time';
874 } elsif ( scalar(@cust_pkg) > 1 ) {
875 #maybe have a way to specify the package/account?
876 return 'Multiple packages found to apply pre-paid time';
879 my $cust_pkg = $cust_pkg[0];
880 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
884 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
887 return 'No account found to apply pre-paid time';
888 } elsif ( scalar(@cust_svc) > 1 ) {
889 return 'Multiple accounts found to apply pre-paid time';
892 my $svc_acct = $cust_svc[0]->svc_x;
893 warn " found service svcnum ". $svc_acct->pkgnum.
894 ' ('. $svc_acct->email. ")\n"
897 $column = "increment_$column";
898 $svc_acct->$column($amount);
902 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
904 Inserts a prepayment in the specified amount for this customer. An optional
905 second argument can specify the prepayment identifier for tracking purposes.
906 If there is an error, returns the error, otherwise returns false.
910 sub insert_cust_pay_prepay {
911 shift->insert_cust_pay('PREP', @_);
914 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
916 Inserts a cash payment in the specified amount for this customer. An optional
917 second argument can specify the payment identifier for tracking purposes.
918 If there is an error, returns the error, otherwise returns false.
922 sub insert_cust_pay_cash {
923 shift->insert_cust_pay('CASH', @_);
926 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
928 Inserts a Western Union payment in the specified amount for this customer. An
929 optional second argument can specify the prepayment identifier for tracking
930 purposes. If there is an error, returns the error, otherwise returns false.
934 sub insert_cust_pay_west {
935 shift->insert_cust_pay('WEST', @_);
938 sub insert_cust_pay {
939 my( $self, $payby, $amount ) = splice(@_, 0, 3);
940 my $payinfo = scalar(@_) ? shift : '';
942 my $cust_pay = new FS::cust_pay {
943 'custnum' => $self->custnum,
944 'paid' => sprintf('%.2f', $amount),
945 #'_date' => #date the prepaid card was purchased???
947 'payinfo' => $payinfo,
955 This method is deprecated. See the I<depend_jobnum> option to the insert and
956 order_pkgs methods for a better way to defer provisioning.
958 Re-schedules all exports by calling the B<reexport> method of all associated
959 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
960 otherwise returns false.
967 carp "WARNING: FS::cust_main::reexport is deprectated; ".
968 "use the depend_jobnum option to insert or order_pkgs to delay export";
970 local $SIG{HUP} = 'IGNORE';
971 local $SIG{INT} = 'IGNORE';
972 local $SIG{QUIT} = 'IGNORE';
973 local $SIG{TERM} = 'IGNORE';
974 local $SIG{TSTP} = 'IGNORE';
975 local $SIG{PIPE} = 'IGNORE';
977 my $oldAutoCommit = $FS::UID::AutoCommit;
978 local $FS::UID::AutoCommit = 0;
981 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
982 my $error = $cust_pkg->reexport;
984 $dbh->rollback if $oldAutoCommit;
989 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
994 =item delete NEW_CUSTNUM
996 This deletes the customer. If there is an error, returns the error, otherwise
999 This will completely remove all traces of the customer record. This is not
1000 what you want when a customer cancels service; for that, cancel all of the
1001 customer's packages (see L</cancel>).
1003 If the customer has any uncancelled packages, you need to pass a new (valid)
1004 customer number for those packages to be transferred to. Cancelled packages
1005 will be deleted. Did I mention that this is NOT what you want when a customer
1006 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1008 You can't delete a customer with invoices (see L<FS::cust_bill>),
1009 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1010 refunds (see L<FS::cust_refund>).
1017 local $SIG{HUP} = 'IGNORE';
1018 local $SIG{INT} = 'IGNORE';
1019 local $SIG{QUIT} = 'IGNORE';
1020 local $SIG{TERM} = 'IGNORE';
1021 local $SIG{TSTP} = 'IGNORE';
1022 local $SIG{PIPE} = 'IGNORE';
1024 my $oldAutoCommit = $FS::UID::AutoCommit;
1025 local $FS::UID::AutoCommit = 0;
1028 if ( $self->cust_bill ) {
1029 $dbh->rollback if $oldAutoCommit;
1030 return "Can't delete a customer with invoices";
1032 if ( $self->cust_credit ) {
1033 $dbh->rollback if $oldAutoCommit;
1034 return "Can't delete a customer with credits";
1036 if ( $self->cust_pay ) {
1037 $dbh->rollback if $oldAutoCommit;
1038 return "Can't delete a customer with payments";
1040 if ( $self->cust_refund ) {
1041 $dbh->rollback if $oldAutoCommit;
1042 return "Can't delete a customer with refunds";
1045 my @cust_pkg = $self->ncancelled_pkgs;
1047 my $new_custnum = shift;
1048 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1049 $dbh->rollback if $oldAutoCommit;
1050 return "Invalid new customer number: $new_custnum";
1052 foreach my $cust_pkg ( @cust_pkg ) {
1053 my %hash = $cust_pkg->hash;
1054 $hash{'custnum'} = $new_custnum;
1055 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1056 my $error = $new_cust_pkg->replace($cust_pkg,
1057 options => { $cust_pkg->options },
1060 $dbh->rollback if $oldAutoCommit;
1065 my @cancelled_cust_pkg = $self->all_pkgs;
1066 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1067 my $error = $cust_pkg->delete;
1069 $dbh->rollback if $oldAutoCommit;
1074 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1075 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1077 my $error = $cust_main_invoice->delete;
1079 $dbh->rollback if $oldAutoCommit;
1084 my $error = $self->SUPER::delete;
1086 $dbh->rollback if $oldAutoCommit;
1090 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1095 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ]
1097 Replaces the OLD_RECORD with this one in the database. If there is an error,
1098 returns the error, otherwise returns false.
1100 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1101 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1102 expected and rollback the entire transaction; it is not necessary to call
1103 check_invoicing_list first. Here's an example:
1105 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1112 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1114 : $self->replace_old;
1118 warn "$me replace called\n"
1121 my $curuser = $FS::CurrentUser::CurrentUser;
1122 if ( $self->payby eq 'COMP'
1123 && $self->payby ne $old->payby
1124 && ! $curuser->access_right('Complimentary customer')
1127 return "You are not permitted to create complimentary accounts.";
1130 local($ignore_expired_card) = 1
1131 if $old->payby =~ /^(CARD|DCRD)$/
1132 && $self->payby =~ /^(CARD|DCRD)$/
1133 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1135 local $SIG{HUP} = 'IGNORE';
1136 local $SIG{INT} = 'IGNORE';
1137 local $SIG{QUIT} = 'IGNORE';
1138 local $SIG{TERM} = 'IGNORE';
1139 local $SIG{TSTP} = 'IGNORE';
1140 local $SIG{PIPE} = 'IGNORE';
1142 my $oldAutoCommit = $FS::UID::AutoCommit;
1143 local $FS::UID::AutoCommit = 0;
1146 my $error = $self->SUPER::replace($old);
1149 $dbh->rollback if $oldAutoCommit;
1153 if ( @param ) { # INVOICING_LIST_ARYREF
1154 my $invoicing_list = shift @param;
1155 $error = $self->check_invoicing_list( $invoicing_list );
1157 $dbh->rollback if $oldAutoCommit;
1160 $self->invoicing_list( $invoicing_list );
1163 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1164 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1165 # card/check/lec info has changed, want to retry realtime_ invoice events
1166 my $error = $self->retry_realtime;
1168 $dbh->rollback if $oldAutoCommit;
1173 unless ( $import || $skip_fuzzyfiles ) {
1174 $error = $self->queue_fuzzyfiles_update;
1176 $dbh->rollback if $oldAutoCommit;
1177 return "updating fuzzy search cache: $error";
1181 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1186 =item queue_fuzzyfiles_update
1188 Used by insert & replace to update the fuzzy search cache
1192 sub queue_fuzzyfiles_update {
1195 local $SIG{HUP} = 'IGNORE';
1196 local $SIG{INT} = 'IGNORE';
1197 local $SIG{QUIT} = 'IGNORE';
1198 local $SIG{TERM} = 'IGNORE';
1199 local $SIG{TSTP} = 'IGNORE';
1200 local $SIG{PIPE} = 'IGNORE';
1202 my $oldAutoCommit = $FS::UID::AutoCommit;
1203 local $FS::UID::AutoCommit = 0;
1206 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1207 my $error = $queue->insert( map $self->getfield($_),
1208 qw(first last company)
1211 $dbh->rollback if $oldAutoCommit;
1212 return "queueing job (transaction rolled back): $error";
1215 if ( $self->ship_last ) {
1216 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1217 $error = $queue->insert( map $self->getfield("ship_$_"),
1218 qw(first last company)
1221 $dbh->rollback if $oldAutoCommit;
1222 return "queueing job (transaction rolled back): $error";
1226 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1233 Checks all fields to make sure this is a valid customer record. If there is
1234 an error, returns the error, otherwise returns false. Called by the insert
1235 and replace methods.
1242 warn "$me check BEFORE: \n". $self->_dump
1246 $self->ut_numbern('custnum')
1247 || $self->ut_number('agentnum')
1248 || $self->ut_textn('agent_custid')
1249 || $self->ut_number('refnum')
1250 || $self->ut_textn('custbatch')
1251 || $self->ut_name('last')
1252 || $self->ut_name('first')
1253 || $self->ut_snumbern('birthdate')
1254 || $self->ut_snumbern('signupdate')
1255 || $self->ut_textn('company')
1256 || $self->ut_text('address1')
1257 || $self->ut_textn('address2')
1258 || $self->ut_text('city')
1259 || $self->ut_textn('county')
1260 || $self->ut_textn('state')
1261 || $self->ut_country('country')
1262 || $self->ut_anything('comments')
1263 || $self->ut_numbern('referral_custnum')
1264 || $self->ut_textn('stateid')
1265 || $self->ut_textn('stateid_state')
1266 || $self->ut_textn('invoice_terms')
1267 || $self->ut_alphan('geocode')
1270 #barf. need message catalogs. i18n. etc.
1271 $error .= "Please select an advertising source."
1272 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1273 return $error if $error;
1275 return "Unknown agent"
1276 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1278 return "Unknown refnum"
1279 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1281 return "Unknown referring custnum: ". $self->referral_custnum
1282 unless ! $self->referral_custnum
1283 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1285 if ( $self->ss eq '' ) {
1290 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1291 or return "Illegal social security number: ". $self->ss;
1292 $self->ss("$1-$2-$3");
1296 # bad idea to disable, causes billing to fail because of no tax rates later
1297 # unless ( $import ) {
1298 unless ( qsearch('cust_main_county', {
1299 'country' => $self->country,
1302 return "Unknown state/county/country: ".
1303 $self->state. "/". $self->county. "/". $self->country
1304 unless qsearch('cust_main_county',{
1305 'state' => $self->state,
1306 'county' => $self->county,
1307 'country' => $self->country,
1313 $self->ut_phonen('daytime', $self->country)
1314 || $self->ut_phonen('night', $self->country)
1315 || $self->ut_phonen('fax', $self->country)
1316 || $self->ut_zip('zip', $self->country)
1318 return $error if $error;
1320 if ( $conf->exists('cust_main-require_phone')
1321 && ! length($self->daytime) && ! length($self->night)
1324 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1326 : FS::Msgcat::_gettext('daytime');
1327 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1329 : FS::Msgcat::_gettext('night');
1331 return "$daytime_label or $night_label is required"
1335 if ( $self->has_ship_address
1336 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1337 $self->addr_fields )
1341 $self->ut_name('ship_last')
1342 || $self->ut_name('ship_first')
1343 || $self->ut_textn('ship_company')
1344 || $self->ut_text('ship_address1')
1345 || $self->ut_textn('ship_address2')
1346 || $self->ut_text('ship_city')
1347 || $self->ut_textn('ship_county')
1348 || $self->ut_textn('ship_state')
1349 || $self->ut_country('ship_country')
1351 return $error if $error;
1353 #false laziness with above
1354 unless ( qsearchs('cust_main_county', {
1355 'country' => $self->ship_country,
1358 return "Unknown ship_state/ship_county/ship_country: ".
1359 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1360 unless qsearch('cust_main_county',{
1361 'state' => $self->ship_state,
1362 'county' => $self->ship_county,
1363 'country' => $self->ship_country,
1369 $self->ut_phonen('ship_daytime', $self->ship_country)
1370 || $self->ut_phonen('ship_night', $self->ship_country)
1371 || $self->ut_phonen('ship_fax', $self->ship_country)
1372 || $self->ut_zip('ship_zip', $self->ship_country)
1374 return $error if $error;
1376 return "Unit # is required."
1377 if $self->ship_address2 =~ /^\s*$/
1378 && $conf->exists('cust_main-require_address2');
1380 } else { # ship_ info eq billing info, so don't store dup info in database
1382 $self->setfield("ship_$_", '')
1383 foreach $self->addr_fields;
1385 return "Unit # is required."
1386 if $self->address2 =~ /^\s*$/
1387 && $conf->exists('cust_main-require_address2');
1391 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1392 # or return "Illegal payby: ". $self->payby;
1394 FS::payby->can_payby($self->table, $self->payby)
1395 or return "Illegal payby: ". $self->payby;
1397 $error = $self->ut_numbern('paystart_month')
1398 || $self->ut_numbern('paystart_year')
1399 || $self->ut_numbern('payissue')
1400 || $self->ut_textn('paytype')
1402 return $error if $error;
1404 if ( $self->payip eq '' ) {
1407 $error = $self->ut_ip('payip');
1408 return $error if $error;
1411 # If it is encrypted and the private key is not availaible then we can't
1412 # check the credit card.
1414 my $check_payinfo = 1;
1416 if ($self->is_encrypted($self->payinfo)) {
1420 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1422 my $payinfo = $self->payinfo;
1423 $payinfo =~ s/\D//g;
1424 $payinfo =~ /^(\d{13,16})$/
1425 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1427 $self->payinfo($payinfo);
1429 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1431 return gettext('unknown_card_type')
1432 if cardtype($self->payinfo) eq "Unknown";
1434 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1436 return 'Banned credit card: banned on '.
1437 time2str('%a %h %o at %r', $ban->_date).
1438 ' by '. $ban->otaker.
1439 ' (ban# '. $ban->bannum. ')';
1442 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1443 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1444 $self->paycvv =~ /^(\d{4})$/
1445 or return "CVV2 (CID) for American Express cards is four digits.";
1448 $self->paycvv =~ /^(\d{3})$/
1449 or return "CVV2 (CVC2/CID) is three digits.";
1456 my $cardtype = cardtype($payinfo);
1457 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1459 return "Start date or issue number is required for $cardtype cards"
1460 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1462 return "Start month must be between 1 and 12"
1463 if $self->paystart_month
1464 and $self->paystart_month < 1 || $self->paystart_month > 12;
1466 return "Start year must be 1990 or later"
1467 if $self->paystart_year
1468 and $self->paystart_year < 1990;
1470 return "Issue number must be beween 1 and 99"
1472 and $self->payissue < 1 || $self->payissue > 99;
1475 $self->paystart_month('');
1476 $self->paystart_year('');
1477 $self->payissue('');
1480 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1482 my $payinfo = $self->payinfo;
1483 $payinfo =~ s/[^\d\@]//g;
1484 if ( $conf->exists('echeck-nonus') ) {
1485 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1486 $payinfo = "$1\@$2";
1488 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1489 $payinfo = "$1\@$2";
1491 $self->payinfo($payinfo);
1494 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1496 return 'Banned ACH account: banned on '.
1497 time2str('%a %h %o at %r', $ban->_date).
1498 ' by '. $ban->otaker.
1499 ' (ban# '. $ban->bannum. ')';
1502 } elsif ( $self->payby eq 'LECB' ) {
1504 my $payinfo = $self->payinfo;
1505 $payinfo =~ s/\D//g;
1506 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1508 $self->payinfo($payinfo);
1511 } elsif ( $self->payby eq 'BILL' ) {
1513 $error = $self->ut_textn('payinfo');
1514 return "Illegal P.O. number: ". $self->payinfo if $error;
1517 } elsif ( $self->payby eq 'COMP' ) {
1519 my $curuser = $FS::CurrentUser::CurrentUser;
1520 if ( ! $self->custnum
1521 && ! $curuser->access_right('Complimentary customer')
1524 return "You are not permitted to create complimentary accounts."
1527 $error = $self->ut_textn('payinfo');
1528 return "Illegal comp account issuer: ". $self->payinfo if $error;
1531 } elsif ( $self->payby eq 'PREPAY' ) {
1533 my $payinfo = $self->payinfo;
1534 $payinfo =~ s/\W//g; #anything else would just confuse things
1535 $self->payinfo($payinfo);
1536 $error = $self->ut_alpha('payinfo');
1537 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1538 return "Unknown prepayment identifier"
1539 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1544 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1545 return "Expiration date required"
1546 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1550 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1551 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1552 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1553 ( $m, $y ) = ( $3, "20$2" );
1555 return "Illegal expiration date: ". $self->paydate;
1557 $self->paydate("$y-$m-01");
1558 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1559 return gettext('expired_card')
1561 && !$ignore_expired_card
1562 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1565 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1566 ( ! $conf->exists('require_cardname')
1567 || $self->payby !~ /^(CARD|DCRD)$/ )
1569 $self->payname( $self->first. " ". $self->getfield('last') );
1571 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1572 or return gettext('illegal_name'). " payname: ". $self->payname;
1576 foreach my $flag (qw( tax spool_cdr squelch_cdr )) {
1577 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1581 $self->otaker(getotaker) unless $self->otaker;
1583 warn "$me check AFTER: \n". $self->_dump
1586 $self->SUPER::check;
1591 Returns a list of fields which have ship_ duplicates.
1596 qw( last first company
1597 address1 address2 city county state zip country
1602 =item has_ship_address
1604 Returns true if this customer record has a separate shipping address.
1608 sub has_ship_address {
1610 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1615 Returns all packages (see L<FS::cust_pkg>) for this customer.
1622 return $self->num_pkgs unless wantarray;
1625 if ( $self->{'_pkgnum'} ) {
1626 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1628 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1631 sort sort_packages @cust_pkg;
1636 Synonym for B<all_pkgs>.
1641 shift->all_pkgs(@_);
1644 =item ncancelled_pkgs
1646 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1650 sub ncancelled_pkgs {
1653 return $self->num_ncancelled_pkgs unless wantarray;
1656 if ( $self->{'_pkgnum'} ) {
1658 warn "$me ncancelled_pkgs: returning cached objects"
1661 @cust_pkg = grep { ! $_->getfield('cancel') }
1662 values %{ $self->{'_pkgnum'}->cache };
1666 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1667 $self->custnum. "\n"
1671 qsearch( 'cust_pkg', {
1672 'custnum' => $self->custnum,
1676 qsearch( 'cust_pkg', {
1677 'custnum' => $self->custnum,
1682 sort sort_packages @cust_pkg;
1686 # This should be generalized to use config options to determine order.
1688 if ( $a->get('cancel') and $b->get('cancel') ) {
1689 $a->pkgnum <=> $b->pkgnum;
1690 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1691 return -1 if $b->get('cancel');
1692 return 1 if $a->get('cancel');
1695 $a->pkgnum <=> $b->pkgnum;
1699 =item suspended_pkgs
1701 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1705 sub suspended_pkgs {
1707 grep { $_->susp } $self->ncancelled_pkgs;
1710 =item unflagged_suspended_pkgs
1712 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1713 customer (thouse packages without the `manual_flag' set).
1717 sub unflagged_suspended_pkgs {
1719 return $self->suspended_pkgs
1720 unless dbdef->table('cust_pkg')->column('manual_flag');
1721 grep { ! $_->manual_flag } $self->suspended_pkgs;
1724 =item unsuspended_pkgs
1726 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1731 sub unsuspended_pkgs {
1733 grep { ! $_->susp } $self->ncancelled_pkgs;
1736 =item num_cancelled_pkgs
1738 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1743 sub num_cancelled_pkgs {
1744 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1747 sub num_ncancelled_pkgs {
1748 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1752 my( $self ) = shift;
1753 my $sql = scalar(@_) ? shift : '';
1754 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1755 my $sth = dbh->prepare(
1756 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1757 ) or die dbh->errstr;
1758 $sth->execute($self->custnum) or die $sth->errstr;
1759 $sth->fetchrow_arrayref->[0];
1764 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1765 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1766 on success or a list of errors.
1772 grep { $_->unsuspend } $self->suspended_pkgs;
1777 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1779 Returns a list: an empty list on success or a list of errors.
1785 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1788 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1790 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1791 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1792 of a list of pkgparts; the hashref has the following keys:
1796 =item pkgparts - listref of pkgparts
1798 =item (other options are passed to the suspend method)
1803 Returns a list: an empty list on success or a list of errors.
1807 sub suspend_if_pkgpart {
1809 my (@pkgparts, %opt);
1810 if (ref($_[0]) eq 'HASH'){
1811 @pkgparts = @{$_[0]{pkgparts}};
1816 grep { $_->suspend(%opt) }
1817 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1818 $self->unsuspended_pkgs;
1821 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1823 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1824 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1825 instead of a list of pkgparts; the hashref has the following keys:
1829 =item pkgparts - listref of pkgparts
1831 =item (other options are passed to the suspend method)
1835 Returns a list: an empty list on success or a list of errors.
1839 sub suspend_unless_pkgpart {
1841 my (@pkgparts, %opt);
1842 if (ref($_[0]) eq 'HASH'){
1843 @pkgparts = @{$_[0]{pkgparts}};
1848 grep { $_->suspend(%opt) }
1849 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1850 $self->unsuspended_pkgs;
1853 =item cancel [ OPTION => VALUE ... ]
1855 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1857 Available options are:
1861 =item quiet - can be set true to supress email cancellation notices.
1863 =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.
1865 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1869 Always returns a list: an empty list on success or a list of errors.
1874 my( $self, %opt ) = @_;
1876 warn "$me cancel called on customer ". $self->custnum. " with options ".
1877 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1880 return ( 'access denied' )
1881 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1883 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1885 #should try decryption (we might have the private key)
1886 # and if not maybe queue a job for the server that does?
1887 return ( "Can't (yet) ban encrypted credit cards" )
1888 if $self->is_encrypted($self->payinfo);
1890 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1891 my $error = $ban->insert;
1892 return ( $error ) if $error;
1896 my @pkgs = $self->ncancelled_pkgs;
1898 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1899 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1902 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1905 sub _banned_pay_hashref {
1916 'payby' => $payby2ban{$self->payby},
1917 'payinfo' => md5_base64($self->payinfo),
1918 #don't ever *search* on reason! #'reason' =>
1924 Returns all notes (see L<FS::cust_main_note>) for this customer.
1931 qsearch( 'cust_main_note',
1932 { 'custnum' => $self->custnum },
1934 'ORDER BY _DATE DESC'
1940 Returns the agent (see L<FS::agent>) for this customer.
1946 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1949 =item bill_and_collect
1951 Cancels and suspends any packages due, generates bills, applies payments and
1954 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1956 Options are passed as name-value pairs. Currently available options are:
1962 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:
1966 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1970 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.
1974 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1978 If set true, re-charges setup fees.
1982 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)
1988 sub bill_and_collect {
1989 my( $self, %options ) = @_;
1995 #$options{actual_time} not $options{time} because freeside-daily -d is for
1996 #pre-printing invoices
1997 my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
1998 $self->ncancelled_pkgs;
2000 foreach my $cust_pkg ( @cancel_pkgs ) {
2001 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2002 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2003 'reason_otaker' => $cpr->otaker
2007 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
2008 " for custnum ". $self->custnum. ": $error"
2016 #$options{actual_time} not $options{time} because freeside-daily -d is for
2017 #pre-printing invoices
2020 && ( ( $_->part_pkg->is_prepaid
2022 && $_->bill < $options{actual_time}
2025 && $_->adjourn <= $options{actual_time}
2029 $self->ncancelled_pkgs;
2031 foreach my $cust_pkg ( @susp_pkgs ) {
2032 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2033 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2034 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2035 'reason_otaker' => $cpr->otaker
2040 warn "Error suspending package ". $cust_pkg->pkgnum.
2041 " for custnum ". $self->custnum. ": $error"
2049 my $error = $self->bill( %options );
2050 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
2052 $self->apply_payments_and_credits;
2054 $error = $self->collect( %options );
2055 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2061 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2062 conjunction with the collect method by calling B<bill_and_collect>.
2064 If there is an error, returns the error, otherwise returns false.
2066 Options are passed as name-value pairs. Currently available options are:
2072 If set true, re-charges setup fees.
2076 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:
2080 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2084 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2086 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2090 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.
2097 my( $self, %options ) = @_;
2098 return '' if $self->payby eq 'COMP';
2099 warn "$me bill customer ". $self->custnum. "\n"
2102 my $time = $options{'time'} || time;
2105 local $SIG{HUP} = 'IGNORE';
2106 local $SIG{INT} = 'IGNORE';
2107 local $SIG{QUIT} = 'IGNORE';
2108 local $SIG{TERM} = 'IGNORE';
2109 local $SIG{TSTP} = 'IGNORE';
2110 local $SIG{PIPE} = 'IGNORE';
2112 my $oldAutoCommit = $FS::UID::AutoCommit;
2113 local $FS::UID::AutoCommit = 0;
2116 $self->select_for_update; #mutex
2118 my @cust_bill_pkg = ();
2121 # find the packages which are due for billing, find out how much they are
2122 # & generate invoice database.
2125 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2129 my @precommit_hooks = ();
2131 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2132 foreach my $cust_pkg (@cust_pkgs) {
2134 #NO!! next if $cust_pkg->cancel;
2135 next if $cust_pkg->getfield('cancel');
2137 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2139 #? to avoid use of uninitialized value errors... ?
2140 $cust_pkg->setfield('bill', '')
2141 unless defined($cust_pkg->bill);
2143 #my $part_pkg = $cust_pkg->part_pkg;
2145 my $real_pkgpart = $cust_pkg->pkgpart;
2146 my %hash = $cust_pkg->hash;
2148 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2150 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2153 $self->_make_lines( 'part_pkg' => $part_pkg,
2154 'cust_pkg' => $cust_pkg,
2155 'precommit_hooks' => \@precommit_hooks,
2156 'line_items' => \@cust_bill_pkg,
2157 'setup' => \$total_setup,
2158 'recur' => \$total_recur,
2159 'tax_matrix' => \%taxlisthash,
2161 'options' => \%options,
2164 $dbh->rollback if $oldAutoCommit;
2168 } #foreach my $part_pkg
2170 } #foreach my $cust_pkg
2172 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2173 #but do commit any package date cycling that happened
2174 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2178 my $postal_pkg = $self->charge_postal_fee();
2179 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2180 $dbh->rollback if $oldAutoCommit;
2181 return "can't charge postal invoice fee for customer ".
2182 $self->custnum. ": $postal_pkg";
2185 ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2186 !$conf->exists('postal_invoice-recurring_only')
2190 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2192 $self->_make_lines( 'part_pkg' => $part_pkg,
2193 'cust_pkg' => $postal_pkg,
2194 'precommit_hooks' => \@precommit_hooks,
2195 'line_items' => \@cust_bill_pkg,
2196 'setup' => \$total_setup,
2197 'recur' => \$total_recur,
2198 'tax_matrix' => \%taxlisthash,
2200 'options' => \%options,
2203 $dbh->rollback if $oldAutoCommit;
2209 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2210 foreach my $tax ( keys %taxlisthash ) {
2211 my $tax_object = shift @{ $taxlisthash{$tax} };
2212 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2213 my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2214 unless (ref($listref_or_error)) {
2215 $dbh->rollback if $oldAutoCommit;
2216 return $listref_or_error;
2218 unshift @{ $taxlisthash{$tax} }, $tax_object;
2220 warn "adding ". $listref_or_error->[1].
2221 " as ". $listref_or_error->[0]. "\n"
2223 $tax{ $tax } += $listref_or_error->[1];
2224 if ( $taxname{ $listref_or_error->[0] } ) {
2225 push @{ $taxname{ $listref_or_error->[0] } }, $tax;
2227 $taxname{ $listref_or_error->[0] } = [ $tax ];
2232 #some taxes are taxed
2235 warn "finding taxed taxes...\n" if $DEBUG > 2;
2236 foreach my $tax ( keys %taxlisthash ) {
2237 my $tax_object = shift @{ $taxlisthash{$tax} };
2238 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2240 next unless $tax_object->can('tax_on_tax');
2242 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2243 my $totname = ref( $tot ). ' '. $tot->taxnum;
2245 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2247 next unless exists( $taxlisthash{ $totname } ); # only increase
2249 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2250 if ( exists( $totlisthash{ $totname } ) ) {
2251 push @{ $totlisthash{ $totname } }, $tax{ $tax };
2253 $totlisthash{ $totname } = [ $tot, $tax{ $tax } ];
2258 warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2259 foreach my $tax ( keys %totlisthash ) {
2260 my $tax_object = shift @{ $totlisthash{$tax} };
2261 warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2263 my $listref_or_error = $tax_object->taxline( @{ $totlisthash{$tax} } );
2264 unless (ref($listref_or_error)) {
2265 $dbh->rollback if $oldAutoCommit;
2266 return $listref_or_error;
2269 warn "adding taxed tax amount ". $listref_or_error->[1].
2270 " as ". $tax_object->taxname. "\n"
2272 $tax{ $tax } += $listref_or_error->[1];
2275 #consolidate and create tax line items
2276 warn "consolidating and generating...\n" if $DEBUG > 2;
2277 foreach my $taxname ( keys %taxname ) {
2280 warn "adding $taxname\n" if $DEBUG > 1;
2281 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2282 $tax += $tax{$taxitem} unless $seen{$taxitem};
2283 $seen{$taxitem} = 1;
2284 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2288 $tax = sprintf('%.2f', $tax );
2289 $total_setup = sprintf('%.2f', $total_setup+$tax );
2291 push @cust_bill_pkg, new FS::cust_bill_pkg {
2297 'itemdesc' => $taxname,
2302 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2304 #create the new invoice
2305 my $cust_bill = new FS::cust_bill ( {
2306 'custnum' => $self->custnum,
2307 '_date' => ( $options{'invoice_time'} || $time ),
2308 'charged' => $charged,
2310 my $error = $cust_bill->insert;
2312 $dbh->rollback if $oldAutoCommit;
2313 return "can't create invoice for customer #". $self->custnum. ": $error";
2316 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2317 $cust_bill_pkg->invnum($cust_bill->invnum);
2318 my $error = $cust_bill_pkg->insert;
2320 $dbh->rollback if $oldAutoCommit;
2321 return "can't create invoice line item: $error";
2326 foreach my $hook ( @precommit_hooks ) {
2328 &{$hook}; #($self) ?
2331 $dbh->rollback if $oldAutoCommit;
2332 return "$@ running precommit hook $hook\n";
2336 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2342 my ($self, %params) = @_;
2344 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2345 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2346 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2347 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2348 my $total_setup = $params{setup} or die "no setup accumulator specified";
2349 my $total_recur = $params{recur} or die "no recur accumulator specified";
2350 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2351 my $time = $params{'time'} or die "no time specified";
2352 my (%options) = %{$params{options}}; #hmmm only for 'resetup'
2355 my $real_pkgpart = $cust_pkg->pkgpart;
2356 my %hash = $cust_pkg->hash;
2357 my $old_cust_pkg = new FS::cust_pkg \%hash;
2363 $cust_pkg->pkgpart($part_pkg->pkgpart);
2371 if ( ! $cust_pkg->setup &&
2373 ( $conf->exists('disable_setup_suspended_pkgs') &&
2374 ! $cust_pkg->getfield('susp')
2375 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2377 || $options{'resetup'}
2380 warn " bill setup\n" if $DEBUG > 1;
2383 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2384 return "$@ running calc_setup for $cust_pkg\n"
2387 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2389 $cust_pkg->setfield('setup', $time)
2390 unless $cust_pkg->setup;
2391 #do need it, but it won't get written to the db
2392 #|| $cust_pkg->pkgpart != $real_pkgpart;
2397 # bill recurring fee
2400 #XXX unit stuff here too
2404 if ( ! $cust_pkg->getfield('susp') and
2405 ( $part_pkg->getfield('freq') ne '0' &&
2406 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2408 || ( $part_pkg->plan eq 'voip_cdr'
2409 && $part_pkg->option('bill_every_call')
2413 # XXX should this be a package event? probably. events are called
2414 # at collection time at the moment, though...
2415 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2416 if $part_pkg->can('reset_usage');
2417 #don't want to reset usage just cause we want a line item??
2418 #&& $part_pkg->pkgpart == $real_pkgpart;
2420 warn " bill recur\n" if $DEBUG > 1;
2423 # XXX shared with $recur_prog
2424 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2426 #over two params! lets at least switch to a hashref for the rest...
2427 my $increment_next_bill = ( $part_pkg->freq ne '0'
2428 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
2430 my %param = ( 'precommit_hooks' => $precommit_hooks,
2431 'increment_next_bill' => $increment_next_bill,
2434 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2435 return "$@ running calc_recur for $cust_pkg\n"
2438 if ( $increment_next_bill ) {
2440 #change this bit to use Date::Manip? CAREFUL with timezones (see
2441 # mailing list archive)
2442 my ($sec,$min,$hour,$mday,$mon,$year) =
2443 (localtime($sdate) )[0,1,2,3,4,5];
2445 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2446 # only for figuring next bill date, nothing else, so, reset $sdate again
2448 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2449 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2450 $cust_pkg->last_bill($sdate);
2452 if ( $part_pkg->freq =~ /^\d+$/ ) {
2453 $mon += $part_pkg->freq;
2454 until ( $mon < 12 ) { $mon -= 12; $year++; }
2455 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2457 $mday += $weeks * 7;
2458 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2461 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2465 return "unparsable frequency: ". $part_pkg->freq;
2467 $cust_pkg->setfield('bill',
2468 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2474 warn "\$setup is undefined" unless defined($setup);
2475 warn "\$recur is undefined" unless defined($recur);
2476 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2479 # If there's line items, create em cust_bill_pkg records
2480 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2485 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2486 # hmm.. and if just the options are modified in some weird price plan?
2488 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2491 my $error = $cust_pkg->replace( $old_cust_pkg,
2492 'options' => { $cust_pkg->options },
2494 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2495 if $error; #just in case
2498 $setup = sprintf( "%.2f", $setup );
2499 $recur = sprintf( "%.2f", $recur );
2500 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2501 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2503 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2504 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2507 if ( $setup != 0 || $recur != 0 ) {
2509 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2512 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2514 warn " adding customer package invoice detail: $_\n"
2515 foreach @cust_pkg_detail;
2517 push @details, @cust_pkg_detail;
2519 my $cust_bill_pkg = new FS::cust_bill_pkg {
2520 'pkgnum' => $cust_pkg->pkgnum,
2522 'unitsetup' => $unitsetup,
2524 'unitrecur' => $unitrecur,
2525 'quantity' => $cust_pkg->quantity,
2526 'details' => \@details,
2529 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
2530 $cust_bill_pkg->sdate( $hash{last_bill} );
2531 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2532 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
2533 $cust_bill_pkg->sdate( $sdate );
2534 $cust_bill_pkg->edate( $cust_pkg->bill );
2537 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2538 unless $part_pkg->pkgpart == $real_pkgpart;
2540 $$total_setup += $setup;
2541 $$total_recur += $recur;
2548 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg);
2549 return $error if $error;
2551 push @$cust_bill_pkgs, $cust_bill_pkg;
2553 } #if $setup != 0 || $recur != 0
2563 my $part_pkg = shift;
2564 my $taxlisthash = shift;
2565 my $cust_bill_pkg = shift;
2566 my $cust_pkg = shift;
2568 my %cust_bill_pkg = ();
2572 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2577 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
2578 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
2579 push @classes, 'setup' if $cust_bill_pkg->setup;
2580 push @classes, 'recur' if $cust_bill_pkg->recur;
2582 if ( $conf->exists('enable_taxproducts')
2583 && (scalar($part_pkg->part_pkg_taxoverride) || $part_pkg->has_taxproduct)
2584 && ( $self->tax !~ /Y/i && $self->payby ne 'COMP' )
2588 foreach my $class (@classes) {
2589 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $prefix );
2590 return $err_or_ref unless ref($err_or_ref);
2591 $taxes{$class} = $err_or_ref;
2594 unless (exists $taxes{''}) {
2595 my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $prefix );
2596 return $err_or_ref unless ref($err_or_ref);
2597 $taxes{''} = $err_or_ref;
2600 } elsif ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
2602 my %taxhash = map { $_ => $self->get("$prefix$_") }
2603 qw( state county country );
2605 $taxhash{'taxclass'} = $part_pkg->taxclass;
2607 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2610 $taxhash{'taxclass'} = '';
2611 @taxes = qsearch( 'cust_main_county', \%taxhash );
2614 #one more try at a whole-country tax rate
2616 $taxhash{$_} = '' foreach qw( state county );
2617 @taxes = qsearch( 'cust_main_county', \%taxhash );
2620 $taxes{''} = [ @taxes ];
2621 $taxes{'setup'} = [ @taxes ];
2622 $taxes{'recur'} = [ @taxes ];
2623 $taxes{$_} = [ @taxes ] foreach (@classes);
2625 # maybe eliminate this entirely, along with all the 0% records
2628 "fatal: can't find tax rate for state/county/country/taxclass ".
2629 join('/', ( map $self->get("$prefix$_"),
2630 qw(state county country)
2632 $part_pkg->taxclass ). "\n";
2635 } #if $conf->exists('enable_taxproducts') ...
2638 if ( $conf->exists('separate_usage') ) {
2639 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
2640 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
2641 push @display, new FS::cust_bill_pkg_display { type => 'S' };
2642 push @display, new FS::cust_bill_pkg_display { type => 'R' };
2643 push @display, new FS::cust_bill_pkg_display { type => 'U',
2646 if ($section && $summary) {
2647 $display[2]->post_total('Y');
2648 push @display, new FS::cust_bill_pkg_display { type => 'U',
2653 $cust_bill_pkg->set('display', \@display);
2655 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
2656 foreach my $key (keys %tax_cust_bill_pkg) {
2657 my @taxes = @{ $taxes{$key} || [] };
2658 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
2660 foreach my $tax ( @taxes ) {
2661 my $taxname = ref( $tax ). ' '. $tax->taxnum;
2662 if ( exists( $taxlisthash->{ $taxname } ) ) {
2663 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
2665 $taxlisthash->{ $taxname } = [ $tax, $tax_cust_bill_pkg ];
2675 my $part_pkg = shift;
2680 my $geocode = $self->geocode('cch');
2682 my @taxclassnums = map { $_->taxclassnum }
2683 $part_pkg->part_pkg_taxoverride($class);
2685 unless (@taxclassnums) {
2686 @taxclassnums = map { $_->taxclassnum }
2687 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
2689 warn "Found taxclassnum values of ". join(',', @taxclassnums)
2694 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2696 @taxes = qsearch({ 'table' => 'tax_rate',
2697 'hashref' => { 'geocode' => $geocode, },
2698 'extra_sql' => $extra_sql,
2700 if scalar(@taxclassnums);
2702 # maybe eliminate this entirely, along with all the 0% records
2705 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2706 join('/', ( map $self->get("$prefix$_"),
2709 $part_pkg->taxproduct_description,
2710 $part_pkg->pkgpart ). "\n";
2713 warn "Found taxes ".
2714 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
2721 =item collect OPTIONS
2723 (Attempt to) collect money for this customer's outstanding invoices (see
2724 L<FS::cust_bill>). Usually used after the bill method.
2726 Actions are now triggered by billing events; see L<FS::part_event> and the
2727 billing events web interface. Old-style invoice events (see
2728 L<FS::part_bill_event>) have been deprecated.
2730 If there is an error, returns the error, otherwise returns false.
2732 Options are passed as name-value pairs.
2734 Currently available options are:
2740 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.
2744 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2748 set true to surpress email card/ACH decline notices.
2752 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2756 allows for one time override of normal customer billing method
2760 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2768 my( $self, %options ) = @_;
2769 my $invoice_time = $options{'invoice_time'} || time;
2772 local $SIG{HUP} = 'IGNORE';
2773 local $SIG{INT} = 'IGNORE';
2774 local $SIG{QUIT} = 'IGNORE';
2775 local $SIG{TERM} = 'IGNORE';
2776 local $SIG{TSTP} = 'IGNORE';
2777 local $SIG{PIPE} = 'IGNORE';
2779 my $oldAutoCommit = $FS::UID::AutoCommit;
2780 local $FS::UID::AutoCommit = 0;
2783 $self->select_for_update; #mutex
2786 my $balance = $self->balance;
2787 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2790 if ( exists($options{'retry_card'}) ) {
2791 carp 'retry_card option passed to collect is deprecated; use retry';
2792 $options{'retry'} ||= $options{'retry_card'};
2794 if ( exists($options{'retry'}) && $options{'retry'} ) {
2795 my $error = $self->retry_realtime;
2797 $dbh->rollback if $oldAutoCommit;
2802 # false laziness w/pay_batch::import_results
2804 my $due_cust_event = $self->due_cust_event(
2805 'debug' => ( $options{'debug'} || 0 ),
2806 'time' => $invoice_time,
2807 'check_freq' => $options{'check_freq'},
2809 unless( ref($due_cust_event) ) {
2810 $dbh->rollback if $oldAutoCommit;
2811 return $due_cust_event;
2814 foreach my $cust_event ( @$due_cust_event ) {
2818 #re-eval event conditions (a previous event could have changed things)
2819 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2820 #don't leave stray "new/locked" records around
2821 my $error = $cust_event->delete;
2823 #gah, even with transactions
2824 $dbh->commit if $oldAutoCommit; #well.
2831 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2832 warn " running cust_event ". $cust_event->eventnum. "\n"
2836 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2837 if ( my $error = $cust_event->do_event() ) {
2838 #XXX wtf is this? figure out a proper dealio with return value
2840 # gah, even with transactions.
2841 $dbh->commit if $oldAutoCommit; #well.
2848 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2853 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2855 Inserts database records for and returns an ordered listref of new events due
2856 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2857 events are due, an empty listref is returned. If there is an error, returns a
2858 scalar error message.
2860 To actually run the events, call each event's test_condition method, and if
2861 still true, call the event's do_event method.
2863 Options are passed as a hashref or as a list of name-value pairs. Available
2870 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.
2874 "Current time" for the events.
2878 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)
2882 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2886 Explicitly pass the objects to be tested (typically used with eventtable).
2892 sub due_cust_event {
2894 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2897 #my $DEBUG = $opt{'debug'}
2898 local($DEBUG) = $opt{'debug'}
2899 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2901 warn "$me due_cust_event called with options ".
2902 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2905 $opt{'time'} ||= time;
2907 local $SIG{HUP} = 'IGNORE';
2908 local $SIG{INT} = 'IGNORE';
2909 local $SIG{QUIT} = 'IGNORE';
2910 local $SIG{TERM} = 'IGNORE';
2911 local $SIG{TSTP} = 'IGNORE';
2912 local $SIG{PIPE} = 'IGNORE';
2914 my $oldAutoCommit = $FS::UID::AutoCommit;
2915 local $FS::UID::AutoCommit = 0;
2918 $self->select_for_update; #mutex
2921 # 1: find possible events (initial search)
2924 my @cust_event = ();
2926 my @eventtable = $opt{'eventtable'}
2927 ? ( $opt{'eventtable'} )
2928 : FS::part_event->eventtables_runorder;
2930 foreach my $eventtable ( @eventtable ) {
2933 if ( $opt{'objects'} ) {
2935 @objects = @{ $opt{'objects'} };
2939 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2940 @objects = ( $eventtable eq 'cust_main' )
2942 : ( $self->$eventtable() );
2946 my @e_cust_event = ();
2948 my $cross = "CROSS JOIN $eventtable";
2949 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2950 unless $eventtable eq 'cust_main';
2952 foreach my $object ( @objects ) {
2954 #this first search uses the condition_sql magic for optimization.
2955 #the more possible events we can eliminate in this step the better
2957 my $cross_where = '';
2958 my $pkey = $object->primary_key;
2959 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2961 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2963 FS::part_event_condition->where_conditions_sql( $eventtable,
2964 'time'=>$opt{'time'}
2966 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2968 $extra_sql = "AND $extra_sql" if $extra_sql;
2970 #here is the agent virtualization
2971 $extra_sql .= " AND ( part_event.agentnum IS NULL
2972 OR part_event.agentnum = ". $self->agentnum. ' )';
2974 $extra_sql .= " $order";
2976 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2977 if $opt{'debug'} > 2;
2978 my @part_event = qsearch( {
2979 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2980 'select' => 'part_event.*',
2981 'table' => 'part_event',
2982 'addl_from' => "$cross $join",
2983 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2984 'eventtable' => $eventtable,
2987 'extra_sql' => "AND $cross_where $extra_sql",
2991 my $pkey = $object->primary_key;
2992 warn " ". scalar(@part_event).
2993 " possible events found for $eventtable ". $object->$pkey(). "\n";
2996 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
3000 warn " ". scalar(@e_cust_event).
3001 " subtotal possible cust events found for $eventtable\n"
3004 push @cust_event, @e_cust_event;
3008 warn " ". scalar(@cust_event).
3009 " total possible cust events found in initial search\n"
3013 # 2: test conditions
3018 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
3019 'stats_hashref' => \%unsat ),
3022 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
3025 warn " invalid conditions not eliminated with condition_sql:\n".
3026 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
3033 unless( $opt{testonly} ) {
3034 foreach my $cust_event ( @cust_event ) {
3036 my $error = $cust_event->insert();
3038 $dbh->rollback if $oldAutoCommit;
3045 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3051 warn " returning events: ". Dumper(@cust_event). "\n"
3058 =item retry_realtime
3060 Schedules realtime / batch credit card / electronic check / LEC billing
3061 events for for retry. Useful if card information has changed or manual
3062 retry is desired. The 'collect' method must be called to actually retry
3065 Implementation details: For either this customer, or for each of this
3066 customer's open invoices, changes the status of the first "done" (with
3067 statustext error) realtime processing event to "failed".
3071 sub retry_realtime {
3074 local $SIG{HUP} = 'IGNORE';
3075 local $SIG{INT} = 'IGNORE';
3076 local $SIG{QUIT} = 'IGNORE';
3077 local $SIG{TERM} = 'IGNORE';
3078 local $SIG{TSTP} = 'IGNORE';
3079 local $SIG{PIPE} = 'IGNORE';
3081 my $oldAutoCommit = $FS::UID::AutoCommit;
3082 local $FS::UID::AutoCommit = 0;
3085 #a little false laziness w/due_cust_event (not too bad, really)
3087 my $join = FS::part_event_condition->join_conditions_sql;
3088 my $order = FS::part_event_condition->order_conditions_sql;
3091 . join ( ' OR ' , map {
3092 "( part_event.eventtable = " . dbh->quote($_)
3093 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3094 } FS::part_event->eventtables)
3097 #here is the agent virtualization
3098 my $agent_virt = " ( part_event.agentnum IS NULL
3099 OR part_event.agentnum = ". $self->agentnum. ' )';
3101 #XXX this shouldn't be hardcoded, actions should declare it...
3102 my @realtime_events = qw(
3103 cust_bill_realtime_card
3104 cust_bill_realtime_check
3105 cust_bill_realtime_lec
3109 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3114 my @cust_event = qsearchs({
3115 'table' => 'cust_event',
3116 'select' => 'cust_event.*',
3117 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3118 'hashref' => { 'status' => 'done' },
3119 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3120 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3123 my %seen_invnum = ();
3124 foreach my $cust_event (@cust_event) {
3126 #max one for the customer, one for each open invoice
3127 my $cust_X = $cust_event->cust_X;
3128 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3132 or $cust_event->part_event->eventtable eq 'cust_bill'
3135 my $error = $cust_event->retry;
3137 $dbh->rollback if $oldAutoCommit;
3138 return "error scheduling event for retry: $error";
3143 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3148 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3150 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3151 via a Business::OnlinePayment realtime gateway. See
3152 L<http://420.am/business-onlinepayment> for supported gateways.
3154 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3156 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3158 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3159 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3160 if set, will override the value from the customer record.
3162 I<description> is a free-text field passed to the gateway. It defaults to
3163 "Internet services".
3165 If an I<invnum> is specified, this payment (if successful) is applied to the
3166 specified invoice. If you don't specify an I<invnum> you might want to
3167 call the B<apply_payments> method.
3169 I<quiet> can be set true to surpress email decline notices.
3171 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3172 resulting paynum, if any.
3174 I<payunique> is a unique identifier for this payment.
3176 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3181 my( $self, $method, $amount, %options ) = @_;
3183 warn "$me realtime_bop: $method $amount\n";
3184 warn " $_ => $options{$_}\n" foreach keys %options;
3187 $options{'description'} ||= 'Internet services';
3189 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3191 eval "use Business::OnlinePayment";
3194 my $payinfo = exists($options{'payinfo'})
3195 ? $options{'payinfo'}
3198 my %method2payby = (
3205 # check for banned credit card/ACH
3208 my $ban = qsearchs('banned_pay', {
3209 'payby' => $method2payby{$method},
3210 'payinfo' => md5_base64($payinfo),
3212 return "Banned credit card" if $ban;
3219 if ( $options{'invnum'} ) {
3220 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3221 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3223 map { $_->part_pkg->taxclass }
3225 map { $_->cust_pkg }
3226 $cust_bill->cust_bill_pkg;
3227 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3228 #different taxclasses
3229 $taxclass = $taxclasses[0];
3233 #look for an agent gateway override first
3235 if ( $method eq 'CC' ) {
3236 $cardtype = cardtype($payinfo);
3237 } elsif ( $method eq 'ECHECK' ) {
3240 $cardtype = $method;
3244 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3245 cardtype => $cardtype,
3246 taxclass => $taxclass, } )
3247 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3249 taxclass => $taxclass, } )
3250 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3251 cardtype => $cardtype,
3253 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3255 taxclass => '', } );
3257 my $payment_gateway = '';
3258 my( $processor, $login, $password, $action, @bop_options );
3259 if ( $override ) { #use a payment gateway override
3261 $payment_gateway = $override->payment_gateway;
3263 $processor = $payment_gateway->gateway_module;
3264 $login = $payment_gateway->gateway_username;
3265 $password = $payment_gateway->gateway_password;
3266 $action = $payment_gateway->gateway_action;
3267 @bop_options = $payment_gateway->options;
3269 } else { #use the standard settings from the config
3271 ( $processor, $login, $password, $action, @bop_options ) =
3272 $self->default_payment_gateway($method);
3280 my $address = exists($options{'address1'})
3281 ? $options{'address1'}
3283 my $address2 = exists($options{'address2'})
3284 ? $options{'address2'}
3286 $address .= ", ". $address2 if length($address2);
3288 my $o_payname = exists($options{'payname'})
3289 ? $options{'payname'}
3291 my($payname, $payfirst, $paylast);
3292 if ( $o_payname && $method ne 'ECHECK' ) {
3293 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3294 or return "Illegal payname $payname";
3295 ($payfirst, $paylast) = ($1, $2);
3297 $payfirst = $self->getfield('first');
3298 $paylast = $self->getfield('last');
3299 $payname = "$payfirst $paylast";
3302 my @invoicing_list = $self->invoicing_list_emailonly;
3303 if ( $conf->exists('emailinvoiceautoalways')
3304 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3305 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3306 push @invoicing_list, $self->all_emails;
3309 my $email = ($conf->exists('business-onlinepayment-email-override'))
3310 ? $conf->config('business-onlinepayment-email-override')
3311 : $invoicing_list[0];
3315 my $payip = exists($options{'payip'})
3318 $content{customer_ip} = $payip
3321 $content{invoice_number} = $options{'invnum'}
3322 if exists($options{'invnum'}) && length($options{'invnum'});
3324 $content{email_customer} =
3325 ( $conf->exists('business-onlinepayment-email_customer')
3326 || $conf->exists('business-onlinepayment-email-override') );
3329 if ( $method eq 'CC' ) {
3331 $content{card_number} = $payinfo;
3332 $paydate = exists($options{'paydate'})
3333 ? $options{'paydate'}
3335 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3336 $content{expiration} = "$2/$1";
3338 my $paycvv = exists($options{'paycvv'})
3339 ? $options{'paycvv'}
3341 $content{cvv2} = $paycvv
3344 my $paystart_month = exists($options{'paystart_month'})
3345 ? $options{'paystart_month'}
3346 : $self->paystart_month;
3348 my $paystart_year = exists($options{'paystart_year'})
3349 ? $options{'paystart_year'}
3350 : $self->paystart_year;
3352 $content{card_start} = "$paystart_month/$paystart_year"
3353 if $paystart_month && $paystart_year;
3355 my $payissue = exists($options{'payissue'})
3356 ? $options{'payissue'}
3358 $content{issue_number} = $payissue if $payissue;
3360 $content{recurring_billing} = 'YES'
3361 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3363 'payinfo' => $payinfo,
3365 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3367 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3371 } elsif ( $method eq 'ECHECK' ) {
3372 ( $content{account_number}, $content{routing_code} ) =
3373 split('@', $payinfo);
3374 $content{bank_name} = $o_payname;
3375 $content{bank_state} = exists($options{'paystate'})
3376 ? $options{'paystate'}
3377 : $self->getfield('paystate');
3378 $content{account_type} = exists($options{'paytype'})
3379 ? uc($options{'paytype'}) || 'CHECKING'
3380 : uc($self->getfield('paytype')) || 'CHECKING';
3381 $content{account_name} = $payname;
3382 $content{customer_org} = $self->company ? 'B' : 'I';
3383 $content{state_id} = exists($options{'stateid'})
3384 ? $options{'stateid'}
3385 : $self->getfield('stateid');
3386 $content{state_id_state} = exists($options{'stateid_state'})
3387 ? $options{'stateid_state'}
3388 : $self->getfield('stateid_state');
3389 $content{customer_ssn} = exists($options{'ss'})
3392 } elsif ( $method eq 'LEC' ) {
3393 $content{phone} = $payinfo;
3397 # run transaction(s)
3400 my $balance = exists( $options{'balance'} )
3401 ? $options{'balance'}
3404 $self->select_for_update; #mutex ... just until we get our pending record in
3406 #the checks here are intended to catch concurrent payments
3407 #double-form-submission prevention is taken care of in cust_pay_pending::check
3410 return "The customer's balance has changed; $method transaction aborted."
3411 if $self->balance < $balance;
3412 #&& $self->balance < $amount; #might as well anyway?
3414 #also check and make sure there aren't *other* pending payments for this cust
3416 my @pending = qsearch('cust_pay_pending', {
3417 'custnum' => $self->custnum,
3418 'status' => { op=>'!=', value=>'done' }
3420 return "A payment is already being processed for this customer (".
3421 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3422 "); $method transaction aborted."
3423 if scalar(@pending);
3425 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3427 my $cust_pay_pending = new FS::cust_pay_pending {
3428 'custnum' => $self->custnum,
3429 #'invnum' => $options{'invnum'},
3432 'payby' => $method2payby{$method},
3433 'payinfo' => $payinfo,
3434 'paydate' => $paydate,
3436 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3438 $cust_pay_pending->payunique( $options{payunique} )
3439 if defined($options{payunique}) && length($options{payunique});
3440 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3441 return $cpp_new_err if $cpp_new_err;
3443 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3445 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3446 $transaction->content(
3449 'password' => $password,
3450 'action' => $action1,
3451 'description' => $options{'description'},
3452 'amount' => $amount,
3453 #'invoice_number' => $options{'invnum'},
3454 'customer_id' => $self->custnum,
3455 'last_name' => $paylast,
3456 'first_name' => $payfirst,
3458 'address' => $address,
3459 'city' => ( exists($options{'city'})
3462 'state' => ( exists($options{'state'})
3465 'zip' => ( exists($options{'zip'})
3468 'country' => ( exists($options{'country'})
3469 ? $options{'country'}
3471 'referer' => 'http://cleanwhisker.420.am/',
3473 'phone' => $self->daytime || $self->night,
3477 $cust_pay_pending->status('pending');
3478 my $cpp_pending_err = $cust_pay_pending->replace;
3479 return $cpp_pending_err if $cpp_pending_err;
3482 my $BOP_TESTING = 0;
3483 my $BOP_TESTING_SUCCESS = 1;
3485 unless ( $BOP_TESTING ) {
3486 $transaction->submit();
3488 if ( $BOP_TESTING_SUCCESS ) {
3489 $transaction->is_success(1);
3490 $transaction->authorization('fake auth');
3492 $transaction->is_success(0);
3493 $transaction->error_message('fake failure');
3497 if ( $transaction->is_success() && $action2 ) {
3499 $cust_pay_pending->status('authorized');
3500 my $cpp_authorized_err = $cust_pay_pending->replace;
3501 return $cpp_authorized_err if $cpp_authorized_err;
3503 my $auth = $transaction->authorization;
3504 my $ordernum = $transaction->can('order_number')
3505 ? $transaction->order_number
3509 new Business::OnlinePayment( $processor, @bop_options );
3516 password => $password,
3517 order_number => $ordernum,
3519 authorization => $auth,
3520 description => $options{'description'},
3523 foreach my $field (qw( authorization_source_code returned_ACI
3524 transaction_identifier validation_code
3525 transaction_sequence_num local_transaction_date
3526 local_transaction_time AVS_result_code )) {
3527 $capture{$field} = $transaction->$field() if $transaction->can($field);
3530 $capture->content( %capture );
3534 unless ( $capture->is_success ) {
3535 my $e = "Authorization successful but capture failed, custnum #".
3536 $self->custnum. ': '. $capture->result_code.
3537 ": ". $capture->error_message;
3544 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3545 my $cpp_captured_err = $cust_pay_pending->replace;
3546 return $cpp_captured_err if $cpp_captured_err;
3549 # remove paycvv after initial transaction
3552 #false laziness w/misc/process/payment.cgi - check both to make sure working
3554 if ( defined $self->dbdef_table->column('paycvv')
3555 && length($self->paycvv)
3556 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3558 my $error = $self->remove_cvv;
3560 warn "WARNING: error removing cvv: $error\n";
3568 if ( $transaction->is_success() ) {
3571 if ( $payment_gateway ) { # agent override
3572 $paybatch = $payment_gateway->gatewaynum. '-';
3575 $paybatch .= "$processor:". $transaction->authorization;
3577 $paybatch .= ':'. $transaction->order_number
3578 if $transaction->can('order_number')
3579 && length($transaction->order_number);
3581 my $cust_pay = new FS::cust_pay ( {
3582 'custnum' => $self->custnum,
3583 'invnum' => $options{'invnum'},
3586 'payby' => $method2payby{$method},
3587 'payinfo' => $payinfo,
3588 'paybatch' => $paybatch,
3589 'paydate' => $paydate,
3591 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3592 $cust_pay->payunique( $options{payunique} )
3593 if defined($options{payunique}) && length($options{payunique});
3595 my $oldAutoCommit = $FS::UID::AutoCommit;
3596 local $FS::UID::AutoCommit = 0;
3599 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3601 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3604 $cust_pay->invnum(''); #try again with no specific invnum
3605 my $error2 = $cust_pay->insert( $options{'manual'} ?
3606 ( 'manual' => 1 ) : ()
3609 # gah. but at least we have a record of the state we had to abort in
3610 # from cust_pay_pending now.
3611 my $e = "WARNING: $method captured but payment not recorded - ".
3612 "error inserting payment ($processor): $error2".
3613 " (previously tried insert with invnum #$options{'invnum'}" .
3614 ": $error ) - pending payment saved as paypendingnum ".
3615 $cust_pay_pending->paypendingnum. "\n";
3621 if ( $options{'paynum_ref'} ) {
3622 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3625 $cust_pay_pending->status('done');
3626 $cust_pay_pending->statustext('captured');
3627 my $cpp_done_err = $cust_pay_pending->replace;
3629 if ( $cpp_done_err ) {
3631 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3632 my $e = "WARNING: $method captured but payment not recorded - ".
3633 "error updating status for paypendingnum ".
3634 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3640 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3641 return ''; #no error
3647 my $perror = "$processor error: ". $transaction->error_message;
3649 unless ( $transaction->error_message ) {
3652 if ( $transaction->can('response_page') ) {
3654 'page' => ( $transaction->can('response_page')
3655 ? $transaction->response_page
3658 'code' => ( $transaction->can('response_code')
3659 ? $transaction->response_code
3662 'headers' => ( $transaction->can('response_headers')
3663 ? $transaction->response_headers
3669 "No additional debugging information available for $processor";
3672 $perror .= "No error_message returned from $processor -- ".
3673 ( ref($t_response) ? Dumper($t_response) : $t_response );
3677 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3678 && $conf->exists('emaildecline')
3679 && grep { $_ ne 'POST' } $self->invoicing_list
3680 && ! grep { $transaction->error_message =~ /$_/ }
3681 $conf->config('emaildecline-exclude')
3683 my @templ = $conf->config('declinetemplate');
3684 my $template = new Text::Template (
3686 SOURCE => [ map "$_\n", @templ ],
3687 ) or return "($perror) can't create template: $Text::Template::ERROR";
3688 $template->compile()
3689 or return "($perror) can't compile template: $Text::Template::ERROR";
3691 my $templ_hash = { error => $transaction->error_message };
3693 my $error = send_email(
3694 'from' => $conf->config('invoice_from'),
3695 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3696 'subject' => 'Your payment could not be processed',
3697 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3700 $perror .= " (also received error sending decline notification: $error)"
3705 $cust_pay_pending->status('done');
3706 $cust_pay_pending->statustext("declined: $perror");
3707 my $cpp_done_err = $cust_pay_pending->replace;
3708 if ( $cpp_done_err ) {
3709 my $e = "WARNING: $method declined but pending payment not resolved - ".
3710 "error updating status for paypendingnum ".
3711 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3713 $perror = "$e ($perror)";
3726 my( $self, $method, $amount, %options ) = @_;
3728 if ( $options{'fake_failure'} ) {
3729 return "Error: No error; test failure requested with fake_failure";
3732 my %method2payby = (
3739 #if ( $payment_gateway ) { # agent override
3740 # $paybatch = $payment_gateway->gatewaynum. '-';
3743 #$paybatch .= "$processor:". $transaction->authorization;
3745 #$paybatch .= ':'. $transaction->order_number
3746 # if $transaction->can('order_number')
3747 # && length($transaction->order_number);
3749 my $paybatch = 'FakeProcessor:54:32';
3751 my $cust_pay = new FS::cust_pay ( {
3752 'custnum' => $self->custnum,
3753 'invnum' => $options{'invnum'},
3756 'payby' => $method2payby{$method},
3757 #'payinfo' => $payinfo,
3758 'payinfo' => '4111111111111111',
3759 'paybatch' => $paybatch,
3760 #'paydate' => $paydate,
3761 'paydate' => '2012-05-01',
3763 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3765 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3768 $cust_pay->invnum(''); #try again with no specific invnum
3769 my $error2 = $cust_pay->insert( $options{'manual'} ?
3770 ( 'manual' => 1 ) : ()
3773 # gah, even with transactions.
3774 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3775 "error inserting (fake!) payment: $error2".
3776 " (previously tried insert with invnum #$options{'invnum'}" .
3783 if ( $options{'paynum_ref'} ) {
3784 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3787 return ''; #no error
3791 =item default_payment_gateway
3795 sub default_payment_gateway {
3796 my( $self, $method ) = @_;
3798 die "Real-time processing not enabled\n"
3799 unless $conf->exists('business-onlinepayment');
3802 my $bop_config = 'business-onlinepayment';
3803 $bop_config .= '-ach'
3804 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3805 my ( $processor, $login, $password, $action, @bop_options ) =
3806 $conf->config($bop_config);
3807 $action ||= 'normal authorization';
3808 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3809 die "No real-time processor is enabled - ".
3810 "did you set the business-onlinepayment configuration value?\n"
3813 ( $processor, $login, $password, $action, @bop_options )
3818 Removes the I<paycvv> field from the database directly.
3820 If there is an error, returns the error, otherwise returns false.
3826 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3827 or return dbh->errstr;
3828 $sth->execute($self->custnum)
3829 or return $sth->errstr;
3834 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3836 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3837 via a Business::OnlinePayment realtime gateway. See
3838 L<http://420.am/business-onlinepayment> for supported gateways.
3840 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3842 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3844 Most gateways require a reference to an original payment transaction to refund,
3845 so you probably need to specify a I<paynum>.
3847 I<amount> defaults to the original amount of the payment if not specified.
3849 I<reason> specifies a reason for the refund.
3851 I<paydate> specifies the expiration date for a credit card overriding the
3852 value from the customer record or the payment record. Specified as yyyy-mm-dd
3854 Implementation note: If I<amount> is unspecified or equal to the amount of the
3855 orignal payment, first an attempt is made to "void" the transaction via
3856 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3857 the normal attempt is made to "refund" ("credit") the transaction via the
3858 gateway is attempted.
3860 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3861 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3862 #if set, will override the value from the customer record.
3864 #If an I<invnum> is specified, this payment (if successful) is applied to the
3865 #specified invoice. If you don't specify an I<invnum> you might want to
3866 #call the B<apply_payments> method.
3870 #some false laziness w/realtime_bop, not enough to make it worth merging
3871 #but some useful small subs should be pulled out
3872 sub realtime_refund_bop {
3873 my( $self, $method, %options ) = @_;
3875 warn "$me realtime_refund_bop: $method refund\n";
3876 warn " $_ => $options{$_}\n" foreach keys %options;
3879 eval "use Business::OnlinePayment";
3883 # look up the original payment and optionally a gateway for that payment
3887 my $amount = $options{'amount'};
3889 my( $processor, $login, $password, @bop_options ) ;
3890 my( $auth, $order_number ) = ( '', '', '' );
3892 if ( $options{'paynum'} ) {
3894 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3895 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3896 or return "Unknown paynum $options{'paynum'}";
3897 $amount ||= $cust_pay->paid;
3899 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3900 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3901 $cust_pay->paybatch;
3902 my $gatewaynum = '';
3903 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3905 if ( $gatewaynum ) { #gateway for the payment to be refunded
3907 my $payment_gateway =
3908 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3909 die "payment gateway $gatewaynum not found"
3910 unless $payment_gateway;
3912 $processor = $payment_gateway->gateway_module;
3913 $login = $payment_gateway->gateway_username;
3914 $password = $payment_gateway->gateway_password;
3915 @bop_options = $payment_gateway->options;
3917 } else { #try the default gateway
3919 my( $conf_processor, $unused_action );
3920 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3921 $self->default_payment_gateway($method);
3923 return "processor of payment $options{'paynum'} $processor does not".
3924 " match default processor $conf_processor"
3925 unless $processor eq $conf_processor;
3930 } else { # didn't specify a paynum, so look for agent gateway overrides
3931 # like a normal transaction
3934 if ( $method eq 'CC' ) {
3935 $cardtype = cardtype($self->payinfo);
3936 } elsif ( $method eq 'ECHECK' ) {
3939 $cardtype = $method;
3942 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3943 cardtype => $cardtype,
3945 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3947 taxclass => '', } );
3949 if ( $override ) { #use a payment gateway override
3951 my $payment_gateway = $override->payment_gateway;
3953 $processor = $payment_gateway->gateway_module;
3954 $login = $payment_gateway->gateway_username;
3955 $password = $payment_gateway->gateway_password;
3956 #$action = $payment_gateway->gateway_action;
3957 @bop_options = $payment_gateway->options;
3959 } else { #use the standard settings from the config
3962 ( $processor, $login, $password, $unused_action, @bop_options ) =
3963 $self->default_payment_gateway($method);
3968 return "neither amount nor paynum specified" unless $amount;
3973 'password' => $password,
3974 'order_number' => $order_number,
3975 'amount' => $amount,
3976 'referer' => 'http://cleanwhisker.420.am/',
3978 $content{authorization} = $auth
3979 if length($auth); #echeck/ACH transactions have an order # but no auth
3980 #(at least with authorize.net)
3982 my $disable_void_after;
3983 if ($conf->exists('disable_void_after')
3984 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3985 $disable_void_after = $1;
3988 #first try void if applicable
3989 if ( $cust_pay && $cust_pay->paid == $amount
3991 ( not defined($disable_void_after) )
3992 || ( time < ($cust_pay->_date + $disable_void_after ) )
3995 warn " attempting void\n" if $DEBUG > 1;
3996 my $void = new Business::OnlinePayment( $processor, @bop_options );
3997 $void->content( 'action' => 'void', %content );
3999 if ( $void->is_success ) {
4000 my $error = $cust_pay->void($options{'reason'});
4002 # gah, even with transactions.
4003 my $e = 'WARNING: Card/ACH voided but database not updated - '.
4004 "error voiding payment: $error";
4008 warn " void successful\n" if $DEBUG > 1;
4013 warn " void unsuccessful, trying refund\n"
4017 my $address = $self->address1;
4018 $address .= ", ". $self->address2 if $self->address2;
4020 my($payname, $payfirst, $paylast);
4021 if ( $self->payname && $method ne 'ECHECK' ) {
4022 $payname = $self->payname;
4023 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4024 or return "Illegal payname $payname";
4025 ($payfirst, $paylast) = ($1, $2);
4027 $payfirst = $self->getfield('first');
4028 $paylast = $self->getfield('last');
4029 $payname = "$payfirst $paylast";
4032 my @invoicing_list = $self->invoicing_list_emailonly;
4033 if ( $conf->exists('emailinvoiceautoalways')
4034 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4035 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4036 push @invoicing_list, $self->all_emails;
4039 my $email = ($conf->exists('business-onlinepayment-email-override'))
4040 ? $conf->config('business-onlinepayment-email-override')
4041 : $invoicing_list[0];
4043 my $payip = exists($options{'payip'})
4046 $content{customer_ip} = $payip
4050 if ( $method eq 'CC' ) {
4053 $content{card_number} = $payinfo = $cust_pay->payinfo;
4054 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
4055 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
4056 ($content{expiration} = "$2/$1"); # where available
4058 $content{card_number} = $payinfo = $self->payinfo;
4059 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
4060 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4061 $content{expiration} = "$2/$1";
4064 } elsif ( $method eq 'ECHECK' ) {
4067 $payinfo = $cust_pay->payinfo;
4069 $payinfo = $self->payinfo;
4071 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
4072 $content{bank_name} = $self->payname;
4073 $content{account_type} = 'CHECKING';
4074 $content{account_name} = $payname;
4075 $content{customer_org} = $self->company ? 'B' : 'I';
4076 $content{customer_ssn} = $self->ss;
4077 } elsif ( $method eq 'LEC' ) {
4078 $content{phone} = $payinfo = $self->payinfo;
4082 my $refund = new Business::OnlinePayment( $processor, @bop_options );
4083 my %sub_content = $refund->content(
4084 'action' => 'credit',
4085 'customer_id' => $self->custnum,
4086 'last_name' => $paylast,
4087 'first_name' => $payfirst,
4089 'address' => $address,
4090 'city' => $self->city,
4091 'state' => $self->state,
4092 'zip' => $self->zip,
4093 'country' => $self->country,
4095 'phone' => $self->daytime || $self->night,
4098 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
4102 return "$processor error: ". $refund->error_message
4103 unless $refund->is_success();
4105 my %method2payby = (
4111 my $paybatch = "$processor:". $refund->authorization;
4112 $paybatch .= ':'. $refund->order_number
4113 if $refund->can('order_number') && $refund->order_number;
4115 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4116 my @cust_bill_pay = $cust_pay->cust_bill_pay;
4117 last unless @cust_bill_pay;
4118 my $cust_bill_pay = pop @cust_bill_pay;
4119 my $error = $cust_bill_pay->delete;
4123 my $cust_refund = new FS::cust_refund ( {
4124 'custnum' => $self->custnum,
4125 'paynum' => $options{'paynum'},
4126 'refund' => $amount,
4128 'payby' => $method2payby{$method},
4129 'payinfo' => $payinfo,
4130 'paybatch' => $paybatch,
4131 'reason' => $options{'reason'} || 'card or ACH refund',
4133 my $error = $cust_refund->insert;
4135 $cust_refund->paynum(''); #try again with no specific paynum
4136 my $error2 = $cust_refund->insert;
4138 # gah, even with transactions.
4139 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4140 "error inserting refund ($processor): $error2".
4141 " (previously tried insert with paynum #$options{'paynum'}" .
4152 =item batch_card OPTION => VALUE...
4154 Adds a payment for this invoice to the pending credit card batch (see
4155 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4156 runs the payment using a realtime gateway.
4161 my ($self, %options) = @_;
4164 if (exists($options{amount})) {
4165 $amount = $options{amount};
4167 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4169 return '' unless $amount > 0;
4171 my $invnum = delete $options{invnum};
4172 my $payby = $options{invnum} || $self->payby; #dubious
4174 if ($options{'realtime'}) {
4175 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4181 my $oldAutoCommit = $FS::UID::AutoCommit;
4182 local $FS::UID::AutoCommit = 0;
4185 #this needs to handle mysql as well as Pg, like svc_acct.pm
4186 #(make it into a common function if folks need to do batching with mysql)
4187 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4188 or return "Cannot lock pay_batch: " . $dbh->errstr;
4192 'payby' => FS::payby->payby2payment($payby),
4195 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4197 unless ( $pay_batch ) {
4198 $pay_batch = new FS::pay_batch \%pay_batch;
4199 my $error = $pay_batch->insert;
4201 $dbh->rollback if $oldAutoCommit;
4202 die "error creating new batch: $error\n";
4206 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4207 'batchnum' => $pay_batch->batchnum,
4208 'custnum' => $self->custnum,
4211 foreach (qw( address1 address2 city state zip country payby payinfo paydate
4213 $options{$_} = '' unless exists($options{$_});
4216 my $cust_pay_batch = new FS::cust_pay_batch ( {
4217 'batchnum' => $pay_batch->batchnum,
4218 'invnum' => $invnum || 0, # is there a better value?
4219 # this field should be
4221 # cust_bill_pay_batch now
4222 'custnum' => $self->custnum,
4223 'last' => $self->getfield('last'),
4224 'first' => $self->getfield('first'),
4225 'address1' => $options{address1} || $self->address1,
4226 'address2' => $options{address2} || $self->address2,
4227 'city' => $options{city} || $self->city,
4228 'state' => $options{state} || $self->state,
4229 'zip' => $options{zip} || $self->zip,
4230 'country' => $options{country} || $self->country,
4231 'payby' => $options{payby} || $self->payby,
4232 'payinfo' => $options{payinfo} || $self->payinfo,
4233 'exp' => $options{paydate} || $self->paydate,
4234 'payname' => $options{payname} || $self->payname,
4235 'amount' => $amount, # consolidating
4238 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4239 if $old_cust_pay_batch;
4242 if ($old_cust_pay_batch) {
4243 $error = $cust_pay_batch->replace($old_cust_pay_batch)
4245 $error = $cust_pay_batch->insert;
4249 $dbh->rollback if $oldAutoCommit;
4253 my $unapplied = $self->total_unapplied_credits
4254 + $self->total_unapplied_payments
4255 + $self->in_transit_payments;
4256 foreach my $cust_bill ($self->open_cust_bill) {
4257 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4258 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4259 'invnum' => $cust_bill->invnum,
4260 'paybatchnum' => $cust_pay_batch->paybatchnum,
4261 'amount' => $cust_bill->owed,
4264 if ($unapplied >= $cust_bill_pay_batch->amount){
4265 $unapplied -= $cust_bill_pay_batch->amount;
4268 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4269 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4271 $error = $cust_bill_pay_batch->insert;
4273 $dbh->rollback if $oldAutoCommit;
4278 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4282 =item apply_payments_and_credits
4284 Applies unapplied payments and credits.
4286 In most cases, this new method should be used in place of sequential
4287 apply_payments and apply_credits methods.
4289 If there is an error, returns the error, otherwise returns false.
4293 sub apply_payments_and_credits {
4296 local $SIG{HUP} = 'IGNORE';
4297 local $SIG{INT} = 'IGNORE';
4298 local $SIG{QUIT} = 'IGNORE';
4299 local $SIG{TERM} = 'IGNORE';
4300 local $SIG{TSTP} = 'IGNORE';
4301 local $SIG{PIPE} = 'IGNORE';
4303 my $oldAutoCommit = $FS::UID::AutoCommit;
4304 local $FS::UID::AutoCommit = 0;
4307 $self->select_for_update; #mutex
4309 foreach my $cust_bill ( $self->open_cust_bill ) {
4310 my $error = $cust_bill->apply_payments_and_credits;
4312 $dbh->rollback if $oldAutoCommit;
4313 return "Error applying: $error";
4317 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4322 =item apply_credits OPTION => VALUE ...
4324 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4325 to outstanding invoice balances in chronological order (or reverse
4326 chronological order if the I<order> option is set to B<newest>) and returns the
4327 value of any remaining unapplied credits available for refund (see
4328 L<FS::cust_refund>).
4330 Dies if there is an error.
4338 local $SIG{HUP} = 'IGNORE';
4339 local $SIG{INT} = 'IGNORE';
4340 local $SIG{QUIT} = 'IGNORE';
4341 local $SIG{TERM} = 'IGNORE';
4342 local $SIG{TSTP} = 'IGNORE';
4343 local $SIG{PIPE} = 'IGNORE';
4345 my $oldAutoCommit = $FS::UID::AutoCommit;
4346 local $FS::UID::AutoCommit = 0;
4349 $self->select_for_update; #mutex
4351 unless ( $self->total_unapplied_credits ) {
4352 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4356 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4357 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4359 my @invoices = $self->open_cust_bill;
4360 @invoices = sort { $b->_date <=> $a->_date } @invoices
4361 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4364 foreach my $cust_bill ( @invoices ) {
4367 if ( !defined($credit) || $credit->credited == 0) {
4368 $credit = pop @credits or last;
4371 if ($cust_bill->owed >= $credit->credited) {
4372 $amount=$credit->credited;
4374 $amount=$cust_bill->owed;
4377 my $cust_credit_bill = new FS::cust_credit_bill ( {
4378 'crednum' => $credit->crednum,
4379 'invnum' => $cust_bill->invnum,
4380 'amount' => $amount,
4382 my $error = $cust_credit_bill->insert;
4384 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4388 redo if ($cust_bill->owed > 0);
4392 my $total_unapplied_credits = $self->total_unapplied_credits;
4394 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4396 return $total_unapplied_credits;
4399 =item apply_payments
4401 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4402 to outstanding invoice balances in chronological order.
4404 #and returns the value of any remaining unapplied payments.
4406 Dies if there is an error.
4410 sub apply_payments {
4413 local $SIG{HUP} = 'IGNORE';
4414 local $SIG{INT} = 'IGNORE';
4415 local $SIG{QUIT} = 'IGNORE';
4416 local $SIG{TERM} = 'IGNORE';
4417 local $SIG{TSTP} = 'IGNORE';
4418 local $SIG{PIPE} = 'IGNORE';
4420 my $oldAutoCommit = $FS::UID::AutoCommit;
4421 local $FS::UID::AutoCommit = 0;
4424 $self->select_for_update; #mutex
4428 my @payments = sort { $b->_date <=> $a->_date }
4429 grep { $_->unapplied > 0 }
4432 my @invoices = sort { $a->_date <=> $b->_date}
4433 grep { $_->owed > 0 }
4438 foreach my $cust_bill ( @invoices ) {
4441 if ( !defined($payment) || $payment->unapplied == 0 ) {
4442 $payment = pop @payments or last;
4445 if ( $cust_bill->owed >= $payment->unapplied ) {
4446 $amount = $payment->unapplied;
4448 $amount = $cust_bill->owed;
4451 my $cust_bill_pay = new FS::cust_bill_pay ( {
4452 'paynum' => $payment->paynum,
4453 'invnum' => $cust_bill->invnum,
4454 'amount' => $amount,
4456 my $error = $cust_bill_pay->insert;
4458 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4462 redo if ( $cust_bill->owed > 0);
4466 my $total_unapplied_payments = $self->total_unapplied_payments;
4468 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4470 return $total_unapplied_payments;
4475 Returns the total owed for this customer on all invoices
4476 (see L<FS::cust_bill/owed>).
4482 $self->total_owed_date(2145859200); #12/31/2037
4485 =item total_owed_date TIME
4487 Returns the total owed for this customer on all invoices with date earlier than
4488 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4489 see L<Time::Local> and L<Date::Parse> for conversion functions.
4493 sub total_owed_date {
4497 foreach my $cust_bill (
4498 grep { $_->_date <= $time }
4499 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4501 $total_bill += $cust_bill->owed;
4503 sprintf( "%.2f", $total_bill );
4508 Returns the total amount of all payments.
4515 $total += $_->paid foreach $self->cust_pay;
4516 sprintf( "%.2f", $total );
4519 =item total_unapplied_credits
4521 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4522 customer. See L<FS::cust_credit/credited>.
4524 =item total_credited
4526 Old name for total_unapplied_credits. Don't use.
4530 sub total_credited {
4531 #carp "total_credited deprecated, use total_unapplied_credits";
4532 shift->total_unapplied_credits(@_);
4535 sub total_unapplied_credits {
4537 my $total_credit = 0;
4538 $total_credit += $_->credited foreach $self->cust_credit;
4539 sprintf( "%.2f", $total_credit );
4542 =item total_unapplied_payments
4544 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4545 See L<FS::cust_pay/unapplied>.
4549 sub total_unapplied_payments {
4551 my $total_unapplied = 0;
4552 $total_unapplied += $_->unapplied foreach $self->cust_pay;
4553 sprintf( "%.2f", $total_unapplied );
4556 =item total_unapplied_refunds
4558 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4559 customer. See L<FS::cust_refund/unapplied>.
4563 sub total_unapplied_refunds {
4565 my $total_unapplied = 0;
4566 $total_unapplied += $_->unapplied foreach $self->cust_refund;
4567 sprintf( "%.2f", $total_unapplied );
4572 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4573 total_unapplied_credits minus total_unapplied_payments).
4581 + $self->total_unapplied_refunds
4582 - $self->total_unapplied_credits
4583 - $self->total_unapplied_payments
4587 =item balance_date TIME
4589 Returns the balance for this customer, only considering invoices with date
4590 earlier than TIME (total_owed_date minus total_credited minus
4591 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4592 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4601 $self->total_owed_date($time)
4602 + $self->total_unapplied_refunds
4603 - $self->total_unapplied_credits
4604 - $self->total_unapplied_payments
4608 =item in_transit_payments
4610 Returns the total of requests for payments for this customer pending in
4611 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4615 sub in_transit_payments {
4617 my $in_transit_payments = 0;
4618 foreach my $pay_batch ( qsearch('pay_batch', {
4621 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4622 'batchnum' => $pay_batch->batchnum,
4623 'custnum' => $self->custnum,
4625 $in_transit_payments += $cust_pay_batch->amount;
4628 sprintf( "%.2f", $in_transit_payments );
4631 =item paydate_monthyear
4633 Returns a two-element list consisting of the month and year of this customer's
4634 paydate (credit card expiration date for CARD customers)
4638 sub paydate_monthyear {
4640 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4642 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4649 =item invoicing_list [ ARRAYREF ]
4651 If an arguement is given, sets these email addresses as invoice recipients
4652 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4653 (except as warnings), so use check_invoicing_list first.
4655 Returns a list of email addresses (with svcnum entries expanded).
4657 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4658 check it without disturbing anything by passing nothing.
4660 This interface may change in the future.
4664 sub invoicing_list {
4665 my( $self, $arrayref ) = @_;
4668 my @cust_main_invoice;
4669 if ( $self->custnum ) {
4670 @cust_main_invoice =
4671 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4673 @cust_main_invoice = ();
4675 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4676 #warn $cust_main_invoice->destnum;
4677 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4678 #warn $cust_main_invoice->destnum;
4679 my $error = $cust_main_invoice->delete;
4680 warn $error if $error;
4683 if ( $self->custnum ) {
4684 @cust_main_invoice =
4685 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4687 @cust_main_invoice = ();
4689 my %seen = map { $_->address => 1 } @cust_main_invoice;
4690 foreach my $address ( @{$arrayref} ) {
4691 next if exists $seen{$address} && $seen{$address};
4692 $seen{$address} = 1;
4693 my $cust_main_invoice = new FS::cust_main_invoice ( {
4694 'custnum' => $self->custnum,
4697 my $error = $cust_main_invoice->insert;
4698 warn $error if $error;
4702 if ( $self->custnum ) {
4704 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4711 =item check_invoicing_list ARRAYREF
4713 Checks these arguements as valid input for the invoicing_list method. If there
4714 is an error, returns the error, otherwise returns false.
4718 sub check_invoicing_list {
4719 my( $self, $arrayref ) = @_;
4721 foreach my $address ( @$arrayref ) {
4723 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4724 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4727 my $cust_main_invoice = new FS::cust_main_invoice ( {
4728 'custnum' => $self->custnum,
4731 my $error = $self->custnum
4732 ? $cust_main_invoice->check
4733 : $cust_main_invoice->checkdest
4735 return $error if $error;
4739 return "Email address required"
4740 if $conf->exists('cust_main-require_invoicing_list_email')
4741 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4746 =item set_default_invoicing_list
4748 Sets the invoicing list to all accounts associated with this customer,
4749 overwriting any previous invoicing list.
4753 sub set_default_invoicing_list {
4755 $self->invoicing_list($self->all_emails);
4760 Returns the email addresses of all accounts provisioned for this customer.
4767 foreach my $cust_pkg ( $self->all_pkgs ) {
4768 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4770 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4771 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4773 $list{$_}=1 foreach map { $_->email } @svc_acct;
4778 =item invoicing_list_addpost
4780 Adds postal invoicing to this customer. If this customer is already configured
4781 to receive postal invoices, does nothing.
4785 sub invoicing_list_addpost {
4787 return if grep { $_ eq 'POST' } $self->invoicing_list;
4788 my @invoicing_list = $self->invoicing_list;
4789 push @invoicing_list, 'POST';
4790 $self->invoicing_list(\@invoicing_list);
4793 =item invoicing_list_emailonly
4795 Returns the list of email invoice recipients (invoicing_list without non-email
4796 destinations such as POST and FAX).
4800 sub invoicing_list_emailonly {
4802 warn "$me invoicing_list_emailonly called"
4804 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4807 =item invoicing_list_emailonly_scalar
4809 Returns the list of email invoice recipients (invoicing_list without non-email
4810 destinations such as POST and FAX) as a comma-separated scalar.
4814 sub invoicing_list_emailonly_scalar {
4816 warn "$me invoicing_list_emailonly_scalar called"
4818 join(', ', $self->invoicing_list_emailonly);
4821 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4823 Returns an array of customers referred by this customer (referral_custnum set
4824 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4825 customers referred by customers referred by this customer and so on, inclusive.
4826 The default behavior is DEPTH 1 (no recursion).
4830 sub referral_cust_main {
4832 my $depth = @_ ? shift : 1;
4833 my $exclude = @_ ? shift : {};
4836 map { $exclude->{$_->custnum}++; $_; }
4837 grep { ! $exclude->{ $_->custnum } }
4838 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4842 map { $_->referral_cust_main($depth-1, $exclude) }
4849 =item referral_cust_main_ncancelled
4851 Same as referral_cust_main, except only returns customers with uncancelled
4856 sub referral_cust_main_ncancelled {
4858 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4861 =item referral_cust_pkg [ DEPTH ]
4863 Like referral_cust_main, except returns a flat list of all unsuspended (and
4864 uncancelled) packages for each customer. The number of items in this list may
4865 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4869 sub referral_cust_pkg {
4871 my $depth = @_ ? shift : 1;
4873 map { $_->unsuspended_pkgs }
4874 grep { $_->unsuspended_pkgs }
4875 $self->referral_cust_main($depth);
4878 =item referring_cust_main
4880 Returns the single cust_main record for the customer who referred this customer
4881 (referral_custnum), or false.
4885 sub referring_cust_main {
4887 return '' unless $self->referral_custnum;
4888 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4891 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
4893 Applies a credit to this customer. If there is an error, returns the error,
4894 otherwise returns false.
4896 REASON can be a text string, an FS::reason object, or a scalar reference to
4897 a reasonnum. If a text string, it will be automatically inserted as a new
4898 reason, and a 'reason_type' option must be passed to indicate the
4899 FS::reason_type for the new reason.
4901 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
4903 Any other options are passed to FS::cust_credit::insert.
4908 my( $self, $amount, $reason, %options ) = @_;
4910 my $cust_credit = new FS::cust_credit {
4911 'custnum' => $self->custnum,
4912 'amount' => $amount,
4915 if ( ref($reason) ) {
4917 if ( ref($reason) eq 'SCALAR' ) {
4918 $cust_credit->reasonnum( $$reason );
4920 $cust_credit->reasonnum( $reason->reasonnum );
4924 $cust_credit->set('reason', $reason)
4927 $cust_credit->addlinfo( delete $options{'addlinfo'} )
4928 if exists($options{'addlinfo'});
4930 $cust_credit->insert(%options);
4934 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4936 Creates a one-time charge for this customer. If there is an error, returns
4937 the error, otherwise returns false.
4943 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4944 my ( $taxproduct, $override );
4945 if ( ref( $_[0] ) ) {
4946 $amount = $_[0]->{amount};
4947 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4948 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4949 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4950 : '$'. sprintf("%.2f",$amount);
4951 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4952 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4953 $additional = $_[0]->{additional};
4954 $taxproduct = $_[0]->{taxproductnum};
4955 $override = { '' => $_[0]->{tax_override} };
4959 $pkg = @_ ? shift : 'One-time charge';
4960 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4961 $taxclass = @_ ? shift : '';
4965 local $SIG{HUP} = 'IGNORE';
4966 local $SIG{INT} = 'IGNORE';
4967 local $SIG{QUIT} = 'IGNORE';
4968 local $SIG{TERM} = 'IGNORE';
4969 local $SIG{TSTP} = 'IGNORE';
4970 local $SIG{PIPE} = 'IGNORE';
4972 my $oldAutoCommit = $FS::UID::AutoCommit;
4973 local $FS::UID::AutoCommit = 0;
4976 my $part_pkg = new FS::part_pkg ( {
4978 'comment' => $comment,
4982 'classnum' => $classnum ? $classnum : '',
4983 'taxclass' => $taxclass,
4984 'taxproductnum' => $taxproduct,
4987 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4988 ( 0 .. @$additional - 1 )
4990 'additional_count' => scalar(@$additional),
4991 'setup_fee' => $amount,
4994 my $error = $part_pkg->insert( options => \%options,
4995 tax_overrides => $override,
4998 $dbh->rollback if $oldAutoCommit;
5002 my $pkgpart = $part_pkg->pkgpart;
5003 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
5004 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
5005 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
5006 $error = $type_pkgs->insert;
5008 $dbh->rollback if $oldAutoCommit;
5013 my $cust_pkg = new FS::cust_pkg ( {
5014 'custnum' => $self->custnum,
5015 'pkgpart' => $pkgpart,
5016 'quantity' => $quantity,
5019 $error = $cust_pkg->insert;
5021 $dbh->rollback if $oldAutoCommit;
5025 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5030 #=item charge_postal_fee
5032 #Applies a one time charge this customer. If there is an error,
5033 #returns the error, returns the cust_pkg charge object or false
5034 #if there was no charge.
5038 # This should be a customer event. For that to work requires that bill
5039 # also be a customer event.
5041 sub charge_postal_fee {
5044 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
5045 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
5047 my $cust_pkg = new FS::cust_pkg ( {
5048 'custnum' => $self->custnum,
5049 'pkgpart' => $pkgpart,
5053 my $error = $cust_pkg->insert;
5054 $error ? $error : $cust_pkg;
5059 Returns all the invoices (see L<FS::cust_bill>) for this customer.
5065 sort { $a->_date <=> $b->_date }
5066 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
5069 =item open_cust_bill
5071 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
5076 sub open_cust_bill {
5078 grep { $_->owed > 0 } $self->cust_bill;
5083 Returns all the credits (see L<FS::cust_credit>) for this customer.
5089 sort { $a->_date <=> $b->_date }
5090 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
5095 Returns all the payments (see L<FS::cust_pay>) for this customer.
5101 sort { $a->_date <=> $b->_date }
5102 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
5107 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
5113 sort { $a->_date <=> $b->_date }
5114 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
5117 =item cust_pay_batch
5119 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
5123 sub cust_pay_batch {
5125 sort { $a->_date <=> $b->_date }
5126 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
5131 Returns all the refunds (see L<FS::cust_refund>) for this customer.
5137 sort { $a->_date <=> $b->_date }
5138 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
5141 =item display_custnum
5143 Returns the displayed customer number for this customer: agent_custid if
5144 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
5148 sub display_custnum {
5150 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
5151 return $self->agent_custid;
5153 return $self->custnum;
5159 Returns a name string for this customer, either "Company (Last, First)" or
5166 my $name = $self->contact;
5167 $name = $self->company. " ($name)" if $self->company;
5173 Returns a name string for this (service/shipping) contact, either
5174 "Company (Last, First)" or "Last, First".
5180 if ( $self->get('ship_last') ) {
5181 my $name = $self->ship_contact;
5182 $name = $self->ship_company. " ($name)" if $self->ship_company;
5191 Returns this customer's full (billing) contact name only, "Last, First"
5197 $self->get('last'). ', '. $self->first;
5202 Returns this customer's full (shipping) contact name only, "Last, First"
5208 $self->get('ship_last')
5209 ? $self->get('ship_last'). ', '. $self->ship_first
5215 Returns this customer's full country name
5221 code2country($self->country);
5224 =item geocode DATA_VENDOR
5226 Returns a value for the customer location as encoded by DATA_VENDOR.
5227 Currently this only makes sense for "CCH" as DATA_VENDOR.
5232 my ($self, $data_vendor) = (shift, shift); #always cch for now
5234 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
5235 return $geocode if $geocode;
5237 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5241 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5242 if $self->country eq 'US';
5244 #CCH specific location stuff
5245 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5247 my @cust_tax_location =
5249 'table' => 'cust_tax_location',
5250 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5251 'extra_sql' => $extra_sql,
5252 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
5255 $geocode = $cust_tax_location[0]->geocode
5256 if scalar(@cust_tax_location);
5265 Returns a status string for this customer, currently:
5269 =item prospect - No packages have ever been ordered
5271 =item active - One or more recurring packages is active
5273 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5275 =item suspended - All non-cancelled recurring packages are suspended
5277 =item cancelled - All recurring packages are cancelled
5283 sub status { shift->cust_status(@_); }
5287 for my $status (qw( prospect active inactive suspended cancelled )) {
5288 my $method = $status.'_sql';
5289 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5290 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5291 $sth->execute( ($self->custnum) x $numnum )
5292 or die "Error executing 'SELECT $sql': ". $sth->errstr;
5293 return $status if $sth->fetchrow_arrayref->[0];
5297 =item ucfirst_cust_status
5299 =item ucfirst_status
5301 Returns the status with the first character capitalized.
5305 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5307 sub ucfirst_cust_status {
5309 ucfirst($self->cust_status);
5314 Returns a hex triplet color string for this customer's status.
5318 use vars qw(%statuscolor);
5319 tie %statuscolor, 'Tie::IxHash',
5320 'prospect' => '7e0079', #'000000', #black? naw, purple
5321 'active' => '00CC00', #green
5322 'inactive' => '0000CC', #blue
5323 'suspended' => 'FF9900', #yellow
5324 'cancelled' => 'FF0000', #red
5327 sub statuscolor { shift->cust_statuscolor(@_); }
5329 sub cust_statuscolor {
5331 $statuscolor{$self->cust_status};
5336 Returns an array of hashes representing the customer's RT tickets.
5343 my $num = $conf->config('cust_main-max_tickets') || 10;
5346 unless ( $conf->config('ticket_system-custom_priority_field') ) {
5348 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5352 foreach my $priority (
5353 $conf->config('ticket_system-custom_priority_field-values'), ''
5355 last if scalar(@tickets) >= $num;
5357 @{ FS::TicketSystem->customer_tickets( $self->custnum,
5358 $num - scalar(@tickets),
5367 # Return services representing svc_accts in customer support packages
5368 sub support_services {
5370 my %packages = map { $_ => 1 } $conf->config('support_packages');
5372 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5373 grep { $_->part_svc->svcdb eq 'svc_acct' }
5374 map { $_->cust_svc }
5375 grep { exists $packages{ $_->pkgpart } }
5376 $self->ncancelled_pkgs;
5382 =head1 CLASS METHODS
5388 Class method that returns the list of possible status strings for customers
5389 (see L<the status method|/status>). For example:
5391 @statuses = FS::cust_main->statuses();
5396 #my $self = shift; #could be class...
5402 Returns an SQL expression identifying prospective cust_main records (customers
5403 with no packages ever ordered)
5407 use vars qw($select_count_pkgs);
5408 $select_count_pkgs =
5409 "SELECT COUNT(*) FROM cust_pkg
5410 WHERE cust_pkg.custnum = cust_main.custnum";
5412 sub select_count_pkgs_sql {
5416 sub prospect_sql { "
5417 0 = ( $select_count_pkgs )
5422 Returns an SQL expression identifying active cust_main records (customers with
5423 active recurring packages).
5428 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5434 Returns an SQL expression identifying inactive cust_main records (customers with
5435 no active recurring packages, but otherwise unsuspended/uncancelled).
5439 sub inactive_sql { "
5440 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5442 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5448 Returns an SQL expression identifying suspended cust_main records.
5453 sub suspended_sql { susp_sql(@_); }
5455 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5457 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5463 Returns an SQL expression identifying cancelled cust_main records.
5467 sub cancelled_sql { cancel_sql(@_); }
5470 my $recurring_sql = FS::cust_pkg->recurring_sql;
5471 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5474 0 < ( $select_count_pkgs )
5475 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
5476 AND 0 = ( $select_count_pkgs AND $recurring_sql
5477 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5479 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5485 =item uncancelled_sql
5487 Returns an SQL expression identifying un-cancelled cust_main records.
5491 sub uncancelled_sql { uncancel_sql(@_); }
5492 sub uncancel_sql { "
5493 ( 0 < ( $select_count_pkgs
5494 AND ( cust_pkg.cancel IS NULL
5495 OR cust_pkg.cancel = 0
5498 OR 0 = ( $select_count_pkgs )
5504 Returns an SQL fragment to retreive the balance.
5509 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5510 WHERE cust_bill.custnum = cust_main.custnum )
5511 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5512 WHERE cust_pay.custnum = cust_main.custnum )
5513 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5514 WHERE cust_credit.custnum = cust_main.custnum )
5515 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5516 WHERE cust_refund.custnum = cust_main.custnum )
5519 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5521 Returns an SQL fragment to retreive the balance for this customer, only
5522 considering invoices with date earlier than START_TIME, and optionally not
5523 later than END_TIME (total_owed_date minus total_unapplied_credits minus
5524 total_unapplied_payments).
5526 Times are specified as SQL fragments or numeric
5527 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5528 L<Date::Parse> for conversion functions. The empty string can be passed
5529 to disable that time constraint completely.
5531 Available options are:
5535 =item unapplied_date
5537 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)
5542 set to true to remove all customer comparison clauses, for totals
5547 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5552 JOIN clause (typically used with the total option)
5558 sub balance_date_sql {
5559 my( $class, $start, $end, %opt ) = @_;
5561 my $owed = FS::cust_bill->owed_sql;
5562 my $unapp_refund = FS::cust_refund->unapplied_sql;
5563 my $unapp_credit = FS::cust_credit->unapplied_sql;
5564 my $unapp_pay = FS::cust_pay->unapplied_sql;
5566 my $j = $opt{'join'} || '';
5568 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5569 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5570 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5571 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5573 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5574 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5575 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5576 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5581 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5583 Helper method for balance_date_sql; name (and usage) subject to change
5584 (suggestions welcome).
5586 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5587 cust_refund, cust_credit or cust_pay).
5589 If TABLE is "cust_bill" or the unapplied_date option is true, only
5590 considers records with date earlier than START_TIME, and optionally not
5591 later than END_TIME .
5595 sub _money_table_where {
5596 my( $class, $table, $start, $end, %opt ) = @_;
5599 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5600 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5601 push @where, "$table._date <= $start" if defined($start) && length($start);
5602 push @where, "$table._date > $end" if defined($end) && length($end);
5604 push @where, @{$opt{'where'}} if $opt{'where'};
5605 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5611 =item search_sql HASHREF
5615 Returns a qsearch hash expression to search for parameters specified in HREF.
5616 Valid parameters are
5624 =item cancelled_pkgs
5630 listref of start date, end date
5636 =item current_balance
5638 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5642 =item flattened_pkgs
5651 my ($class, $params) = @_;
5662 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5664 "cust_main.agentnum = $1";
5671 #prospect active inactive suspended cancelled
5672 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5673 my $method = $params->{'status'}. '_sql';
5674 #push @where, $class->$method();
5675 push @where, FS::cust_main->$method();
5679 # parse cancelled package checkbox
5684 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5685 unless $params->{'cancelled_pkgs'};
5691 foreach my $field (qw( signupdate )) {
5693 next unless exists($params->{$field});
5695 my($beginning, $ending) = @{$params->{$field}};
5698 "cust_main.$field IS NOT NULL",
5699 "cust_main.$field >= $beginning",
5700 "cust_main.$field <= $ending";
5702 $orderby ||= "ORDER BY cust_main.$field";
5710 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5712 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5719 #my $balance_sql = $class->balance_sql();
5720 my $balance_sql = FS::cust_main->balance_sql();
5722 push @where, map { s/current_balance/$balance_sql/; $_ }
5723 @{ $params->{'current_balance'} };
5729 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
5731 "cust_main.custbatch = '$1'";
5735 # setup queries, subs, etc. for the search
5738 $orderby ||= 'ORDER BY custnum';
5740 # here is the agent virtualization
5741 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5743 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5745 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5747 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5749 my $select = join(', ',
5750 'cust_main.custnum',
5751 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5754 my(@extra_headers) = ();
5755 my(@extra_fields) = ();
5757 if ($params->{'flattened_pkgs'}) {
5759 if ($dbh->{Driver}->{Name} eq 'Pg') {
5761 $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";
5763 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5764 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5765 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5767 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5768 "omitting packing information from report.";
5771 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";
5773 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5774 $sth->execute() or die $sth->errstr;
5775 my $headerrow = $sth->fetchrow_arrayref;
5776 my $headercount = $headerrow ? $headerrow->[0] : 0;
5777 while($headercount) {
5778 unshift @extra_headers, "Package ". $headercount;
5779 unshift @extra_fields, eval q!sub {my $c = shift;
5780 my @a = split '\|', $c->magic;
5781 my $p = $a[!.--$headercount. q!];
5789 'table' => 'cust_main',
5790 'select' => $select,
5792 'extra_sql' => $extra_sql,
5793 'order_by' => $orderby,
5794 'count_query' => $count_query,
5795 'extra_headers' => \@extra_headers,
5796 'extra_fields' => \@extra_fields,
5801 =item email_search_sql HASHREF
5805 Emails a notice to the specified customers.
5807 Valid parameters are those of the L<search_sql> method, plus the following:
5829 Optional job queue job for status updates.
5833 Returns an error message, or false for success.
5835 If an error occurs during any email, stops the enture send and returns that
5836 error. Presumably if you're getting SMTP errors aborting is better than
5837 retrying everything.
5841 sub email_search_sql {
5842 my($class, $params) = @_;
5844 my $from = delete $params->{from};
5845 my $subject = delete $params->{subject};
5846 my $html_body = delete $params->{html_body};
5847 my $text_body = delete $params->{text_body};
5849 my $job = delete $params->{'job'};
5851 my $sql_query = $class->search_sql($params);
5853 my $count_query = delete($sql_query->{'count_query'});
5854 my $count_sth = dbh->prepare($count_query)
5855 or die "Error preparing $count_query: ". dbh->errstr;
5857 or die "Error executing $count_query: ". $count_sth->errstr;
5858 my $count_arrayref = $count_sth->fetchrow_arrayref;
5859 my $num_cust = $count_arrayref->[0];
5861 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5862 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5865 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5867 #eventually order+limit magic to reduce memory use?
5868 foreach my $cust_main ( qsearch($sql_query) ) {
5870 my $to = $cust_main->invoicing_list_emailonly_scalar;
5873 my $error = send_email(
5877 'subject' => $subject,
5878 'html_body' => $html_body,
5879 'text_body' => $text_body,
5882 return $error if $error;
5884 if ( $job ) { #progressbar foo
5886 if ( time - $min_sec > $last ) {
5887 my $error = $job->update_statustext(
5888 int( 100 * $num / $num_cust )
5890 die $error if $error;
5900 use Storable qw(thaw);
5903 sub process_email_search_sql {
5905 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5907 my $param = thaw(decode_base64(shift));
5908 warn Dumper($param) if $DEBUG;
5910 $param->{'job'} = $job;
5912 my $error = FS::cust_main->email_search_sql( $param );
5913 die $error if $error;
5917 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5919 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5920 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5921 appropriate ship_ field is also searched).
5923 Additional options are the same as FS::Record::qsearch
5928 my( $self, $fuzzy, $hash, @opt) = @_;
5933 check_and_rebuild_fuzzyfiles();
5934 foreach my $field ( keys %$fuzzy ) {
5936 my $all = $self->all_X($field);
5937 next unless scalar(@$all);
5940 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5943 foreach ( keys %match ) {
5944 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5945 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5948 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5951 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5953 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5961 Returns a masked version of the named field
5966 my ($self,$field) = @_;
5970 'x'x(length($self->getfield($field))-4).
5971 substr($self->getfield($field), (length($self->getfield($field))-4));
5981 =item smart_search OPTION => VALUE ...
5983 Accepts the following options: I<search>, the string to search for. The string
5984 will be searched for as a customer number, phone number, name or company name,
5985 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5986 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5987 skip fuzzy matching when an exact match is found.
5989 Any additional options are treated as an additional qualifier on the search
5992 Returns a (possibly empty) array of FS::cust_main objects.
5999 #here is the agent virtualization
6000 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6004 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
6005 my $search = delete $options{'search'};
6006 ( my $alphanum_search = $search ) =~ s/\W//g;
6008 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
6010 #false laziness w/Record::ut_phone
6011 my $phonen = "$1-$2-$3";
6012 $phonen .= " x$4" if $4;
6014 push @cust_main, qsearch( {
6015 'table' => 'cust_main',
6016 'hashref' => { %options },
6017 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
6019 join(' OR ', map "$_ = '$phonen'",
6020 qw( daytime night fax
6021 ship_daytime ship_night ship_fax )
6024 " AND $agentnums_sql", #agent virtualization
6027 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
6028 #try looking for matches with extensions unless one was specified
6030 push @cust_main, qsearch( {
6031 'table' => 'cust_main',
6032 'hashref' => { %options },
6033 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
6035 join(' OR ', map "$_ LIKE '$phonen\%'",
6037 ship_daytime ship_night )
6040 " AND $agentnums_sql", #agent virtualization
6045 # custnum search (also try agent_custid), with some tweaking options if your
6046 # legacy cust "numbers" have letters
6049 if ( $search =~ /^\s*(\d+)\s*$/
6050 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
6051 && $search =~ /^\s*(\w\w?\d+)\s*$/
6058 if ( $num <= 2147483647 ) { #need a bigint custnum? wow.
6059 push @cust_main, qsearch( {
6060 'table' => 'cust_main',
6061 'hashref' => { 'custnum' => $num, %options },
6062 'extra_sql' => " AND $agentnums_sql", #agent virtualization
6066 push @cust_main, qsearch( {
6067 'table' => 'cust_main',
6068 'hashref' => { 'agent_custid' => $num, %options },
6069 'extra_sql' => " AND $agentnums_sql", #agent virtualization
6072 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
6074 my($company, $last, $first) = ( $1, $2, $3 );
6076 # "Company (Last, First)"
6077 #this is probably something a browser remembered,
6078 #so just do an exact search
6080 foreach my $prefix ( '', 'ship_' ) {
6081 push @cust_main, qsearch( {
6082 'table' => 'cust_main',
6083 'hashref' => { $prefix.'first' => $first,
6084 $prefix.'last' => $last,
6085 $prefix.'company' => $company,
6088 'extra_sql' => " AND $agentnums_sql",
6092 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
6093 # try (ship_){last,company}
6097 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
6098 # # full strings the browser remembers won't work
6099 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
6101 use Lingua::EN::NameParse;
6102 my $NameParse = new Lingua::EN::NameParse(
6104 allow_reversed => 1,
6107 my($last, $first) = ( '', '' );
6108 #maybe disable this too and just rely on NameParse?
6109 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
6111 ($last, $first) = ( $1, $2 );
6113 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
6114 } elsif ( ! $NameParse->parse($value) ) {
6116 my %name = $NameParse->components;
6117 $first = $name{'given_name_1'};
6118 $last = $name{'surname_1'};
6122 if ( $first && $last ) {
6124 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
6127 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6129 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
6130 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
6133 push @cust_main, qsearch( {
6134 'table' => 'cust_main',
6135 'hashref' => \%options,
6136 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6139 # or it just be something that was typed in... (try that in a sec)
6143 my $q_value = dbh->quote($value);
6146 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6147 $sql .= " ( LOWER(last) = $q_value
6148 OR LOWER(company) = $q_value
6149 OR LOWER(ship_last) = $q_value
6150 OR LOWER(ship_company) = $q_value
6153 push @cust_main, qsearch( {
6154 'table' => 'cust_main',
6155 'hashref' => \%options,
6156 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6159 #no exact match, trying substring/fuzzy
6160 #always do substring & fuzzy (unless they're explicity config'ed off)
6161 #getting complaints searches are not returning enough
6162 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
6164 #still some false laziness w/search_sql (was search/cust_main.cgi)
6169 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
6170 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
6173 if ( $first && $last ) {
6176 { 'first' => { op=>'ILIKE', value=>"%$first%" },
6177 'last' => { op=>'ILIKE', value=>"%$last%" },
6179 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
6180 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
6187 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
6188 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
6192 foreach my $hashref ( @hashrefs ) {
6194 push @cust_main, qsearch( {
6195 'table' => 'cust_main',
6196 'hashref' => { %$hashref,
6199 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6208 " AND $agentnums_sql", #extra_sql #agent virtualization
6211 if ( $first && $last ) {
6212 push @cust_main, FS::cust_main->fuzzy_search(
6213 { 'last' => $last, #fuzzy hashref
6214 'first' => $first }, #
6218 foreach my $field ( 'last', 'company' ) {
6220 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6225 #eliminate duplicates
6227 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6237 Accepts the following options: I<email>, the email address to search for. The
6238 email address will be searched for as an email invoice destination and as an
6241 #Any additional options are treated as an additional qualifier on the search
6242 #(i.e. I<agentnum>).
6244 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6254 my $email = delete $options{'email'};
6256 #we're only being used by RT at the moment... no agent virtualization yet
6257 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6261 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6263 my ( $user, $domain ) = ( $1, $2 );
6265 warn "$me smart_search: searching for $user in domain $domain"
6271 'table' => 'cust_main_invoice',
6272 'hashref' => { 'dest' => $email },
6279 map $_->cust_svc->cust_pkg,
6281 'table' => 'svc_acct',
6282 'hashref' => { 'username' => $user, },
6284 'AND ( SELECT domain FROM svc_domain
6285 WHERE svc_acct.domsvc = svc_domain.svcnum
6286 ) = '. dbh->quote($domain),
6292 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6294 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6301 =item check_and_rebuild_fuzzyfiles
6305 use vars qw(@fuzzyfields);
6306 @fuzzyfields = ( 'last', 'first', 'company' );
6308 sub check_and_rebuild_fuzzyfiles {
6309 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6310 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6313 =item rebuild_fuzzyfiles
6317 sub rebuild_fuzzyfiles {
6319 use Fcntl qw(:flock);
6321 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6322 mkdir $dir, 0700 unless -d $dir;
6324 foreach my $fuzzy ( @fuzzyfields ) {
6326 open(LOCK,">>$dir/cust_main.$fuzzy")
6327 or die "can't open $dir/cust_main.$fuzzy: $!";
6329 or die "can't lock $dir/cust_main.$fuzzy: $!";
6331 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6332 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6334 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6335 my $sth = dbh->prepare("SELECT $field FROM cust_main".
6336 " WHERE $field != '' AND $field IS NOT NULL");
6337 $sth->execute or die $sth->errstr;
6339 while ( my $row = $sth->fetchrow_arrayref ) {
6340 print CACHE $row->[0]. "\n";
6345 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6347 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6358 my( $self, $field ) = @_;
6359 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6360 open(CACHE,"<$dir/cust_main.$field")
6361 or die "can't open $dir/cust_main.$field: $!";
6362 my @array = map { chomp; $_; } <CACHE>;
6367 =item append_fuzzyfiles LASTNAME COMPANY
6371 sub append_fuzzyfiles {
6372 #my( $first, $last, $company ) = @_;
6374 &check_and_rebuild_fuzzyfiles;
6376 use Fcntl qw(:flock);
6378 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6380 foreach my $field (qw( first last company )) {
6385 open(CACHE,">>$dir/cust_main.$field")
6386 or die "can't open $dir/cust_main.$field: $!";
6387 flock(CACHE,LOCK_EX)
6388 or die "can't lock $dir/cust_main.$field: $!";
6390 print CACHE "$value\n";
6392 flock(CACHE,LOCK_UN)
6393 or die "can't unlock $dir/cust_main.$field: $!";
6408 #warn join('-',keys %$param);
6409 my $fh = $param->{filehandle};
6410 my @fields = @{$param->{fields}};
6412 eval "use Text::CSV_XS;";
6415 my $csv = new Text::CSV_XS;
6422 local $SIG{HUP} = 'IGNORE';
6423 local $SIG{INT} = 'IGNORE';
6424 local $SIG{QUIT} = 'IGNORE';
6425 local $SIG{TERM} = 'IGNORE';
6426 local $SIG{TSTP} = 'IGNORE';
6427 local $SIG{PIPE} = 'IGNORE';
6429 my $oldAutoCommit = $FS::UID::AutoCommit;
6430 local $FS::UID::AutoCommit = 0;
6433 #while ( $columns = $csv->getline($fh) ) {
6435 while ( defined($line=<$fh>) ) {
6437 $csv->parse($line) or do {
6438 $dbh->rollback if $oldAutoCommit;
6439 return "can't parse: ". $csv->error_input();
6442 my @columns = $csv->fields();
6443 #warn join('-',@columns);
6446 foreach my $field ( @fields ) {
6447 $row{$field} = shift @columns;
6450 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6451 unless ( $cust_main ) {
6452 $dbh->rollback if $oldAutoCommit;
6453 return "unknown custnum $row{'custnum'}";
6456 if ( $row{'amount'} > 0 ) {
6457 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6459 $dbh->rollback if $oldAutoCommit;
6463 } elsif ( $row{'amount'} < 0 ) {
6464 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6467 $dbh->rollback if $oldAutoCommit;
6477 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6479 return "Empty file!" unless $imported;
6485 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6487 Sends a templated email notification to the customer (see L<Text::Template>).
6489 OPTIONS is a hash and may include
6491 I<from> - the email sender (default is invoice_from)
6493 I<to> - comma-separated scalar or arrayref of recipients
6494 (default is invoicing_list)
6496 I<subject> - The subject line of the sent email notification
6497 (default is "Notice from company_name")
6499 I<extra_fields> - a hashref of name/value pairs which will be substituted
6502 The following variables are vavailable in the template.
6504 I<$first> - the customer first name
6505 I<$last> - the customer last name
6506 I<$company> - the customer company
6507 I<$payby> - a description of the method of payment for the customer
6508 # would be nice to use FS::payby::shortname
6509 I<$payinfo> - the account information used to collect for this customer
6510 I<$expdate> - the expiration of the customer payment in seconds from epoch
6515 my ($customer, $template, %options) = @_;
6517 return unless $conf->exists($template);
6519 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6520 $from = $options{from} if exists($options{from});
6522 my $to = join(',', $customer->invoicing_list_emailonly);
6523 $to = $options{to} if exists($options{to});
6525 my $subject = "Notice from " . $conf->config('company_name')
6526 if $conf->exists('company_name');
6527 $subject = $options{subject} if exists($options{subject});
6529 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6530 SOURCE => [ map "$_\n",
6531 $conf->config($template)]
6533 or die "can't create new Text::Template object: Text::Template::ERROR";
6534 $notify_template->compile()
6535 or die "can't compile template: Text::Template::ERROR";
6537 $FS::notify_template::_template::company_name = $conf->config('company_name');
6538 $FS::notify_template::_template::company_address =
6539 join("\n", $conf->config('company_address') ). "\n";
6541 my $paydate = $customer->paydate || '2037-12-31';
6542 $FS::notify_template::_template::first = $customer->first;
6543 $FS::notify_template::_template::last = $customer->last;
6544 $FS::notify_template::_template::company = $customer->company;
6545 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6546 my $payby = $customer->payby;
6547 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6548 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6550 #credit cards expire at the end of the month/year of their exp date
6551 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6552 $FS::notify_template::_template::payby = 'credit card';
6553 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6554 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6556 }elsif ($payby eq 'COMP') {
6557 $FS::notify_template::_template::payby = 'complimentary account';
6559 $FS::notify_template::_template::payby = 'current method';
6561 $FS::notify_template::_template::expdate = $expire_time;
6563 for (keys %{$options{extra_fields}}){
6565 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6568 send_email(from => $from,
6570 subject => $subject,
6571 body => $notify_template->fill_in( PACKAGE =>
6572 'FS::notify_template::_template' ),
6577 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6579 Generates a templated notification to the customer (see L<Text::Template>).
6581 OPTIONS is a hash and may include
6583 I<extra_fields> - a hashref of name/value pairs which will be substituted
6584 into the template. These values may override values mentioned below
6585 and those from the customer record.
6587 The following variables are available in the template instead of or in addition
6588 to the fields of the customer record.
6590 I<$payby> - a description of the method of payment for the customer
6591 # would be nice to use FS::payby::shortname
6592 I<$payinfo> - the masked account information used to collect for this customer
6593 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6594 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6598 sub generate_letter {
6599 my ($self, $template, %options) = @_;
6601 return unless $conf->exists($template);
6603 my $letter_template = new Text::Template
6605 SOURCE => [ map "$_\n", $conf->config($template)],
6606 DELIMITERS => [ '[@--', '--@]' ],
6608 or die "can't create new Text::Template object: Text::Template::ERROR";
6610 $letter_template->compile()
6611 or die "can't compile template: Text::Template::ERROR";
6613 my %letter_data = map { $_ => $self->$_ } $self->fields;
6614 $letter_data{payinfo} = $self->mask_payinfo;
6616 #my $paydate = $self->paydate || '2037-12-31';
6617 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6619 my $payby = $self->payby;
6620 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6621 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6623 #credit cards expire at the end of the month/year of their exp date
6624 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6625 $letter_data{payby} = 'credit card';
6626 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6627 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6629 }elsif ($payby eq 'COMP') {
6630 $letter_data{payby} = 'complimentary account';
6632 $letter_data{payby} = 'current method';
6634 $letter_data{expdate} = $expire_time;
6636 for (keys %{$options{extra_fields}}){
6637 $letter_data{$_} = $options{extra_fields}->{$_};
6640 unless(exists($letter_data{returnaddress})){
6641 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6642 $self->agent_template)
6644 if ( length($retadd) ) {
6645 $letter_data{returnaddress} = $retadd;
6646 } elsif ( grep /\S/, $conf->config('company_address') ) {
6647 $letter_data{returnaddress} =
6648 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6649 $conf->config('company_address')
6652 $letter_data{returnaddress} = '~';
6656 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6658 $letter_data{company_name} = $conf->config('company_name');
6660 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6661 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6665 ) or die "can't open temp file: $!\n";
6667 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6669 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6673 =item print_ps TEMPLATE
6675 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6681 my $file = $self->generate_letter(@_);
6682 FS::Misc::generate_ps($file);
6685 =item print TEMPLATE
6687 Prints the filled in template.
6689 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6693 sub queueable_print {
6696 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6697 or die "invalid customer number: " . $opt{custvnum};
6699 my $error = $self->print( $opt{template} );
6700 die $error if $error;
6704 my ($self, $template) = (shift, shift);
6705 do_print [ $self->print_ps($template) ];
6708 sub agent_template {
6710 $self->_agent_plandata('agent_templatename');
6713 sub agent_invoice_from {
6715 $self->_agent_plandata('agent_invoice_from');
6718 sub _agent_plandata {
6719 my( $self, $option ) = @_;
6721 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6722 #agent-specific Conf
6724 use FS::part_event::Condition;
6726 my $agentnum = $self->agentnum;
6729 if ( driver_name =~ /^Pg/i ) {
6731 } elsif ( driver_name =~ /^mysql/i ) {
6734 die "don't know how to use regular expressions in ". driver_name. " databases";
6737 my $part_event_option =
6739 'select' => 'part_event_option.*',
6740 'table' => 'part_event_option',
6742 LEFT JOIN part_event USING ( eventpart )
6743 LEFT JOIN part_event_option AS peo_agentnum
6744 ON ( part_event.eventpart = peo_agentnum.eventpart
6745 AND peo_agentnum.optionname = 'agentnum'
6746 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6748 LEFT JOIN part_event_option AS peo_cust_bill_age
6749 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6750 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6753 #'hashref' => { 'optionname' => $option },
6754 #'hashref' => { 'part_event_option.optionname' => $option },
6756 " WHERE part_event_option.optionname = ". dbh->quote($option).
6757 " AND action = 'cust_bill_send_agent' ".
6758 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6759 " AND peo_agentnum.optionname = 'agentnum' ".
6760 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
6762 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6764 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6766 , part_event.weight".
6770 unless ( $part_event_option ) {
6771 return $self->agent->invoice_template || ''
6772 if $option eq 'agent_templatename';
6776 $part_event_option->optionvalue;
6781 ## actual sub, not a method, designed to be called from the queue.
6782 ## sets up the customer, and calls the bill_and_collect
6783 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6784 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6785 $cust_main->bill_and_collect(
6796 The delete method should possibly take an FS::cust_main object reference
6797 instead of a scalar customer number.
6799 Bill and collect options should probably be passed as references instead of a
6802 There should probably be a configuration file with a list of allowed credit
6805 No multiple currency support (probably a larger project than just this module).
6807 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6809 Birthdates rely on negative epoch values.
6811 The payby for card/check batches is broken. With mixed batching, bad
6814 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
6818 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6819 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6820 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.