5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 use Scalar::Util qw( blessed );
12 use Time::Local qw(timelocal_nocheck);
15 use Digest::MD5 qw(md5_base64);
19 use File::Slurp qw( slurp );
20 use File::Temp qw( tempfile );
21 use String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
24 use FS::UID qw( getotaker dbh driver_name );
25 use FS::Record qw( qsearchs qsearch dbdef );
26 use FS::Misc qw( generate_email send_email generate_ps do_print );
27 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
32 use FS::cust_bill_pkg_display;
34 use FS::cust_pay_pending;
35 use FS::cust_pay_void;
36 use FS::cust_pay_batch;
39 use FS::part_referral;
40 use FS::cust_main_county;
41 use FS::cust_tax_location;
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')
1269 #barf. need message catalogs. i18n. etc.
1270 $error .= "Please select an advertising source."
1271 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1272 return $error if $error;
1274 return "Unknown agent"
1275 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1277 return "Unknown refnum"
1278 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1280 return "Unknown referring custnum: ". $self->referral_custnum
1281 unless ! $self->referral_custnum
1282 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1284 if ( $self->ss eq '' ) {
1289 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1290 or return "Illegal social security number: ". $self->ss;
1291 $self->ss("$1-$2-$3");
1295 # bad idea to disable, causes billing to fail because of no tax rates later
1296 # unless ( $import ) {
1297 unless ( qsearch('cust_main_county', {
1298 'country' => $self->country,
1301 return "Unknown state/county/country: ".
1302 $self->state. "/". $self->county. "/". $self->country
1303 unless qsearch('cust_main_county',{
1304 'state' => $self->state,
1305 'county' => $self->county,
1306 'country' => $self->country,
1312 $self->ut_phonen('daytime', $self->country)
1313 || $self->ut_phonen('night', $self->country)
1314 || $self->ut_phonen('fax', $self->country)
1315 || $self->ut_zip('zip', $self->country)
1317 return $error if $error;
1319 if ( $conf->exists('cust_main-require_phone')
1320 && ! length($self->daytime) && ! length($self->night)
1323 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1325 : FS::Msgcat::_gettext('daytime');
1326 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1328 : FS::Msgcat::_gettext('night');
1330 return "$daytime_label or $night_label is required"
1334 if ( $self->has_ship_address
1335 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1336 $self->addr_fields )
1340 $self->ut_name('ship_last')
1341 || $self->ut_name('ship_first')
1342 || $self->ut_textn('ship_company')
1343 || $self->ut_text('ship_address1')
1344 || $self->ut_textn('ship_address2')
1345 || $self->ut_text('ship_city')
1346 || $self->ut_textn('ship_county')
1347 || $self->ut_textn('ship_state')
1348 || $self->ut_country('ship_country')
1350 return $error if $error;
1352 #false laziness with above
1353 unless ( qsearchs('cust_main_county', {
1354 'country' => $self->ship_country,
1357 return "Unknown ship_state/ship_county/ship_country: ".
1358 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1359 unless qsearch('cust_main_county',{
1360 'state' => $self->ship_state,
1361 'county' => $self->ship_county,
1362 'country' => $self->ship_country,
1368 $self->ut_phonen('ship_daytime', $self->ship_country)
1369 || $self->ut_phonen('ship_night', $self->ship_country)
1370 || $self->ut_phonen('ship_fax', $self->ship_country)
1371 || $self->ut_zip('ship_zip', $self->ship_country)
1373 return $error if $error;
1375 return "Unit # is required."
1376 if $self->ship_address2 =~ /^\s*$/
1377 && $conf->exists('cust_main-require_address2');
1379 } else { # ship_ info eq billing info, so don't store dup info in database
1381 $self->setfield("ship_$_", '')
1382 foreach $self->addr_fields;
1384 return "Unit # is required."
1385 if $self->address2 =~ /^\s*$/
1386 && $conf->exists('cust_main-require_address2');
1390 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1391 # or return "Illegal payby: ". $self->payby;
1393 FS::payby->can_payby($self->table, $self->payby)
1394 or return "Illegal payby: ". $self->payby;
1396 $error = $self->ut_numbern('paystart_month')
1397 || $self->ut_numbern('paystart_year')
1398 || $self->ut_numbern('payissue')
1399 || $self->ut_textn('paytype')
1401 return $error if $error;
1403 if ( $self->payip eq '' ) {
1406 $error = $self->ut_ip('payip');
1407 return $error if $error;
1410 # If it is encrypted and the private key is not availaible then we can't
1411 # check the credit card.
1413 my $check_payinfo = 1;
1415 if ($self->is_encrypted($self->payinfo)) {
1419 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1421 my $payinfo = $self->payinfo;
1422 $payinfo =~ s/\D//g;
1423 $payinfo =~ /^(\d{13,16})$/
1424 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1426 $self->payinfo($payinfo);
1428 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1430 return gettext('unknown_card_type')
1431 if cardtype($self->payinfo) eq "Unknown";
1433 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1435 return 'Banned credit card: banned on '.
1436 time2str('%a %h %o at %r', $ban->_date).
1437 ' by '. $ban->otaker.
1438 ' (ban# '. $ban->bannum. ')';
1441 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1442 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1443 $self->paycvv =~ /^(\d{4})$/
1444 or return "CVV2 (CID) for American Express cards is four digits.";
1447 $self->paycvv =~ /^(\d{3})$/
1448 or return "CVV2 (CVC2/CID) is three digits.";
1455 my $cardtype = cardtype($payinfo);
1456 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1458 return "Start date or issue number is required for $cardtype cards"
1459 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1461 return "Start month must be between 1 and 12"
1462 if $self->paystart_month
1463 and $self->paystart_month < 1 || $self->paystart_month > 12;
1465 return "Start year must be 1990 or later"
1466 if $self->paystart_year
1467 and $self->paystart_year < 1990;
1469 return "Issue number must be beween 1 and 99"
1471 and $self->payissue < 1 || $self->payissue > 99;
1474 $self->paystart_month('');
1475 $self->paystart_year('');
1476 $self->payissue('');
1479 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1481 my $payinfo = $self->payinfo;
1482 $payinfo =~ s/[^\d\@]//g;
1483 if ( $conf->exists('echeck-nonus') ) {
1484 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1485 $payinfo = "$1\@$2";
1487 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1488 $payinfo = "$1\@$2";
1490 $self->payinfo($payinfo);
1493 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1495 return 'Banned ACH account: banned on '.
1496 time2str('%a %h %o at %r', $ban->_date).
1497 ' by '. $ban->otaker.
1498 ' (ban# '. $ban->bannum. ')';
1501 } elsif ( $self->payby eq 'LECB' ) {
1503 my $payinfo = $self->payinfo;
1504 $payinfo =~ s/\D//g;
1505 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1507 $self->payinfo($payinfo);
1510 } elsif ( $self->payby eq 'BILL' ) {
1512 $error = $self->ut_textn('payinfo');
1513 return "Illegal P.O. number: ". $self->payinfo if $error;
1516 } elsif ( $self->payby eq 'COMP' ) {
1518 my $curuser = $FS::CurrentUser::CurrentUser;
1519 if ( ! $self->custnum
1520 && ! $curuser->access_right('Complimentary customer')
1523 return "You are not permitted to create complimentary accounts."
1526 $error = $self->ut_textn('payinfo');
1527 return "Illegal comp account issuer: ". $self->payinfo if $error;
1530 } elsif ( $self->payby eq 'PREPAY' ) {
1532 my $payinfo = $self->payinfo;
1533 $payinfo =~ s/\W//g; #anything else would just confuse things
1534 $self->payinfo($payinfo);
1535 $error = $self->ut_alpha('payinfo');
1536 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1537 return "Unknown prepayment identifier"
1538 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1543 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1544 return "Expiration date required"
1545 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1549 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1550 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1551 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1552 ( $m, $y ) = ( $3, "20$2" );
1554 return "Illegal expiration date: ". $self->paydate;
1556 $self->paydate("$y-$m-01");
1557 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1558 return gettext('expired_card')
1560 && !$ignore_expired_card
1561 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1564 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1565 ( ! $conf->exists('require_cardname')
1566 || $self->payby !~ /^(CARD|DCRD)$/ )
1568 $self->payname( $self->first. " ". $self->getfield('last') );
1570 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1571 or return gettext('illegal_name'). " payname: ". $self->payname;
1575 foreach my $flag (qw( tax spool_cdr squelch_cdr )) {
1576 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1580 $self->otaker(getotaker) unless $self->otaker;
1582 warn "$me check AFTER: \n". $self->_dump
1585 $self->SUPER::check;
1590 Returns a list of fields which have ship_ duplicates.
1595 qw( last first company
1596 address1 address2 city county state zip country
1601 =item has_ship_address
1603 Returns true if this customer record has a separate shipping address.
1607 sub has_ship_address {
1609 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1614 Returns all packages (see L<FS::cust_pkg>) for this customer.
1621 return $self->num_pkgs unless wantarray;
1624 if ( $self->{'_pkgnum'} ) {
1625 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1627 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1630 sort sort_packages @cust_pkg;
1635 Synonym for B<all_pkgs>.
1640 shift->all_pkgs(@_);
1643 =item ncancelled_pkgs
1645 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1649 sub ncancelled_pkgs {
1652 return $self->num_ncancelled_pkgs unless wantarray;
1655 if ( $self->{'_pkgnum'} ) {
1657 warn "$me ncancelled_pkgs: returning cached objects"
1660 @cust_pkg = grep { ! $_->getfield('cancel') }
1661 values %{ $self->{'_pkgnum'}->cache };
1665 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1666 $self->custnum. "\n"
1670 qsearch( 'cust_pkg', {
1671 'custnum' => $self->custnum,
1675 qsearch( 'cust_pkg', {
1676 'custnum' => $self->custnum,
1681 sort sort_packages @cust_pkg;
1685 # This should be generalized to use config options to determine order.
1687 if ( $a->get('cancel') and $b->get('cancel') ) {
1688 $a->pkgnum <=> $b->pkgnum;
1689 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1690 return -1 if $b->get('cancel');
1691 return 1 if $a->get('cancel');
1694 $a->pkgnum <=> $b->pkgnum;
1698 =item suspended_pkgs
1700 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1704 sub suspended_pkgs {
1706 grep { $_->susp } $self->ncancelled_pkgs;
1709 =item unflagged_suspended_pkgs
1711 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1712 customer (thouse packages without the `manual_flag' set).
1716 sub unflagged_suspended_pkgs {
1718 return $self->suspended_pkgs
1719 unless dbdef->table('cust_pkg')->column('manual_flag');
1720 grep { ! $_->manual_flag } $self->suspended_pkgs;
1723 =item unsuspended_pkgs
1725 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1730 sub unsuspended_pkgs {
1732 grep { ! $_->susp } $self->ncancelled_pkgs;
1735 =item num_cancelled_pkgs
1737 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1742 sub num_cancelled_pkgs {
1743 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1746 sub num_ncancelled_pkgs {
1747 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1751 my( $self ) = shift;
1752 my $sql = scalar(@_) ? shift : '';
1753 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1754 my $sth = dbh->prepare(
1755 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1756 ) or die dbh->errstr;
1757 $sth->execute($self->custnum) or die $sth->errstr;
1758 $sth->fetchrow_arrayref->[0];
1763 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1764 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1765 on success or a list of errors.
1771 grep { $_->unsuspend } $self->suspended_pkgs;
1776 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1778 Returns a list: an empty list on success or a list of errors.
1784 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1787 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1789 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1790 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1791 of a list of pkgparts; the hashref has the following keys:
1795 =item pkgparts - listref of pkgparts
1797 =item (other options are passed to the suspend method)
1802 Returns a list: an empty list on success or a list of errors.
1806 sub suspend_if_pkgpart {
1808 my (@pkgparts, %opt);
1809 if (ref($_[0]) eq 'HASH'){
1810 @pkgparts = @{$_[0]{pkgparts}};
1815 grep { $_->suspend(%opt) }
1816 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1817 $self->unsuspended_pkgs;
1820 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1822 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1823 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1824 instead of a list of pkgparts; the hashref has the following keys:
1828 =item pkgparts - listref of pkgparts
1830 =item (other options are passed to the suspend method)
1834 Returns a list: an empty list on success or a list of errors.
1838 sub suspend_unless_pkgpart {
1840 my (@pkgparts, %opt);
1841 if (ref($_[0]) eq 'HASH'){
1842 @pkgparts = @{$_[0]{pkgparts}};
1847 grep { $_->suspend(%opt) }
1848 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1849 $self->unsuspended_pkgs;
1852 =item cancel [ OPTION => VALUE ... ]
1854 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1856 Available options are:
1860 =item quiet - can be set true to supress email cancellation notices.
1862 =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.
1864 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1868 Always returns a list: an empty list on success or a list of errors.
1873 my( $self, %opt ) = @_;
1875 warn "$me cancel called on customer ". $self->custnum. " with options ".
1876 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1879 return ( 'access denied' )
1880 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1882 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1884 #should try decryption (we might have the private key)
1885 # and if not maybe queue a job for the server that does?
1886 return ( "Can't (yet) ban encrypted credit cards" )
1887 if $self->is_encrypted($self->payinfo);
1889 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1890 my $error = $ban->insert;
1891 return ( $error ) if $error;
1895 my @pkgs = $self->ncancelled_pkgs;
1897 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1898 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1901 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1904 sub _banned_pay_hashref {
1915 'payby' => $payby2ban{$self->payby},
1916 'payinfo' => md5_base64($self->payinfo),
1917 #don't ever *search* on reason! #'reason' =>
1923 Returns all notes (see L<FS::cust_main_note>) for this customer.
1930 qsearch( 'cust_main_note',
1931 { 'custnum' => $self->custnum },
1933 'ORDER BY _DATE DESC'
1939 Returns the agent (see L<FS::agent>) for this customer.
1945 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1948 =item bill_and_collect
1950 Cancels and suspends any packages due, generates bills, applies payments and
1953 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1955 Options are passed as name-value pairs. Currently available options are:
1961 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:
1965 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1969 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.
1973 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1977 If set true, re-charges setup fees.
1981 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)
1987 sub bill_and_collect {
1988 my( $self, %options ) = @_;
1994 #$options{actual_time} not $options{time} because freeside-daily -d is for
1995 #pre-printing invoices
1996 my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
1997 $self->ncancelled_pkgs;
1999 foreach my $cust_pkg ( @cancel_pkgs ) {
2000 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2001 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
2002 'reason_otaker' => $cpr->otaker
2006 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
2007 " for custnum ". $self->custnum. ": $error"
2015 #$options{actual_time} not $options{time} because freeside-daily -d is for
2016 #pre-printing invoices
2019 && ( ( $_->part_pkg->is_prepaid
2021 && $_->bill < $options{actual_time}
2024 && $_->adjourn <= $options{actual_time}
2028 $self->ncancelled_pkgs;
2030 foreach my $cust_pkg ( @susp_pkgs ) {
2031 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2032 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2033 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2034 'reason_otaker' => $cpr->otaker
2039 warn "Error suspending package ". $cust_pkg->pkgnum.
2040 " for custnum ". $self->custnum. ": $error"
2048 my $error = $self->bill( %options );
2049 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
2051 $self->apply_payments_and_credits;
2053 $error = $self->collect( %options );
2054 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2060 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2061 conjunction with the collect method by calling B<bill_and_collect>.
2063 If there is an error, returns the error, otherwise returns false.
2065 Options are passed as name-value pairs. Currently available options are:
2071 If set true, re-charges setup fees.
2075 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:
2079 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2083 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2085 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2089 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.
2096 my( $self, %options ) = @_;
2097 return '' if $self->payby eq 'COMP';
2098 warn "$me bill customer ". $self->custnum. "\n"
2101 my $time = $options{'time'} || time;
2104 local $SIG{HUP} = 'IGNORE';
2105 local $SIG{INT} = 'IGNORE';
2106 local $SIG{QUIT} = 'IGNORE';
2107 local $SIG{TERM} = 'IGNORE';
2108 local $SIG{TSTP} = 'IGNORE';
2109 local $SIG{PIPE} = 'IGNORE';
2111 my $oldAutoCommit = $FS::UID::AutoCommit;
2112 local $FS::UID::AutoCommit = 0;
2115 $self->select_for_update; #mutex
2117 my @cust_bill_pkg = ();
2120 # find the packages which are due for billing, find out how much they are
2121 # & generate invoice database.
2124 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2128 my @precommit_hooks = ();
2130 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2131 foreach my $cust_pkg (@cust_pkgs) {
2133 #NO!! next if $cust_pkg->cancel;
2134 next if $cust_pkg->getfield('cancel');
2136 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2138 #? to avoid use of uninitialized value errors... ?
2139 $cust_pkg->setfield('bill', '')
2140 unless defined($cust_pkg->bill);
2142 #my $part_pkg = $cust_pkg->part_pkg;
2144 my $real_pkgpart = $cust_pkg->pkgpart;
2145 my %hash = $cust_pkg->hash;
2147 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2149 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2152 $self->_make_lines( 'part_pkg' => $part_pkg,
2153 'cust_pkg' => $cust_pkg,
2154 'precommit_hooks' => \@precommit_hooks,
2155 'line_items' => \@cust_bill_pkg,
2156 'setup' => \$total_setup,
2157 'recur' => \$total_recur,
2158 'tax_matrix' => \%taxlisthash,
2160 'options' => \%options,
2163 $dbh->rollback if $oldAutoCommit;
2167 } #foreach my $part_pkg
2169 } #foreach my $cust_pkg
2171 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2172 #but do commit any package date cycling that happened
2173 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2177 my $postal_pkg = $self->charge_postal_fee();
2178 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2179 $dbh->rollback if $oldAutoCommit;
2180 return "can't charge postal invoice fee for customer ".
2181 $self->custnum. ": $postal_pkg";
2184 ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
2185 !$conf->exists('postal_invoice-recurring_only')
2189 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2191 $self->_make_lines( 'part_pkg' => $part_pkg,
2192 'cust_pkg' => $postal_pkg,
2193 'precommit_hooks' => \@precommit_hooks,
2194 'line_items' => \@cust_bill_pkg,
2195 'setup' => \$total_setup,
2196 'recur' => \$total_recur,
2197 'tax_matrix' => \%taxlisthash,
2199 'options' => \%options,
2202 $dbh->rollback if $oldAutoCommit;
2208 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2209 foreach my $tax ( keys %taxlisthash ) {
2210 my $tax_object = shift @{ $taxlisthash{$tax} };
2211 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2212 my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2213 unless (ref($listref_or_error)) {
2214 $dbh->rollback if $oldAutoCommit;
2215 return $listref_or_error;
2217 unshift @{ $taxlisthash{$tax} }, $tax_object;
2219 warn "adding ". $listref_or_error->[1].
2220 " as ". $listref_or_error->[0]. "\n"
2222 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2223 if ( $taxname{ $listref_or_error->[0] } ) {
2224 push @{ $taxname{ $listref_or_error->[0] } }, $tax_object->taxname;
2226 $taxname{ $listref_or_error->[0] } = [ $tax_object->taxname ];
2231 #some taxes are taxed
2234 warn "finding taxed taxes...\n" if $DEBUG > 2;
2235 foreach my $tax ( keys %taxlisthash ) {
2236 my $tax_object = shift @{ $taxlisthash{$tax} };
2237 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2239 next unless $tax_object->can('tax_on_tax');
2241 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2242 my $totname = ref( $tot ). ' '. $tot->taxnum;
2244 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2246 next unless exists( $taxlisthash{ $totname } ); # only increase
2248 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2249 if ( exists( $totlisthash{ $totname } ) ) {
2250 push @{ $totlisthash{ $totname } }, $tax{ $tax_object->taxname };
2252 $totlisthash{ $totname } = [ $tot, $tax{ $tax_object->taxname } ];
2257 warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2258 foreach my $tax ( keys %totlisthash ) {
2259 my $tax_object = shift @{ $totlisthash{$tax} };
2260 warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2262 my $listref_or_error = $tax_object->taxline( @{ $totlisthash{$tax} } );
2263 unless (ref($listref_or_error)) {
2264 $dbh->rollback if $oldAutoCommit;
2265 return $listref_or_error;
2268 warn "adding taxed tax amount ". $listref_or_error->[1].
2269 " as ". $tax_object->taxname. "\n"
2271 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2274 #consolidate and create tax line items
2275 warn "consolidating and generating...\n" if $DEBUG > 2;
2276 foreach my $taxname ( keys %taxname ) {
2279 warn "adding $taxname\n" if $DEBUG > 1;
2280 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2281 $tax += $tax{$taxitem} unless $seen{$taxitem};
2282 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2286 $tax = sprintf('%.2f', $tax );
2287 $total_setup = sprintf('%.2f', $total_setup+$tax );
2289 push @cust_bill_pkg, new FS::cust_bill_pkg {
2295 'itemdesc' => $taxname,
2300 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2302 #create the new invoice
2303 my $cust_bill = new FS::cust_bill ( {
2304 'custnum' => $self->custnum,
2305 '_date' => ( $options{'invoice_time'} || $time ),
2306 'charged' => $charged,
2308 my $error = $cust_bill->insert;
2310 $dbh->rollback if $oldAutoCommit;
2311 return "can't create invoice for customer #". $self->custnum. ": $error";
2314 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2315 $cust_bill_pkg->invnum($cust_bill->invnum);
2316 my $error = $cust_bill_pkg->insert;
2318 $dbh->rollback if $oldAutoCommit;
2319 return "can't create invoice line item: $error";
2324 foreach my $hook ( @precommit_hooks ) {
2326 &{$hook}; #($self) ?
2329 $dbh->rollback if $oldAutoCommit;
2330 return "$@ running precommit hook $hook\n";
2334 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2340 my ($self, %params) = @_;
2342 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2343 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2344 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2345 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2346 my $total_setup = $params{setup} or die "no setup accumulator specified";
2347 my $total_recur = $params{recur} or die "no recur accumulator specified";
2348 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2349 my $time = $params{'time'} or die "no time specified";
2350 my (%options) = %{$params{options}}; #hmmm only for 'resetup'
2353 my $real_pkgpart = $cust_pkg->pkgpart;
2354 my %hash = $cust_pkg->hash;
2355 my $old_cust_pkg = new FS::cust_pkg \%hash;
2361 $cust_pkg->pkgpart($part_pkg->pkgpart);
2369 if ( ! $cust_pkg->setup &&
2371 ( $conf->exists('disable_setup_suspended_pkgs') &&
2372 ! $cust_pkg->getfield('susp')
2373 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2375 || $options{'resetup'}
2378 warn " bill setup\n" if $DEBUG > 1;
2381 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2382 return "$@ running calc_setup for $cust_pkg\n"
2385 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2387 $cust_pkg->setfield('setup', $time)
2388 unless $cust_pkg->setup;
2389 #do need it, but it won't get written to the db
2390 #|| $cust_pkg->pkgpart != $real_pkgpart;
2395 # bill recurring fee
2398 #XXX unit stuff here too
2402 if ( ! $cust_pkg->getfield('susp') and
2403 ( $part_pkg->getfield('freq') ne '0' &&
2404 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2406 || ( $part_pkg->plan eq 'voip_cdr'
2407 && $part_pkg->option('bill_every_call')
2411 # XXX should this be a package event? probably. events are called
2412 # at collection time at the moment, though...
2413 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2414 if $part_pkg->can('reset_usage');
2415 #don't want to reset usage just cause we want a line item??
2416 #&& $part_pkg->pkgpart == $real_pkgpart;
2418 warn " bill recur\n" if $DEBUG > 1;
2421 # XXX shared with $recur_prog
2422 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2424 #over two params! lets at least switch to a hashref for the rest...
2425 my $increment_next_bill = ( $part_pkg->freq ne '0'
2426 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
2428 my %param = ( 'precommit_hooks' => $precommit_hooks,
2429 'increment_next_bill' => $increment_next_bill,
2432 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2433 return "$@ running calc_recur for $cust_pkg\n"
2436 if ( $increment_next_bill ) {
2438 #change this bit to use Date::Manip? CAREFUL with timezones (see
2439 # mailing list archive)
2440 my ($sec,$min,$hour,$mday,$mon,$year) =
2441 (localtime($sdate) )[0,1,2,3,4,5];
2443 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2444 # only for figuring next bill date, nothing else, so, reset $sdate again
2446 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2447 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2448 $cust_pkg->last_bill($sdate);
2450 if ( $part_pkg->freq =~ /^\d+$/ ) {
2451 $mon += $part_pkg->freq;
2452 until ( $mon < 12 ) { $mon -= 12; $year++; }
2453 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2455 $mday += $weeks * 7;
2456 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2459 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2463 return "unparsable frequency: ". $part_pkg->freq;
2465 $cust_pkg->setfield('bill',
2466 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2472 warn "\$setup is undefined" unless defined($setup);
2473 warn "\$recur is undefined" unless defined($recur);
2474 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2477 # If there's line items, create em cust_bill_pkg records
2478 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2483 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2484 # hmm.. and if just the options are modified in some weird price plan?
2486 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2489 my $error = $cust_pkg->replace( $old_cust_pkg,
2490 'options' => { $cust_pkg->options },
2492 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2493 if $error; #just in case
2496 $setup = sprintf( "%.2f", $setup );
2497 $recur = sprintf( "%.2f", $recur );
2498 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2499 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2501 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2502 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2505 if ( $setup != 0 || $recur != 0 ) {
2507 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2510 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2512 warn " adding customer package invoice detail: $_\n"
2513 foreach @cust_pkg_detail;
2515 push @details, @cust_pkg_detail;
2517 my $cust_bill_pkg = new FS::cust_bill_pkg {
2518 'pkgnum' => $cust_pkg->pkgnum,
2520 'unitsetup' => $unitsetup,
2522 'unitrecur' => $unitrecur,
2523 'quantity' => $cust_pkg->quantity,
2524 'details' => \@details,
2527 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
2528 $cust_bill_pkg->sdate( $hash{last_bill} );
2529 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2530 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
2531 $cust_bill_pkg->sdate( $sdate );
2532 $cust_bill_pkg->edate( $cust_pkg->bill );
2535 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2536 unless $part_pkg->pkgpart == $real_pkgpart;
2538 $$total_setup += $setup;
2539 $$total_recur += $recur;
2546 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg);
2547 return $error if $error;
2549 push @$cust_bill_pkgs, $cust_bill_pkg;
2551 } #if $setup != 0 || $recur != 0
2561 my $part_pkg = shift;
2562 my $taxlisthash = shift;
2563 my $cust_bill_pkg = shift;
2564 my $cust_pkg = shift;
2566 my %cust_bill_pkg = ();
2570 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2575 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
2576 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
2577 push @classes, 'setup' if $cust_bill_pkg->setup;
2578 push @classes, 'recur' if $cust_bill_pkg->recur;
2580 if ( $conf->exists('enable_taxproducts')
2581 && (scalar($part_pkg->part_pkg_taxoverride) || $part_pkg->has_taxproduct)
2582 && ( $self->tax !~ /Y/i && $self->payby ne 'COMP' )
2586 foreach my $class (@classes) {
2587 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $prefix );
2588 return $err_or_ref unless ref($err_or_ref);
2589 $taxes{$class} = $err_or_ref;
2592 unless (exists $taxes{''}) {
2593 my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $prefix );
2594 return $err_or_ref unless ref($err_or_ref);
2595 $taxes{''} = $err_or_ref;
2598 } elsif ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
2600 my %taxhash = map { $_ => $self->get("$prefix$_") }
2601 qw( state county country );
2603 $taxhash{'taxclass'} = $part_pkg->taxclass;
2605 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2608 $taxhash{'taxclass'} = '';
2609 @taxes = qsearch( 'cust_main_county', \%taxhash );
2612 #one more try at a whole-country tax rate
2614 $taxhash{$_} = '' foreach qw( state county );
2615 @taxes = qsearch( 'cust_main_county', \%taxhash );
2618 $taxes{''} = [ @taxes ];
2619 $taxes{'setup'} = [ @taxes ];
2620 $taxes{'recur'} = [ @taxes ];
2621 $taxes{$_} = [ @taxes ] foreach (@classes);
2623 # maybe eliminate this entirely, along with all the 0% records
2626 "fatal: can't find tax rate for state/county/country/taxclass ".
2627 join('/', ( map $self->get("$prefix$_"),
2628 qw(state county country)
2630 $part_pkg->taxclass ). "\n";
2633 } #if $conf->exists('enable_taxproducts') ...
2636 if ( $conf->exists('separate_usage') ) {
2637 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
2638 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
2639 push @display, new FS::cust_bill_pkg_display { type => 'S' };
2640 push @display, new FS::cust_bill_pkg_display { type => 'R' };
2641 push @display, new FS::cust_bill_pkg_display { type => 'U',
2644 if ($section && $summary) {
2645 $display[2]->post_total('Y');
2646 push @display, new FS::cust_bill_pkg_display { type => 'U',
2651 $cust_bill_pkg->set('display', \@display);
2653 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
2654 foreach my $key (keys %tax_cust_bill_pkg) {
2655 my @taxes = @{ $taxes{$key} };
2656 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
2658 foreach my $tax ( @taxes ) {
2659 my $taxname = ref( $tax ). ' '. $tax->taxnum;
2660 if ( exists( $taxlisthash->{ $taxname } ) ) {
2661 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
2663 $taxlisthash->{ $taxname } = [ $tax, $tax_cust_bill_pkg ];
2673 my $part_pkg = shift;
2678 my $geocode = $self->geocode('cch');
2680 my @taxclassnums = map { $_->taxclassnum }
2681 $part_pkg->part_pkg_taxoverride($class);
2683 unless (@taxclassnums) {
2684 @taxclassnums = map { $_->taxclassnum }
2685 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
2687 warn "Found taxclassnum values of ". join(',', @taxclassnums)
2692 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2694 @taxes = qsearch({ 'table' => 'tax_rate',
2695 'hashref' => { 'geocode' => $geocode, },
2696 'extra_sql' => $extra_sql,
2698 if scalar(@taxclassnums);
2700 # maybe eliminate this entirely, along with all the 0% records
2703 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2704 join('/', ( map $self->get("$prefix$_"),
2707 $part_pkg->taxproduct_description,
2708 $part_pkg->pkgpart ). "\n";
2711 warn "Found taxes ".
2712 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
2719 =item collect OPTIONS
2721 (Attempt to) collect money for this customer's outstanding invoices (see
2722 L<FS::cust_bill>). Usually used after the bill method.
2724 Actions are now triggered by billing events; see L<FS::part_event> and the
2725 billing events web interface. Old-style invoice events (see
2726 L<FS::part_bill_event>) have been deprecated.
2728 If there is an error, returns the error, otherwise returns false.
2730 Options are passed as name-value pairs.
2732 Currently available options are:
2738 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.
2742 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2746 set true to surpress email card/ACH decline notices.
2750 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2754 allows for one time override of normal customer billing method
2758 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)
2766 my( $self, %options ) = @_;
2767 my $invoice_time = $options{'invoice_time'} || time;
2770 local $SIG{HUP} = 'IGNORE';
2771 local $SIG{INT} = 'IGNORE';
2772 local $SIG{QUIT} = 'IGNORE';
2773 local $SIG{TERM} = 'IGNORE';
2774 local $SIG{TSTP} = 'IGNORE';
2775 local $SIG{PIPE} = 'IGNORE';
2777 my $oldAutoCommit = $FS::UID::AutoCommit;
2778 local $FS::UID::AutoCommit = 0;
2781 $self->select_for_update; #mutex
2784 my $balance = $self->balance;
2785 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2788 if ( exists($options{'retry_card'}) ) {
2789 carp 'retry_card option passed to collect is deprecated; use retry';
2790 $options{'retry'} ||= $options{'retry_card'};
2792 if ( exists($options{'retry'}) && $options{'retry'} ) {
2793 my $error = $self->retry_realtime;
2795 $dbh->rollback if $oldAutoCommit;
2800 # false laziness w/pay_batch::import_results
2802 my $due_cust_event = $self->due_cust_event(
2803 'debug' => ( $options{'debug'} || 0 ),
2804 'time' => $invoice_time,
2805 'check_freq' => $options{'check_freq'},
2807 unless( ref($due_cust_event) ) {
2808 $dbh->rollback if $oldAutoCommit;
2809 return $due_cust_event;
2812 foreach my $cust_event ( @$due_cust_event ) {
2816 #re-eval event conditions (a previous event could have changed things)
2817 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2818 #don't leave stray "new/locked" records around
2819 my $error = $cust_event->delete;
2821 #gah, even with transactions
2822 $dbh->commit if $oldAutoCommit; #well.
2829 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2830 warn " running cust_event ". $cust_event->eventnum. "\n"
2834 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2835 if ( my $error = $cust_event->do_event() ) {
2836 #XXX wtf is this? figure out a proper dealio with return value
2838 # gah, even with transactions.
2839 $dbh->commit if $oldAutoCommit; #well.
2846 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2851 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2853 Inserts database records for and returns an ordered listref of new events due
2854 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2855 events are due, an empty listref is returned. If there is an error, returns a
2856 scalar error message.
2858 To actually run the events, call each event's test_condition method, and if
2859 still true, call the event's do_event method.
2861 Options are passed as a hashref or as a list of name-value pairs. Available
2868 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.
2872 "Current time" for the events.
2876 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)
2880 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2884 Explicitly pass the objects to be tested (typically used with eventtable).
2890 sub due_cust_event {
2892 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2895 #my $DEBUG = $opt{'debug'}
2896 local($DEBUG) = $opt{'debug'}
2897 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2899 warn "$me due_cust_event called with options ".
2900 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2903 $opt{'time'} ||= time;
2905 local $SIG{HUP} = 'IGNORE';
2906 local $SIG{INT} = 'IGNORE';
2907 local $SIG{QUIT} = 'IGNORE';
2908 local $SIG{TERM} = 'IGNORE';
2909 local $SIG{TSTP} = 'IGNORE';
2910 local $SIG{PIPE} = 'IGNORE';
2912 my $oldAutoCommit = $FS::UID::AutoCommit;
2913 local $FS::UID::AutoCommit = 0;
2916 $self->select_for_update; #mutex
2919 # 1: find possible events (initial search)
2922 my @cust_event = ();
2924 my @eventtable = $opt{'eventtable'}
2925 ? ( $opt{'eventtable'} )
2926 : FS::part_event->eventtables_runorder;
2928 foreach my $eventtable ( @eventtable ) {
2931 if ( $opt{'objects'} ) {
2933 @objects = @{ $opt{'objects'} };
2937 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2938 @objects = ( $eventtable eq 'cust_main' )
2940 : ( $self->$eventtable() );
2944 my @e_cust_event = ();
2946 my $cross = "CROSS JOIN $eventtable";
2947 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2948 unless $eventtable eq 'cust_main';
2950 foreach my $object ( @objects ) {
2952 #this first search uses the condition_sql magic for optimization.
2953 #the more possible events we can eliminate in this step the better
2955 my $cross_where = '';
2956 my $pkey = $object->primary_key;
2957 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2959 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2961 FS::part_event_condition->where_conditions_sql( $eventtable,
2962 'time'=>$opt{'time'}
2964 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2966 $extra_sql = "AND $extra_sql" if $extra_sql;
2968 #here is the agent virtualization
2969 $extra_sql .= " AND ( part_event.agentnum IS NULL
2970 OR part_event.agentnum = ". $self->agentnum. ' )';
2972 $extra_sql .= " $order";
2974 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2975 if $opt{'debug'} > 2;
2976 my @part_event = qsearch( {
2977 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2978 'select' => 'part_event.*',
2979 'table' => 'part_event',
2980 'addl_from' => "$cross $join",
2981 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2982 'eventtable' => $eventtable,
2985 'extra_sql' => "AND $cross_where $extra_sql",
2989 my $pkey = $object->primary_key;
2990 warn " ". scalar(@part_event).
2991 " possible events found for $eventtable ". $object->$pkey(). "\n";
2994 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2998 warn " ". scalar(@e_cust_event).
2999 " subtotal possible cust events found for $eventtable\n"
3002 push @cust_event, @e_cust_event;
3006 warn " ". scalar(@cust_event).
3007 " total possible cust events found in initial search\n"
3011 # 2: test conditions
3016 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
3017 'stats_hashref' => \%unsat ),
3020 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
3023 warn " invalid conditions not eliminated with condition_sql:\n".
3024 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
3031 unless( $opt{testonly} ) {
3032 foreach my $cust_event ( @cust_event ) {
3034 my $error = $cust_event->insert();
3036 $dbh->rollback if $oldAutoCommit;
3043 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3049 warn " returning events: ". Dumper(@cust_event). "\n"
3056 =item retry_realtime
3058 Schedules realtime / batch credit card / electronic check / LEC billing
3059 events for for retry. Useful if card information has changed or manual
3060 retry is desired. The 'collect' method must be called to actually retry
3063 Implementation details: For either this customer, or for each of this
3064 customer's open invoices, changes the status of the first "done" (with
3065 statustext error) realtime processing event to "failed".
3069 sub retry_realtime {
3072 local $SIG{HUP} = 'IGNORE';
3073 local $SIG{INT} = 'IGNORE';
3074 local $SIG{QUIT} = 'IGNORE';
3075 local $SIG{TERM} = 'IGNORE';
3076 local $SIG{TSTP} = 'IGNORE';
3077 local $SIG{PIPE} = 'IGNORE';
3079 my $oldAutoCommit = $FS::UID::AutoCommit;
3080 local $FS::UID::AutoCommit = 0;
3083 #a little false laziness w/due_cust_event (not too bad, really)
3085 my $join = FS::part_event_condition->join_conditions_sql;
3086 my $order = FS::part_event_condition->order_conditions_sql;
3089 . join ( ' OR ' , map {
3090 "( part_event.eventtable = " . dbh->quote($_)
3091 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3092 } FS::part_event->eventtables)
3095 #here is the agent virtualization
3096 my $agent_virt = " ( part_event.agentnum IS NULL
3097 OR part_event.agentnum = ". $self->agentnum. ' )';
3099 #XXX this shouldn't be hardcoded, actions should declare it...
3100 my @realtime_events = qw(
3101 cust_bill_realtime_card
3102 cust_bill_realtime_check
3103 cust_bill_realtime_lec
3107 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3112 my @cust_event = qsearchs({
3113 'table' => 'cust_event',
3114 'select' => 'cust_event.*',
3115 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3116 'hashref' => { 'status' => 'done' },
3117 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3118 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3121 my %seen_invnum = ();
3122 foreach my $cust_event (@cust_event) {
3124 #max one for the customer, one for each open invoice
3125 my $cust_X = $cust_event->cust_X;
3126 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3130 or $cust_event->part_event->eventtable eq 'cust_bill'
3133 my $error = $cust_event->retry;
3135 $dbh->rollback if $oldAutoCommit;
3136 return "error scheduling event for retry: $error";
3141 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3146 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3148 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3149 via a Business::OnlinePayment realtime gateway. See
3150 L<http://420.am/business-onlinepayment> for supported gateways.
3152 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3154 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3156 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3157 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3158 if set, will override the value from the customer record.
3160 I<description> is a free-text field passed to the gateway. It defaults to
3161 "Internet services".
3163 If an I<invnum> is specified, this payment (if successful) is applied to the
3164 specified invoice. If you don't specify an I<invnum> you might want to
3165 call the B<apply_payments> method.
3167 I<quiet> can be set true to surpress email decline notices.
3169 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3170 resulting paynum, if any.
3172 I<payunique> is a unique identifier for this payment.
3174 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3179 my( $self, $method, $amount, %options ) = @_;
3181 warn "$me realtime_bop: $method $amount\n";
3182 warn " $_ => $options{$_}\n" foreach keys %options;
3185 $options{'description'} ||= 'Internet services';
3187 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3189 eval "use Business::OnlinePayment";
3192 my $payinfo = exists($options{'payinfo'})
3193 ? $options{'payinfo'}
3196 my %method2payby = (
3203 # check for banned credit card/ACH
3206 my $ban = qsearchs('banned_pay', {
3207 'payby' => $method2payby{$method},
3208 'payinfo' => md5_base64($payinfo),
3210 return "Banned credit card" if $ban;
3217 if ( $options{'invnum'} ) {
3218 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3219 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3221 map { $_->part_pkg->taxclass }
3223 map { $_->cust_pkg }
3224 $cust_bill->cust_bill_pkg;
3225 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3226 #different taxclasses
3227 $taxclass = $taxclasses[0];
3231 #look for an agent gateway override first
3233 if ( $method eq 'CC' ) {
3234 $cardtype = cardtype($payinfo);
3235 } elsif ( $method eq 'ECHECK' ) {
3238 $cardtype = $method;
3242 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3243 cardtype => $cardtype,
3244 taxclass => $taxclass, } )
3245 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3247 taxclass => $taxclass, } )
3248 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3249 cardtype => $cardtype,
3251 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3253 taxclass => '', } );
3255 my $payment_gateway = '';
3256 my( $processor, $login, $password, $action, @bop_options );
3257 if ( $override ) { #use a payment gateway override
3259 $payment_gateway = $override->payment_gateway;
3261 $processor = $payment_gateway->gateway_module;
3262 $login = $payment_gateway->gateway_username;
3263 $password = $payment_gateway->gateway_password;
3264 $action = $payment_gateway->gateway_action;
3265 @bop_options = $payment_gateway->options;
3267 } else { #use the standard settings from the config
3269 ( $processor, $login, $password, $action, @bop_options ) =
3270 $self->default_payment_gateway($method);
3278 my $address = exists($options{'address1'})
3279 ? $options{'address1'}
3281 my $address2 = exists($options{'address2'})
3282 ? $options{'address2'}
3284 $address .= ", ". $address2 if length($address2);
3286 my $o_payname = exists($options{'payname'})
3287 ? $options{'payname'}
3289 my($payname, $payfirst, $paylast);
3290 if ( $o_payname && $method ne 'ECHECK' ) {
3291 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3292 or return "Illegal payname $payname";
3293 ($payfirst, $paylast) = ($1, $2);
3295 $payfirst = $self->getfield('first');
3296 $paylast = $self->getfield('last');
3297 $payname = "$payfirst $paylast";
3300 my @invoicing_list = $self->invoicing_list_emailonly;
3301 if ( $conf->exists('emailinvoiceautoalways')
3302 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3303 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3304 push @invoicing_list, $self->all_emails;
3307 my $email = ($conf->exists('business-onlinepayment-email-override'))
3308 ? $conf->config('business-onlinepayment-email-override')
3309 : $invoicing_list[0];
3313 my $payip = exists($options{'payip'})
3316 $content{customer_ip} = $payip
3319 $content{invoice_number} = $options{'invnum'}
3320 if exists($options{'invnum'}) && length($options{'invnum'});
3322 $content{email_customer} =
3323 ( $conf->exists('business-onlinepayment-email_customer')
3324 || $conf->exists('business-onlinepayment-email-override') );
3327 if ( $method eq 'CC' ) {
3329 $content{card_number} = $payinfo;
3330 $paydate = exists($options{'paydate'})
3331 ? $options{'paydate'}
3333 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3334 $content{expiration} = "$2/$1";
3336 my $paycvv = exists($options{'paycvv'})
3337 ? $options{'paycvv'}
3339 $content{cvv2} = $paycvv
3342 my $paystart_month = exists($options{'paystart_month'})
3343 ? $options{'paystart_month'}
3344 : $self->paystart_month;
3346 my $paystart_year = exists($options{'paystart_year'})
3347 ? $options{'paystart_year'}
3348 : $self->paystart_year;
3350 $content{card_start} = "$paystart_month/$paystart_year"
3351 if $paystart_month && $paystart_year;
3353 my $payissue = exists($options{'payissue'})
3354 ? $options{'payissue'}
3356 $content{issue_number} = $payissue if $payissue;
3358 $content{recurring_billing} = 'YES'
3359 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3361 'payinfo' => $payinfo,
3363 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3365 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3369 } elsif ( $method eq 'ECHECK' ) {
3370 ( $content{account_number}, $content{routing_code} ) =
3371 split('@', $payinfo);
3372 $content{bank_name} = $o_payname;
3373 $content{bank_state} = exists($options{'paystate'})
3374 ? $options{'paystate'}
3375 : $self->getfield('paystate');
3376 $content{account_type} = exists($options{'paytype'})
3377 ? uc($options{'paytype'}) || 'CHECKING'
3378 : uc($self->getfield('paytype')) || 'CHECKING';
3379 $content{account_name} = $payname;
3380 $content{customer_org} = $self->company ? 'B' : 'I';
3381 $content{state_id} = exists($options{'stateid'})
3382 ? $options{'stateid'}
3383 : $self->getfield('stateid');
3384 $content{state_id_state} = exists($options{'stateid_state'})
3385 ? $options{'stateid_state'}
3386 : $self->getfield('stateid_state');
3387 $content{customer_ssn} = exists($options{'ss'})
3390 } elsif ( $method eq 'LEC' ) {
3391 $content{phone} = $payinfo;
3395 # run transaction(s)
3398 my $balance = exists( $options{'balance'} )
3399 ? $options{'balance'}
3402 $self->select_for_update; #mutex ... just until we get our pending record in
3404 #the checks here are intended to catch concurrent payments
3405 #double-form-submission prevention is taken care of in cust_pay_pending::check
3408 return "The customer's balance has changed; $method transaction aborted."
3409 if $self->balance < $balance;
3410 #&& $self->balance < $amount; #might as well anyway?
3412 #also check and make sure there aren't *other* pending payments for this cust
3414 my @pending = qsearch('cust_pay_pending', {
3415 'custnum' => $self->custnum,
3416 'status' => { op=>'!=', value=>'done' }
3418 return "A payment is already being processed for this customer (".
3419 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3420 "); $method transaction aborted."
3421 if scalar(@pending);
3423 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3425 my $cust_pay_pending = new FS::cust_pay_pending {
3426 'custnum' => $self->custnum,
3427 #'invnum' => $options{'invnum'},
3430 'payby' => $method2payby{$method},
3431 'payinfo' => $payinfo,
3432 'paydate' => $paydate,
3434 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3436 $cust_pay_pending->payunique( $options{payunique} )
3437 if defined($options{payunique}) && length($options{payunique});
3438 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3439 return $cpp_new_err if $cpp_new_err;
3441 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3443 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3444 $transaction->content(
3447 'password' => $password,
3448 'action' => $action1,
3449 'description' => $options{'description'},
3450 'amount' => $amount,
3451 #'invoice_number' => $options{'invnum'},
3452 'customer_id' => $self->custnum,
3453 'last_name' => $paylast,
3454 'first_name' => $payfirst,
3456 'address' => $address,
3457 'city' => ( exists($options{'city'})
3460 'state' => ( exists($options{'state'})
3463 'zip' => ( exists($options{'zip'})
3466 'country' => ( exists($options{'country'})
3467 ? $options{'country'}
3469 'referer' => 'http://cleanwhisker.420.am/',
3471 'phone' => $self->daytime || $self->night,
3475 $cust_pay_pending->status('pending');
3476 my $cpp_pending_err = $cust_pay_pending->replace;
3477 return $cpp_pending_err if $cpp_pending_err;
3480 my $BOP_TESTING = 0;
3481 my $BOP_TESTING_SUCCESS = 1;
3483 unless ( $BOP_TESTING ) {
3484 $transaction->submit();
3486 if ( $BOP_TESTING_SUCCESS ) {
3487 $transaction->is_success(1);
3488 $transaction->authorization('fake auth');
3490 $transaction->is_success(0);
3491 $transaction->error_message('fake failure');
3495 if ( $transaction->is_success() && $action2 ) {
3497 $cust_pay_pending->status('authorized');
3498 my $cpp_authorized_err = $cust_pay_pending->replace;
3499 return $cpp_authorized_err if $cpp_authorized_err;
3501 my $auth = $transaction->authorization;
3502 my $ordernum = $transaction->can('order_number')
3503 ? $transaction->order_number
3507 new Business::OnlinePayment( $processor, @bop_options );
3514 password => $password,
3515 order_number => $ordernum,
3517 authorization => $auth,
3518 description => $options{'description'},
3521 foreach my $field (qw( authorization_source_code returned_ACI
3522 transaction_identifier validation_code
3523 transaction_sequence_num local_transaction_date
3524 local_transaction_time AVS_result_code )) {
3525 $capture{$field} = $transaction->$field() if $transaction->can($field);
3528 $capture->content( %capture );
3532 unless ( $capture->is_success ) {
3533 my $e = "Authorization successful but capture failed, custnum #".
3534 $self->custnum. ': '. $capture->result_code.
3535 ": ". $capture->error_message;
3542 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3543 my $cpp_captured_err = $cust_pay_pending->replace;
3544 return $cpp_captured_err if $cpp_captured_err;
3547 # remove paycvv after initial transaction
3550 #false laziness w/misc/process/payment.cgi - check both to make sure working
3552 if ( defined $self->dbdef_table->column('paycvv')
3553 && length($self->paycvv)
3554 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3556 my $error = $self->remove_cvv;
3558 warn "WARNING: error removing cvv: $error\n";
3566 if ( $transaction->is_success() ) {
3569 if ( $payment_gateway ) { # agent override
3570 $paybatch = $payment_gateway->gatewaynum. '-';
3573 $paybatch .= "$processor:". $transaction->authorization;
3575 $paybatch .= ':'. $transaction->order_number
3576 if $transaction->can('order_number')
3577 && length($transaction->order_number);
3579 my $cust_pay = new FS::cust_pay ( {
3580 'custnum' => $self->custnum,
3581 'invnum' => $options{'invnum'},
3584 'payby' => $method2payby{$method},
3585 'payinfo' => $payinfo,
3586 'paybatch' => $paybatch,
3587 'paydate' => $paydate,
3589 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3590 $cust_pay->payunique( $options{payunique} )
3591 if defined($options{payunique}) && length($options{payunique});
3593 my $oldAutoCommit = $FS::UID::AutoCommit;
3594 local $FS::UID::AutoCommit = 0;
3597 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3599 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3602 $cust_pay->invnum(''); #try again with no specific invnum
3603 my $error2 = $cust_pay->insert( $options{'manual'} ?
3604 ( 'manual' => 1 ) : ()
3607 # gah. but at least we have a record of the state we had to abort in
3608 # from cust_pay_pending now.
3609 my $e = "WARNING: $method captured but payment not recorded - ".
3610 "error inserting payment ($processor): $error2".
3611 " (previously tried insert with invnum #$options{'invnum'}" .
3612 ": $error ) - pending payment saved as paypendingnum ".
3613 $cust_pay_pending->paypendingnum. "\n";
3619 if ( $options{'paynum_ref'} ) {
3620 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3623 $cust_pay_pending->status('done');
3624 $cust_pay_pending->statustext('captured');
3625 my $cpp_done_err = $cust_pay_pending->replace;
3627 if ( $cpp_done_err ) {
3629 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3630 my $e = "WARNING: $method captured but payment not recorded - ".
3631 "error updating status for paypendingnum ".
3632 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3638 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3639 return ''; #no error
3645 my $perror = "$processor error: ". $transaction->error_message;
3647 unless ( $transaction->error_message ) {
3650 if ( $transaction->can('response_page') ) {
3652 'page' => ( $transaction->can('response_page')
3653 ? $transaction->response_page
3656 'code' => ( $transaction->can('response_code')
3657 ? $transaction->response_code
3660 'headers' => ( $transaction->can('response_headers')
3661 ? $transaction->response_headers
3667 "No additional debugging information available for $processor";
3670 $perror .= "No error_message returned from $processor -- ".
3671 ( ref($t_response) ? Dumper($t_response) : $t_response );
3675 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3676 && $conf->exists('emaildecline')
3677 && grep { $_ ne 'POST' } $self->invoicing_list
3678 && ! grep { $transaction->error_message =~ /$_/ }
3679 $conf->config('emaildecline-exclude')
3681 my @templ = $conf->config('declinetemplate');
3682 my $template = new Text::Template (
3684 SOURCE => [ map "$_\n", @templ ],
3685 ) or return "($perror) can't create template: $Text::Template::ERROR";
3686 $template->compile()
3687 or return "($perror) can't compile template: $Text::Template::ERROR";
3689 my $templ_hash = { error => $transaction->error_message };
3691 my $error = send_email(
3692 'from' => $conf->config('invoice_from'),
3693 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3694 'subject' => 'Your payment could not be processed',
3695 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3698 $perror .= " (also received error sending decline notification: $error)"
3703 $cust_pay_pending->status('done');
3704 $cust_pay_pending->statustext("declined: $perror");
3705 my $cpp_done_err = $cust_pay_pending->replace;
3706 if ( $cpp_done_err ) {
3707 my $e = "WARNING: $method declined but pending payment not resolved - ".
3708 "error updating status for paypendingnum ".
3709 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3711 $perror = "$e ($perror)";
3724 my( $self, $method, $amount, %options ) = @_;
3726 if ( $options{'fake_failure'} ) {
3727 return "Error: No error; test failure requested with fake_failure";
3730 my %method2payby = (
3737 #if ( $payment_gateway ) { # agent override
3738 # $paybatch = $payment_gateway->gatewaynum. '-';
3741 #$paybatch .= "$processor:". $transaction->authorization;
3743 #$paybatch .= ':'. $transaction->order_number
3744 # if $transaction->can('order_number')
3745 # && length($transaction->order_number);
3747 my $paybatch = 'FakeProcessor:54:32';
3749 my $cust_pay = new FS::cust_pay ( {
3750 'custnum' => $self->custnum,
3751 'invnum' => $options{'invnum'},
3754 'payby' => $method2payby{$method},
3755 #'payinfo' => $payinfo,
3756 'payinfo' => '4111111111111111',
3757 'paybatch' => $paybatch,
3758 #'paydate' => $paydate,
3759 'paydate' => '2012-05-01',
3761 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3763 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3766 $cust_pay->invnum(''); #try again with no specific invnum
3767 my $error2 = $cust_pay->insert( $options{'manual'} ?
3768 ( 'manual' => 1 ) : ()
3771 # gah, even with transactions.
3772 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3773 "error inserting (fake!) payment: $error2".
3774 " (previously tried insert with invnum #$options{'invnum'}" .
3781 if ( $options{'paynum_ref'} ) {
3782 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3785 return ''; #no error
3789 =item default_payment_gateway
3793 sub default_payment_gateway {
3794 my( $self, $method ) = @_;
3796 die "Real-time processing not enabled\n"
3797 unless $conf->exists('business-onlinepayment');
3800 my $bop_config = 'business-onlinepayment';
3801 $bop_config .= '-ach'
3802 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3803 my ( $processor, $login, $password, $action, @bop_options ) =
3804 $conf->config($bop_config);
3805 $action ||= 'normal authorization';
3806 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3807 die "No real-time processor is enabled - ".
3808 "did you set the business-onlinepayment configuration value?\n"
3811 ( $processor, $login, $password, $action, @bop_options )
3816 Removes the I<paycvv> field from the database directly.
3818 If there is an error, returns the error, otherwise returns false.
3824 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3825 or return dbh->errstr;
3826 $sth->execute($self->custnum)
3827 or return $sth->errstr;
3832 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3834 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3835 via a Business::OnlinePayment realtime gateway. See
3836 L<http://420.am/business-onlinepayment> for supported gateways.
3838 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3840 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3842 Most gateways require a reference to an original payment transaction to refund,
3843 so you probably need to specify a I<paynum>.
3845 I<amount> defaults to the original amount of the payment if not specified.
3847 I<reason> specifies a reason for the refund.
3849 I<paydate> specifies the expiration date for a credit card overriding the
3850 value from the customer record or the payment record. Specified as yyyy-mm-dd
3852 Implementation note: If I<amount> is unspecified or equal to the amount of the
3853 orignal payment, first an attempt is made to "void" the transaction via
3854 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3855 the normal attempt is made to "refund" ("credit") the transaction via the
3856 gateway is attempted.
3858 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3859 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3860 #if set, will override the value from the customer record.
3862 #If an I<invnum> is specified, this payment (if successful) is applied to the
3863 #specified invoice. If you don't specify an I<invnum> you might want to
3864 #call the B<apply_payments> method.
3868 #some false laziness w/realtime_bop, not enough to make it worth merging
3869 #but some useful small subs should be pulled out
3870 sub realtime_refund_bop {
3871 my( $self, $method, %options ) = @_;
3873 warn "$me realtime_refund_bop: $method refund\n";
3874 warn " $_ => $options{$_}\n" foreach keys %options;
3877 eval "use Business::OnlinePayment";
3881 # look up the original payment and optionally a gateway for that payment
3885 my $amount = $options{'amount'};
3887 my( $processor, $login, $password, @bop_options ) ;
3888 my( $auth, $order_number ) = ( '', '', '' );
3890 if ( $options{'paynum'} ) {
3892 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3893 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3894 or return "Unknown paynum $options{'paynum'}";
3895 $amount ||= $cust_pay->paid;
3897 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3898 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3899 $cust_pay->paybatch;
3900 my $gatewaynum = '';
3901 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3903 if ( $gatewaynum ) { #gateway for the payment to be refunded
3905 my $payment_gateway =
3906 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3907 die "payment gateway $gatewaynum not found"
3908 unless $payment_gateway;
3910 $processor = $payment_gateway->gateway_module;
3911 $login = $payment_gateway->gateway_username;
3912 $password = $payment_gateway->gateway_password;
3913 @bop_options = $payment_gateway->options;
3915 } else { #try the default gateway
3917 my( $conf_processor, $unused_action );
3918 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3919 $self->default_payment_gateway($method);
3921 return "processor of payment $options{'paynum'} $processor does not".
3922 " match default processor $conf_processor"
3923 unless $processor eq $conf_processor;
3928 } else { # didn't specify a paynum, so look for agent gateway overrides
3929 # like a normal transaction
3932 if ( $method eq 'CC' ) {
3933 $cardtype = cardtype($self->payinfo);
3934 } elsif ( $method eq 'ECHECK' ) {
3937 $cardtype = $method;
3940 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3941 cardtype => $cardtype,
3943 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3945 taxclass => '', } );
3947 if ( $override ) { #use a payment gateway override
3949 my $payment_gateway = $override->payment_gateway;
3951 $processor = $payment_gateway->gateway_module;
3952 $login = $payment_gateway->gateway_username;
3953 $password = $payment_gateway->gateway_password;
3954 #$action = $payment_gateway->gateway_action;
3955 @bop_options = $payment_gateway->options;
3957 } else { #use the standard settings from the config
3960 ( $processor, $login, $password, $unused_action, @bop_options ) =
3961 $self->default_payment_gateway($method);
3966 return "neither amount nor paynum specified" unless $amount;
3971 'password' => $password,
3972 'order_number' => $order_number,
3973 'amount' => $amount,
3974 'referer' => 'http://cleanwhisker.420.am/',
3976 $content{authorization} = $auth
3977 if length($auth); #echeck/ACH transactions have an order # but no auth
3978 #(at least with authorize.net)
3980 my $disable_void_after;
3981 if ($conf->exists('disable_void_after')
3982 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3983 $disable_void_after = $1;
3986 #first try void if applicable
3987 if ( $cust_pay && $cust_pay->paid == $amount
3989 ( not defined($disable_void_after) )
3990 || ( time < ($cust_pay->_date + $disable_void_after ) )
3993 warn " attempting void\n" if $DEBUG > 1;
3994 my $void = new Business::OnlinePayment( $processor, @bop_options );
3995 $void->content( 'action' => 'void', %content );
3997 if ( $void->is_success ) {
3998 my $error = $cust_pay->void($options{'reason'});
4000 # gah, even with transactions.
4001 my $e = 'WARNING: Card/ACH voided but database not updated - '.
4002 "error voiding payment: $error";
4006 warn " void successful\n" if $DEBUG > 1;
4011 warn " void unsuccessful, trying refund\n"
4015 my $address = $self->address1;
4016 $address .= ", ". $self->address2 if $self->address2;
4018 my($payname, $payfirst, $paylast);
4019 if ( $self->payname && $method ne 'ECHECK' ) {
4020 $payname = $self->payname;
4021 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4022 or return "Illegal payname $payname";
4023 ($payfirst, $paylast) = ($1, $2);
4025 $payfirst = $self->getfield('first');
4026 $paylast = $self->getfield('last');
4027 $payname = "$payfirst $paylast";
4030 my @invoicing_list = $self->invoicing_list_emailonly;
4031 if ( $conf->exists('emailinvoiceautoalways')
4032 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4033 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4034 push @invoicing_list, $self->all_emails;
4037 my $email = ($conf->exists('business-onlinepayment-email-override'))
4038 ? $conf->config('business-onlinepayment-email-override')
4039 : $invoicing_list[0];
4041 my $payip = exists($options{'payip'})
4044 $content{customer_ip} = $payip
4048 if ( $method eq 'CC' ) {
4051 $content{card_number} = $payinfo = $cust_pay->payinfo;
4052 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
4053 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
4054 ($content{expiration} = "$2/$1"); # where available
4056 $content{card_number} = $payinfo = $self->payinfo;
4057 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
4058 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4059 $content{expiration} = "$2/$1";
4062 } elsif ( $method eq 'ECHECK' ) {
4065 $payinfo = $cust_pay->payinfo;
4067 $payinfo = $self->payinfo;
4069 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
4070 $content{bank_name} = $self->payname;
4071 $content{account_type} = 'CHECKING';
4072 $content{account_name} = $payname;
4073 $content{customer_org} = $self->company ? 'B' : 'I';
4074 $content{customer_ssn} = $self->ss;
4075 } elsif ( $method eq 'LEC' ) {
4076 $content{phone} = $payinfo = $self->payinfo;
4080 my $refund = new Business::OnlinePayment( $processor, @bop_options );
4081 my %sub_content = $refund->content(
4082 'action' => 'credit',
4083 'customer_id' => $self->custnum,
4084 'last_name' => $paylast,
4085 'first_name' => $payfirst,
4087 'address' => $address,
4088 'city' => $self->city,
4089 'state' => $self->state,
4090 'zip' => $self->zip,
4091 'country' => $self->country,
4093 'phone' => $self->daytime || $self->night,
4096 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
4100 return "$processor error: ". $refund->error_message
4101 unless $refund->is_success();
4103 my %method2payby = (
4109 my $paybatch = "$processor:". $refund->authorization;
4110 $paybatch .= ':'. $refund->order_number
4111 if $refund->can('order_number') && $refund->order_number;
4113 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4114 my @cust_bill_pay = $cust_pay->cust_bill_pay;
4115 last unless @cust_bill_pay;
4116 my $cust_bill_pay = pop @cust_bill_pay;
4117 my $error = $cust_bill_pay->delete;
4121 my $cust_refund = new FS::cust_refund ( {
4122 'custnum' => $self->custnum,
4123 'paynum' => $options{'paynum'},
4124 'refund' => $amount,
4126 'payby' => $method2payby{$method},
4127 'payinfo' => $payinfo,
4128 'paybatch' => $paybatch,
4129 'reason' => $options{'reason'} || 'card or ACH refund',
4131 my $error = $cust_refund->insert;
4133 $cust_refund->paynum(''); #try again with no specific paynum
4134 my $error2 = $cust_refund->insert;
4136 # gah, even with transactions.
4137 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4138 "error inserting refund ($processor): $error2".
4139 " (previously tried insert with paynum #$options{'paynum'}" .
4150 =item batch_card OPTION => VALUE...
4152 Adds a payment for this invoice to the pending credit card batch (see
4153 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4154 runs the payment using a realtime gateway.
4159 my ($self, %options) = @_;
4162 if (exists($options{amount})) {
4163 $amount = $options{amount};
4165 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4167 return '' unless $amount > 0;
4169 my $invnum = delete $options{invnum};
4170 my $payby = $options{invnum} || $self->payby; #dubious
4172 if ($options{'realtime'}) {
4173 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4179 my $oldAutoCommit = $FS::UID::AutoCommit;
4180 local $FS::UID::AutoCommit = 0;
4183 #this needs to handle mysql as well as Pg, like svc_acct.pm
4184 #(make it into a common function if folks need to do batching with mysql)
4185 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4186 or return "Cannot lock pay_batch: " . $dbh->errstr;
4190 'payby' => FS::payby->payby2payment($payby),
4193 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4195 unless ( $pay_batch ) {
4196 $pay_batch = new FS::pay_batch \%pay_batch;
4197 my $error = $pay_batch->insert;
4199 $dbh->rollback if $oldAutoCommit;
4200 die "error creating new batch: $error\n";
4204 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4205 'batchnum' => $pay_batch->batchnum,
4206 'custnum' => $self->custnum,
4209 foreach (qw( address1 address2 city state zip country payby payinfo paydate
4211 $options{$_} = '' unless exists($options{$_});
4214 my $cust_pay_batch = new FS::cust_pay_batch ( {
4215 'batchnum' => $pay_batch->batchnum,
4216 'invnum' => $invnum || 0, # is there a better value?
4217 # this field should be
4219 # cust_bill_pay_batch now
4220 'custnum' => $self->custnum,
4221 'last' => $self->getfield('last'),
4222 'first' => $self->getfield('first'),
4223 'address1' => $options{address1} || $self->address1,
4224 'address2' => $options{address2} || $self->address2,
4225 'city' => $options{city} || $self->city,
4226 'state' => $options{state} || $self->state,
4227 'zip' => $options{zip} || $self->zip,
4228 'country' => $options{country} || $self->country,
4229 'payby' => $options{payby} || $self->payby,
4230 'payinfo' => $options{payinfo} || $self->payinfo,
4231 'exp' => $options{paydate} || $self->paydate,
4232 'payname' => $options{payname} || $self->payname,
4233 'amount' => $amount, # consolidating
4236 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4237 if $old_cust_pay_batch;
4240 if ($old_cust_pay_batch) {
4241 $error = $cust_pay_batch->replace($old_cust_pay_batch)
4243 $error = $cust_pay_batch->insert;
4247 $dbh->rollback if $oldAutoCommit;
4251 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
4252 foreach my $cust_bill ($self->open_cust_bill) {
4253 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4254 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4255 'invnum' => $cust_bill->invnum,
4256 'paybatchnum' => $cust_pay_batch->paybatchnum,
4257 'amount' => $cust_bill->owed,
4260 if ($unapplied >= $cust_bill_pay_batch->amount){
4261 $unapplied -= $cust_bill_pay_batch->amount;
4264 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4265 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4267 $error = $cust_bill_pay_batch->insert;
4269 $dbh->rollback if $oldAutoCommit;
4274 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4280 Returns the total owed for this customer on all invoices
4281 (see L<FS::cust_bill/owed>).
4287 $self->total_owed_date(2145859200); #12/31/2037
4290 =item total_owed_date TIME
4292 Returns the total owed for this customer on all invoices with date earlier than
4293 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4294 see L<Time::Local> and L<Date::Parse> for conversion functions.
4298 sub total_owed_date {
4302 foreach my $cust_bill (
4303 grep { $_->_date <= $time }
4304 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4306 $total_bill += $cust_bill->owed;
4308 sprintf( "%.2f", $total_bill );
4311 =item apply_payments_and_credits
4313 Applies unapplied payments and credits.
4315 In most cases, this new method should be used in place of sequential
4316 apply_payments and apply_credits methods.
4318 If there is an error, returns the error, otherwise returns false.
4322 sub apply_payments_and_credits {
4325 local $SIG{HUP} = 'IGNORE';
4326 local $SIG{INT} = 'IGNORE';
4327 local $SIG{QUIT} = 'IGNORE';
4328 local $SIG{TERM} = 'IGNORE';
4329 local $SIG{TSTP} = 'IGNORE';
4330 local $SIG{PIPE} = 'IGNORE';
4332 my $oldAutoCommit = $FS::UID::AutoCommit;
4333 local $FS::UID::AutoCommit = 0;
4336 $self->select_for_update; #mutex
4338 foreach my $cust_bill ( $self->open_cust_bill ) {
4339 my $error = $cust_bill->apply_payments_and_credits;
4341 $dbh->rollback if $oldAutoCommit;
4342 return "Error applying: $error";
4346 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4351 =item apply_credits OPTION => VALUE ...
4353 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4354 to outstanding invoice balances in chronological order (or reverse
4355 chronological order if the I<order> option is set to B<newest>) and returns the
4356 value of any remaining unapplied credits available for refund (see
4357 L<FS::cust_refund>).
4359 Dies if there is an error.
4367 local $SIG{HUP} = 'IGNORE';
4368 local $SIG{INT} = 'IGNORE';
4369 local $SIG{QUIT} = 'IGNORE';
4370 local $SIG{TERM} = 'IGNORE';
4371 local $SIG{TSTP} = 'IGNORE';
4372 local $SIG{PIPE} = 'IGNORE';
4374 my $oldAutoCommit = $FS::UID::AutoCommit;
4375 local $FS::UID::AutoCommit = 0;
4378 $self->select_for_update; #mutex
4380 unless ( $self->total_credited ) {
4381 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4385 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4386 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4388 my @invoices = $self->open_cust_bill;
4389 @invoices = sort { $b->_date <=> $a->_date } @invoices
4390 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4393 foreach my $cust_bill ( @invoices ) {
4396 if ( !defined($credit) || $credit->credited == 0) {
4397 $credit = pop @credits or last;
4400 if ($cust_bill->owed >= $credit->credited) {
4401 $amount=$credit->credited;
4403 $amount=$cust_bill->owed;
4406 my $cust_credit_bill = new FS::cust_credit_bill ( {
4407 'crednum' => $credit->crednum,
4408 'invnum' => $cust_bill->invnum,
4409 'amount' => $amount,
4411 my $error = $cust_credit_bill->insert;
4413 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4417 redo if ($cust_bill->owed > 0);
4421 my $total_credited = $self->total_credited;
4423 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4425 return $total_credited;
4428 =item apply_payments
4430 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4431 to outstanding invoice balances in chronological order.
4433 #and returns the value of any remaining unapplied payments.
4435 Dies if there is an error.
4439 sub apply_payments {
4442 local $SIG{HUP} = 'IGNORE';
4443 local $SIG{INT} = 'IGNORE';
4444 local $SIG{QUIT} = 'IGNORE';
4445 local $SIG{TERM} = 'IGNORE';
4446 local $SIG{TSTP} = 'IGNORE';
4447 local $SIG{PIPE} = 'IGNORE';
4449 my $oldAutoCommit = $FS::UID::AutoCommit;
4450 local $FS::UID::AutoCommit = 0;
4453 $self->select_for_update; #mutex
4457 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4458 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4460 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4461 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4465 foreach my $cust_bill ( @invoices ) {
4468 if ( !defined($payment) || $payment->unapplied == 0 ) {
4469 $payment = pop @payments or last;
4472 if ( $cust_bill->owed >= $payment->unapplied ) {
4473 $amount = $payment->unapplied;
4475 $amount = $cust_bill->owed;
4478 my $cust_bill_pay = new FS::cust_bill_pay ( {
4479 'paynum' => $payment->paynum,
4480 'invnum' => $cust_bill->invnum,
4481 'amount' => $amount,
4483 my $error = $cust_bill_pay->insert;
4485 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4489 redo if ( $cust_bill->owed > 0);
4493 my $total_unapplied_payments = $self->total_unapplied_payments;
4495 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4497 return $total_unapplied_payments;
4500 =item total_credited
4502 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4503 customer. See L<FS::cust_credit/credited>.
4507 sub total_credited {
4509 my $total_credit = 0;
4510 foreach my $cust_credit ( qsearch('cust_credit', {
4511 'custnum' => $self->custnum,
4513 $total_credit += $cust_credit->credited;
4515 sprintf( "%.2f", $total_credit );
4518 =item total_unapplied_payments
4520 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4521 See L<FS::cust_pay/unapplied>.
4525 sub total_unapplied_payments {
4527 my $total_unapplied = 0;
4528 foreach my $cust_pay ( qsearch('cust_pay', {
4529 'custnum' => $self->custnum,
4531 $total_unapplied += $cust_pay->unapplied;
4533 sprintf( "%.2f", $total_unapplied );
4536 =item total_unapplied_refunds
4538 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4539 customer. See L<FS::cust_refund/unapplied>.
4543 sub total_unapplied_refunds {
4545 my $total_unapplied = 0;
4546 foreach my $cust_refund ( qsearch('cust_refund', {
4547 'custnum' => $self->custnum,
4549 $total_unapplied += $cust_refund->unapplied;
4551 sprintf( "%.2f", $total_unapplied );
4556 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4557 total_credited minus total_unapplied_payments).
4565 + $self->total_unapplied_refunds
4566 - $self->total_credited
4567 - $self->total_unapplied_payments
4571 =item balance_date TIME
4573 Returns the balance for this customer, only considering invoices with date
4574 earlier than TIME (total_owed_date minus total_credited minus
4575 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4576 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4585 $self->total_owed_date($time)
4586 + $self->total_unapplied_refunds
4587 - $self->total_credited
4588 - $self->total_unapplied_payments
4592 =item in_transit_payments
4594 Returns the total of requests for payments for this customer pending in
4595 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4599 sub in_transit_payments {
4601 my $in_transit_payments = 0;
4602 foreach my $pay_batch ( qsearch('pay_batch', {
4605 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4606 'batchnum' => $pay_batch->batchnum,
4607 'custnum' => $self->custnum,
4609 $in_transit_payments += $cust_pay_batch->amount;
4612 sprintf( "%.2f", $in_transit_payments );
4615 =item paydate_monthyear
4617 Returns a two-element list consisting of the month and year of this customer's
4618 paydate (credit card expiration date for CARD customers)
4622 sub paydate_monthyear {
4624 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4626 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4633 =item invoicing_list [ ARRAYREF ]
4635 If an arguement is given, sets these email addresses as invoice recipients
4636 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4637 (except as warnings), so use check_invoicing_list first.
4639 Returns a list of email addresses (with svcnum entries expanded).
4641 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4642 check it without disturbing anything by passing nothing.
4644 This interface may change in the future.
4648 sub invoicing_list {
4649 my( $self, $arrayref ) = @_;
4652 my @cust_main_invoice;
4653 if ( $self->custnum ) {
4654 @cust_main_invoice =
4655 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4657 @cust_main_invoice = ();
4659 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4660 #warn $cust_main_invoice->destnum;
4661 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4662 #warn $cust_main_invoice->destnum;
4663 my $error = $cust_main_invoice->delete;
4664 warn $error if $error;
4667 if ( $self->custnum ) {
4668 @cust_main_invoice =
4669 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4671 @cust_main_invoice = ();
4673 my %seen = map { $_->address => 1 } @cust_main_invoice;
4674 foreach my $address ( @{$arrayref} ) {
4675 next if exists $seen{$address} && $seen{$address};
4676 $seen{$address} = 1;
4677 my $cust_main_invoice = new FS::cust_main_invoice ( {
4678 'custnum' => $self->custnum,
4681 my $error = $cust_main_invoice->insert;
4682 warn $error if $error;
4686 if ( $self->custnum ) {
4688 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4695 =item check_invoicing_list ARRAYREF
4697 Checks these arguements as valid input for the invoicing_list method. If there
4698 is an error, returns the error, otherwise returns false.
4702 sub check_invoicing_list {
4703 my( $self, $arrayref ) = @_;
4705 foreach my $address ( @$arrayref ) {
4707 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4708 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4711 my $cust_main_invoice = new FS::cust_main_invoice ( {
4712 'custnum' => $self->custnum,
4715 my $error = $self->custnum
4716 ? $cust_main_invoice->check
4717 : $cust_main_invoice->checkdest
4719 return $error if $error;
4723 return "Email address required"
4724 if $conf->exists('cust_main-require_invoicing_list_email')
4725 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4730 =item set_default_invoicing_list
4732 Sets the invoicing list to all accounts associated with this customer,
4733 overwriting any previous invoicing list.
4737 sub set_default_invoicing_list {
4739 $self->invoicing_list($self->all_emails);
4744 Returns the email addresses of all accounts provisioned for this customer.
4751 foreach my $cust_pkg ( $self->all_pkgs ) {
4752 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4754 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4755 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4757 $list{$_}=1 foreach map { $_->email } @svc_acct;
4762 =item invoicing_list_addpost
4764 Adds postal invoicing to this customer. If this customer is already configured
4765 to receive postal invoices, does nothing.
4769 sub invoicing_list_addpost {
4771 return if grep { $_ eq 'POST' } $self->invoicing_list;
4772 my @invoicing_list = $self->invoicing_list;
4773 push @invoicing_list, 'POST';
4774 $self->invoicing_list(\@invoicing_list);
4777 =item invoicing_list_emailonly
4779 Returns the list of email invoice recipients (invoicing_list without non-email
4780 destinations such as POST and FAX).
4784 sub invoicing_list_emailonly {
4786 warn "$me invoicing_list_emailonly called"
4788 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4791 =item invoicing_list_emailonly_scalar
4793 Returns the list of email invoice recipients (invoicing_list without non-email
4794 destinations such as POST and FAX) as a comma-separated scalar.
4798 sub invoicing_list_emailonly_scalar {
4800 warn "$me invoicing_list_emailonly_scalar called"
4802 join(', ', $self->invoicing_list_emailonly);
4805 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4807 Returns an array of customers referred by this customer (referral_custnum set
4808 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4809 customers referred by customers referred by this customer and so on, inclusive.
4810 The default behavior is DEPTH 1 (no recursion).
4814 sub referral_cust_main {
4816 my $depth = @_ ? shift : 1;
4817 my $exclude = @_ ? shift : {};
4820 map { $exclude->{$_->custnum}++; $_; }
4821 grep { ! $exclude->{ $_->custnum } }
4822 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4826 map { $_->referral_cust_main($depth-1, $exclude) }
4833 =item referral_cust_main_ncancelled
4835 Same as referral_cust_main, except only returns customers with uncancelled
4840 sub referral_cust_main_ncancelled {
4842 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4845 =item referral_cust_pkg [ DEPTH ]
4847 Like referral_cust_main, except returns a flat list of all unsuspended (and
4848 uncancelled) packages for each customer. The number of items in this list may
4849 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4853 sub referral_cust_pkg {
4855 my $depth = @_ ? shift : 1;
4857 map { $_->unsuspended_pkgs }
4858 grep { $_->unsuspended_pkgs }
4859 $self->referral_cust_main($depth);
4862 =item referring_cust_main
4864 Returns the single cust_main record for the customer who referred this customer
4865 (referral_custnum), or false.
4869 sub referring_cust_main {
4871 return '' unless $self->referral_custnum;
4872 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4875 =item credit AMOUNT, REASON
4877 Applies a credit to this customer. If there is an error, returns the error,
4878 otherwise returns false.
4883 my( $self, $amount, $reason, %options ) = @_;
4884 my $cust_credit = new FS::cust_credit {
4885 'custnum' => $self->custnum,
4886 'amount' => $amount,
4887 'reason' => $reason,
4889 $cust_credit->insert(%options);
4892 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4894 Creates a one-time charge for this customer. If there is an error, returns
4895 the error, otherwise returns false.
4901 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4902 my ( $taxproduct, $override );
4903 if ( ref( $_[0] ) ) {
4904 $amount = $_[0]->{amount};
4905 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4906 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4907 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4908 : '$'. sprintf("%.2f",$amount);
4909 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4910 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4911 $additional = $_[0]->{additional};
4912 $taxproduct = $_[0]->{taxproductnum};
4913 $override = { '' => $_[0]->{tax_override} };
4917 $pkg = @_ ? shift : 'One-time charge';
4918 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4919 $taxclass = @_ ? shift : '';
4923 local $SIG{HUP} = 'IGNORE';
4924 local $SIG{INT} = 'IGNORE';
4925 local $SIG{QUIT} = 'IGNORE';
4926 local $SIG{TERM} = 'IGNORE';
4927 local $SIG{TSTP} = 'IGNORE';
4928 local $SIG{PIPE} = 'IGNORE';
4930 my $oldAutoCommit = $FS::UID::AutoCommit;
4931 local $FS::UID::AutoCommit = 0;
4934 my $part_pkg = new FS::part_pkg ( {
4936 'comment' => $comment,
4940 'classnum' => $classnum ? $classnum : '',
4941 'taxclass' => $taxclass,
4942 'taxproductnum' => $taxproduct,
4945 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4946 ( 0 .. @$additional - 1 )
4948 'additional_count' => scalar(@$additional),
4949 'setup_fee' => $amount,
4952 my $error = $part_pkg->insert( options => \%options,
4953 tax_overrides => $override,
4956 $dbh->rollback if $oldAutoCommit;
4960 my $pkgpart = $part_pkg->pkgpart;
4961 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4962 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4963 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4964 $error = $type_pkgs->insert;
4966 $dbh->rollback if $oldAutoCommit;
4971 my $cust_pkg = new FS::cust_pkg ( {
4972 'custnum' => $self->custnum,
4973 'pkgpart' => $pkgpart,
4974 'quantity' => $quantity,
4977 $error = $cust_pkg->insert;
4979 $dbh->rollback if $oldAutoCommit;
4983 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4988 #=item charge_postal_fee
4990 #Applies a one time charge this customer. If there is an error,
4991 #returns the error, returns the cust_pkg charge object or false
4992 #if there was no charge.
4996 # This should be a customer event. For that to work requires that bill
4997 # also be a customer event.
4999 sub charge_postal_fee {
5002 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
5003 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
5005 my $cust_pkg = new FS::cust_pkg ( {
5006 'custnum' => $self->custnum,
5007 'pkgpart' => $pkgpart,
5011 my $error = $cust_pkg->insert;
5012 $error ? $error : $cust_pkg;
5017 Returns all the invoices (see L<FS::cust_bill>) for this customer.
5023 sort { $a->_date <=> $b->_date }
5024 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
5027 =item open_cust_bill
5029 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
5034 sub open_cust_bill {
5036 grep { $_->owed > 0 } $self->cust_bill;
5041 Returns all the credits (see L<FS::cust_credit>) for this customer.
5047 sort { $a->_date <=> $b->_date }
5048 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
5053 Returns all the payments (see L<FS::cust_pay>) for this customer.
5059 sort { $a->_date <=> $b->_date }
5060 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
5065 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
5071 sort { $a->_date <=> $b->_date }
5072 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
5075 =item cust_pay_batch
5077 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
5081 sub cust_pay_batch {
5083 sort { $a->_date <=> $b->_date }
5084 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
5089 Returns all the refunds (see L<FS::cust_refund>) for this customer.
5095 sort { $a->_date <=> $b->_date }
5096 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
5099 =item display_custnum
5101 Returns the displayed customer number for this customer: agent_custid if
5102 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
5106 sub display_custnum {
5108 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
5109 return $self->agent_custid;
5111 return $self->custnum;
5117 Returns a name string for this customer, either "Company (Last, First)" or
5124 my $name = $self->contact;
5125 $name = $self->company. " ($name)" if $self->company;
5131 Returns a name string for this (service/shipping) contact, either
5132 "Company (Last, First)" or "Last, First".
5138 if ( $self->get('ship_last') ) {
5139 my $name = $self->ship_contact;
5140 $name = $self->ship_company. " ($name)" if $self->ship_company;
5149 Returns this customer's full (billing) contact name only, "Last, First"
5155 $self->get('last'). ', '. $self->first;
5160 Returns this customer's full (shipping) contact name only, "Last, First"
5166 $self->get('ship_last')
5167 ? $self->get('ship_last'). ', '. $self->ship_first
5173 Returns this customer's full country name
5179 code2country($self->country);
5182 =item geocode DATA_VENDOR
5184 Returns a value for the customer location as encoded by DATA_VENDOR.
5185 Currently this only makes sense for "CCH" as DATA_VENDOR.
5190 my ($self, $data_vendor) = (shift, shift); #always cch for now
5192 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5196 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5197 if $self->country eq 'US';
5199 #CCH specific location stuff
5200 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5203 my @cust_tax_location =
5205 'table' => 'cust_tax_location',
5206 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5207 'extra_sql' => $extra_sql,
5208 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
5211 $geocode = $cust_tax_location[0]->geocode
5212 if scalar(@cust_tax_location);
5221 Returns a status string for this customer, currently:
5225 =item prospect - No packages have ever been ordered
5227 =item active - One or more recurring packages is active
5229 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5231 =item suspended - All non-cancelled recurring packages are suspended
5233 =item cancelled - All recurring packages are cancelled
5239 sub status { shift->cust_status(@_); }
5243 for my $status (qw( prospect active inactive suspended cancelled )) {
5244 my $method = $status.'_sql';
5245 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5246 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5247 $sth->execute( ($self->custnum) x $numnum )
5248 or die "Error executing 'SELECT $sql': ". $sth->errstr;
5249 return $status if $sth->fetchrow_arrayref->[0];
5253 =item ucfirst_cust_status
5255 =item ucfirst_status
5257 Returns the status with the first character capitalized.
5261 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5263 sub ucfirst_cust_status {
5265 ucfirst($self->cust_status);
5270 Returns a hex triplet color string for this customer's status.
5274 use vars qw(%statuscolor);
5275 tie %statuscolor, 'Tie::IxHash',
5276 'prospect' => '7e0079', #'000000', #black? naw, purple
5277 'active' => '00CC00', #green
5278 'inactive' => '0000CC', #blue
5279 'suspended' => 'FF9900', #yellow
5280 'cancelled' => 'FF0000', #red
5283 sub statuscolor { shift->cust_statuscolor(@_); }
5285 sub cust_statuscolor {
5287 $statuscolor{$self->cust_status};
5292 Returns an array of hashes representing the customer's RT tickets.
5299 my $num = $conf->config('cust_main-max_tickets') || 10;
5302 unless ( $conf->config('ticket_system-custom_priority_field') ) {
5304 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5308 foreach my $priority (
5309 $conf->config('ticket_system-custom_priority_field-values'), ''
5311 last if scalar(@tickets) >= $num;
5313 @{ FS::TicketSystem->customer_tickets( $self->custnum,
5314 $num - scalar(@tickets),
5323 # Return services representing svc_accts in customer support packages
5324 sub support_services {
5326 my %packages = map { $_ => 1 } $conf->config('support_packages');
5328 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5329 grep { $_->part_svc->svcdb eq 'svc_acct' }
5330 map { $_->cust_svc }
5331 grep { exists $packages{ $_->pkgpart } }
5332 $self->ncancelled_pkgs;
5338 =head1 CLASS METHODS
5344 Class method that returns the list of possible status strings for customers
5345 (see L<the status method|/status>). For example:
5347 @statuses = FS::cust_main->statuses();
5352 #my $self = shift; #could be class...
5358 Returns an SQL expression identifying prospective cust_main records (customers
5359 with no packages ever ordered)
5363 use vars qw($select_count_pkgs);
5364 $select_count_pkgs =
5365 "SELECT COUNT(*) FROM cust_pkg
5366 WHERE cust_pkg.custnum = cust_main.custnum";
5368 sub select_count_pkgs_sql {
5372 sub prospect_sql { "
5373 0 = ( $select_count_pkgs )
5378 Returns an SQL expression identifying active cust_main records (customers with
5379 active recurring packages).
5384 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5390 Returns an SQL expression identifying inactive cust_main records (customers with
5391 no active recurring packages, but otherwise unsuspended/uncancelled).
5395 sub inactive_sql { "
5396 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5398 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5404 Returns an SQL expression identifying suspended cust_main records.
5409 sub suspended_sql { susp_sql(@_); }
5411 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5413 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5419 Returns an SQL expression identifying cancelled cust_main records.
5423 sub cancelled_sql { cancel_sql(@_); }
5426 my $recurring_sql = FS::cust_pkg->recurring_sql;
5427 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5430 0 < ( $select_count_pkgs )
5431 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
5432 AND 0 = ( $select_count_pkgs AND $recurring_sql
5433 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5435 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5441 =item uncancelled_sql
5443 Returns an SQL expression identifying un-cancelled cust_main records.
5447 sub uncancelled_sql { uncancel_sql(@_); }
5448 sub uncancel_sql { "
5449 ( 0 < ( $select_count_pkgs
5450 AND ( cust_pkg.cancel IS NULL
5451 OR cust_pkg.cancel = 0
5454 OR 0 = ( $select_count_pkgs )
5460 Returns an SQL fragment to retreive the balance.
5465 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5466 WHERE cust_bill.custnum = cust_main.custnum )
5467 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5468 WHERE cust_pay.custnum = cust_main.custnum )
5469 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5470 WHERE cust_credit.custnum = cust_main.custnum )
5471 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5472 WHERE cust_refund.custnum = cust_main.custnum )
5475 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5477 Returns an SQL fragment to retreive the balance for this customer, only
5478 considering invoices with date earlier than START_TIME, and optionally not
5479 later than END_TIME (total_owed_date minus total_credited minus
5480 total_unapplied_payments).
5482 Times are specified as SQL fragments or numeric
5483 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5484 L<Date::Parse> for conversion functions. The empty string can be passed
5485 to disable that time constraint completely.
5487 Available options are:
5491 =item unapplied_date
5493 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)
5498 set to true to remove all customer comparison clauses, for totals
5503 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5508 JOIN clause (typically used with the total option)
5514 sub balance_date_sql {
5515 my( $class, $start, $end, %opt ) = @_;
5517 my $owed = FS::cust_bill->owed_sql;
5518 my $unapp_refund = FS::cust_refund->unapplied_sql;
5519 my $unapp_credit = FS::cust_credit->unapplied_sql;
5520 my $unapp_pay = FS::cust_pay->unapplied_sql;
5522 my $j = $opt{'join'} || '';
5524 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5525 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5526 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5527 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5529 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5530 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5531 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5532 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5537 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5539 Helper method for balance_date_sql; name (and usage) subject to change
5540 (suggestions welcome).
5542 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5543 cust_refund, cust_credit or cust_pay).
5545 If TABLE is "cust_bill" or the unapplied_date option is true, only
5546 considers records with date earlier than START_TIME, and optionally not
5547 later than END_TIME .
5551 sub _money_table_where {
5552 my( $class, $table, $start, $end, %opt ) = @_;
5555 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5556 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5557 push @where, "$table._date <= $start" if defined($start) && length($start);
5558 push @where, "$table._date > $end" if defined($end) && length($end);
5560 push @where, @{$opt{'where'}} if $opt{'where'};
5561 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5567 =item search_sql HASHREF
5571 Returns a qsearch hash expression to search for parameters specified in HREF.
5572 Valid parameters are
5580 =item cancelled_pkgs
5586 listref of start date, end date
5592 =item current_balance
5594 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5598 =item flattened_pkgs
5607 my ($class, $params) = @_;
5618 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5620 "cust_main.agentnum = $1";
5627 #prospect active inactive suspended cancelled
5628 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5629 my $method = $params->{'status'}. '_sql';
5630 #push @where, $class->$method();
5631 push @where, FS::cust_main->$method();
5635 # parse cancelled package checkbox
5640 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5641 unless $params->{'cancelled_pkgs'};
5647 foreach my $field (qw( signupdate )) {
5649 next unless exists($params->{$field});
5651 my($beginning, $ending) = @{$params->{$field}};
5654 "cust_main.$field IS NOT NULL",
5655 "cust_main.$field >= $beginning",
5656 "cust_main.$field <= $ending";
5658 $orderby ||= "ORDER BY cust_main.$field";
5666 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5668 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5675 #my $balance_sql = $class->balance_sql();
5676 my $balance_sql = FS::cust_main->balance_sql();
5678 push @where, map { s/current_balance/$balance_sql/; $_ }
5679 @{ $params->{'current_balance'} };
5685 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
5687 "cust_main.custbatch = '$1'";
5691 # setup queries, subs, etc. for the search
5694 $orderby ||= 'ORDER BY custnum';
5696 # here is the agent virtualization
5697 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5699 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5701 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5703 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5705 my $select = join(', ',
5706 'cust_main.custnum',
5707 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5710 my(@extra_headers) = ();
5711 my(@extra_fields) = ();
5713 if ($params->{'flattened_pkgs'}) {
5715 if ($dbh->{Driver}->{Name} eq 'Pg') {
5717 $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";
5719 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5720 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5721 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5723 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5724 "omitting packing information from report.";
5727 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";
5729 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5730 $sth->execute() or die $sth->errstr;
5731 my $headerrow = $sth->fetchrow_arrayref;
5732 my $headercount = $headerrow ? $headerrow->[0] : 0;
5733 while($headercount) {
5734 unshift @extra_headers, "Package ". $headercount;
5735 unshift @extra_fields, eval q!sub {my $c = shift;
5736 my @a = split '\|', $c->magic;
5737 my $p = $a[!.--$headercount. q!];
5745 'table' => 'cust_main',
5746 'select' => $select,
5748 'extra_sql' => $extra_sql,
5749 'order_by' => $orderby,
5750 'count_query' => $count_query,
5751 'extra_headers' => \@extra_headers,
5752 'extra_fields' => \@extra_fields,
5757 =item email_search_sql HASHREF
5761 Emails a notice to the specified customers.
5763 Valid parameters are those of the L<search_sql> method, plus the following:
5785 Optional job queue job for status updates.
5789 Returns an error message, or false for success.
5791 If an error occurs during any email, stops the enture send and returns that
5792 error. Presumably if you're getting SMTP errors aborting is better than
5793 retrying everything.
5797 sub email_search_sql {
5798 my($class, $params) = @_;
5800 my $from = delete $params->{from};
5801 my $subject = delete $params->{subject};
5802 my $html_body = delete $params->{html_body};
5803 my $text_body = delete $params->{text_body};
5805 my $job = delete $params->{'job'};
5807 my $sql_query = $class->search_sql($params);
5809 my $count_query = delete($sql_query->{'count_query'});
5810 my $count_sth = dbh->prepare($count_query)
5811 or die "Error preparing $count_query: ". dbh->errstr;
5813 or die "Error executing $count_query: ". $count_sth->errstr;
5814 my $count_arrayref = $count_sth->fetchrow_arrayref;
5815 my $num_cust = $count_arrayref->[0];
5817 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5818 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5821 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5823 #eventually order+limit magic to reduce memory use?
5824 foreach my $cust_main ( qsearch($sql_query) ) {
5826 my $to = $cust_main->invoicing_list_emailonly_scalar;
5829 my $error = send_email(
5833 'subject' => $subject,
5834 'html_body' => $html_body,
5835 'text_body' => $text_body,
5838 return $error if $error;
5840 if ( $job ) { #progressbar foo
5842 if ( time - $min_sec > $last ) {
5843 my $error = $job->update_statustext(
5844 int( 100 * $num / $num_cust )
5846 die $error if $error;
5856 use Storable qw(thaw);
5859 sub process_email_search_sql {
5861 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5863 my $param = thaw(decode_base64(shift));
5864 warn Dumper($param) if $DEBUG;
5866 $param->{'job'} = $job;
5868 my $error = FS::cust_main->email_search_sql( $param );
5869 die $error if $error;
5873 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5875 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5876 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5877 appropriate ship_ field is also searched).
5879 Additional options are the same as FS::Record::qsearch
5884 my( $self, $fuzzy, $hash, @opt) = @_;
5889 check_and_rebuild_fuzzyfiles();
5890 foreach my $field ( keys %$fuzzy ) {
5892 my $all = $self->all_X($field);
5893 next unless scalar(@$all);
5896 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5899 foreach ( keys %match ) {
5900 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5901 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5904 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5907 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5909 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5917 Returns a masked version of the named field
5922 my ($self,$field) = @_;
5926 'x'x(length($self->getfield($field))-4).
5927 substr($self->getfield($field), (length($self->getfield($field))-4));
5937 =item smart_search OPTION => VALUE ...
5939 Accepts the following options: I<search>, the string to search for. The string
5940 will be searched for as a customer number, phone number, name or company name,
5941 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5942 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5943 skip fuzzy matching when an exact match is found.
5945 Any additional options are treated as an additional qualifier on the search
5948 Returns a (possibly empty) array of FS::cust_main objects.
5955 #here is the agent virtualization
5956 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5960 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5961 my $search = delete $options{'search'};
5962 ( my $alphanum_search = $search ) =~ s/\W//g;
5964 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5966 #false laziness w/Record::ut_phone
5967 my $phonen = "$1-$2-$3";
5968 $phonen .= " x$4" if $4;
5970 push @cust_main, qsearch( {
5971 'table' => 'cust_main',
5972 'hashref' => { %options },
5973 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5975 join(' OR ', map "$_ = '$phonen'",
5976 qw( daytime night fax
5977 ship_daytime ship_night ship_fax )
5980 " AND $agentnums_sql", #agent virtualization
5983 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5984 #try looking for matches with extensions unless one was specified
5986 push @cust_main, qsearch( {
5987 'table' => 'cust_main',
5988 'hashref' => { %options },
5989 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5991 join(' OR ', map "$_ LIKE '$phonen\%'",
5993 ship_daytime ship_night )
5996 " AND $agentnums_sql", #agent virtualization
6001 # custnum search (also try agent_custid), with some tweaking options if your
6002 # legacy cust "numbers" have letters
6005 if ( $search =~ /^\s*(\d+)\s*$/
6006 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
6007 && $search =~ /^\s*(\w\w?\d+)\s*$/
6014 if ( $num <= 2147483647 ) { #need a bigint custnum? wow.
6015 push @cust_main, qsearch( {
6016 'table' => 'cust_main',
6017 'hashref' => { 'custnum' => $num, %options },
6018 'extra_sql' => " AND $agentnums_sql", #agent virtualization
6022 push @cust_main, qsearch( {
6023 'table' => 'cust_main',
6024 'hashref' => { 'agent_custid' => $num, %options },
6025 'extra_sql' => " AND $agentnums_sql", #agent virtualization
6028 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
6030 my($company, $last, $first) = ( $1, $2, $3 );
6032 # "Company (Last, First)"
6033 #this is probably something a browser remembered,
6034 #so just do an exact search
6036 foreach my $prefix ( '', 'ship_' ) {
6037 push @cust_main, qsearch( {
6038 'table' => 'cust_main',
6039 'hashref' => { $prefix.'first' => $first,
6040 $prefix.'last' => $last,
6041 $prefix.'company' => $company,
6044 'extra_sql' => " AND $agentnums_sql",
6048 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
6049 # try (ship_){last,company}
6053 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
6054 # # full strings the browser remembers won't work
6055 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
6057 use Lingua::EN::NameParse;
6058 my $NameParse = new Lingua::EN::NameParse(
6060 allow_reversed => 1,
6063 my($last, $first) = ( '', '' );
6064 #maybe disable this too and just rely on NameParse?
6065 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
6067 ($last, $first) = ( $1, $2 );
6069 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
6070 } elsif ( ! $NameParse->parse($value) ) {
6072 my %name = $NameParse->components;
6073 $first = $name{'given_name_1'};
6074 $last = $name{'surname_1'};
6078 if ( $first && $last ) {
6080 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
6083 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6085 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
6086 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
6089 push @cust_main, qsearch( {
6090 'table' => 'cust_main',
6091 'hashref' => \%options,
6092 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6095 # or it just be something that was typed in... (try that in a sec)
6099 my $q_value = dbh->quote($value);
6102 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6103 $sql .= " ( LOWER(last) = $q_value
6104 OR LOWER(company) = $q_value
6105 OR LOWER(ship_last) = $q_value
6106 OR LOWER(ship_company) = $q_value
6109 push @cust_main, qsearch( {
6110 'table' => 'cust_main',
6111 'hashref' => \%options,
6112 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6115 #no exact match, trying substring/fuzzy
6116 #always do substring & fuzzy (unless they're explicity config'ed off)
6117 #getting complaints searches are not returning enough
6118 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
6120 #still some false laziness w/search_sql (was search/cust_main.cgi)
6125 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
6126 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
6129 if ( $first && $last ) {
6132 { 'first' => { op=>'ILIKE', value=>"%$first%" },
6133 'last' => { op=>'ILIKE', value=>"%$last%" },
6135 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
6136 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
6143 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
6144 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
6148 foreach my $hashref ( @hashrefs ) {
6150 push @cust_main, qsearch( {
6151 'table' => 'cust_main',
6152 'hashref' => { %$hashref,
6155 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6164 " AND $agentnums_sql", #extra_sql #agent virtualization
6167 if ( $first && $last ) {
6168 push @cust_main, FS::cust_main->fuzzy_search(
6169 { 'last' => $last, #fuzzy hashref
6170 'first' => $first }, #
6174 foreach my $field ( 'last', 'company' ) {
6176 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6181 #eliminate duplicates
6183 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6193 Accepts the following options: I<email>, the email address to search for. The
6194 email address will be searched for as an email invoice destination and as an
6197 #Any additional options are treated as an additional qualifier on the search
6198 #(i.e. I<agentnum>).
6200 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6210 my $email = delete $options{'email'};
6212 #we're only being used by RT at the moment... no agent virtualization yet
6213 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6217 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6219 my ( $user, $domain ) = ( $1, $2 );
6221 warn "$me smart_search: searching for $user in domain $domain"
6227 'table' => 'cust_main_invoice',
6228 'hashref' => { 'dest' => $email },
6235 map $_->cust_svc->cust_pkg,
6237 'table' => 'svc_acct',
6238 'hashref' => { 'username' => $user, },
6240 'AND ( SELECT domain FROM svc_domain
6241 WHERE svc_acct.domsvc = svc_domain.svcnum
6242 ) = '. dbh->quote($domain),
6248 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6250 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6257 =item check_and_rebuild_fuzzyfiles
6261 use vars qw(@fuzzyfields);
6262 @fuzzyfields = ( 'last', 'first', 'company' );
6264 sub check_and_rebuild_fuzzyfiles {
6265 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6266 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6269 =item rebuild_fuzzyfiles
6273 sub rebuild_fuzzyfiles {
6275 use Fcntl qw(:flock);
6277 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6278 mkdir $dir, 0700 unless -d $dir;
6280 foreach my $fuzzy ( @fuzzyfields ) {
6282 open(LOCK,">>$dir/cust_main.$fuzzy")
6283 or die "can't open $dir/cust_main.$fuzzy: $!";
6285 or die "can't lock $dir/cust_main.$fuzzy: $!";
6287 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6288 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6290 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6291 my $sth = dbh->prepare("SELECT $field FROM cust_main".
6292 " WHERE $field != '' AND $field IS NOT NULL");
6293 $sth->execute or die $sth->errstr;
6295 while ( my $row = $sth->fetchrow_arrayref ) {
6296 print CACHE $row->[0]. "\n";
6301 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6303 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6314 my( $self, $field ) = @_;
6315 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6316 open(CACHE,"<$dir/cust_main.$field")
6317 or die "can't open $dir/cust_main.$field: $!";
6318 my @array = map { chomp; $_; } <CACHE>;
6323 =item append_fuzzyfiles LASTNAME COMPANY
6327 sub append_fuzzyfiles {
6328 #my( $first, $last, $company ) = @_;
6330 &check_and_rebuild_fuzzyfiles;
6332 use Fcntl qw(:flock);
6334 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6336 foreach my $field (qw( first last company )) {
6341 open(CACHE,">>$dir/cust_main.$field")
6342 or die "can't open $dir/cust_main.$field: $!";
6343 flock(CACHE,LOCK_EX)
6344 or die "can't lock $dir/cust_main.$field: $!";
6346 print CACHE "$value\n";
6348 flock(CACHE,LOCK_UN)
6349 or die "can't unlock $dir/cust_main.$field: $!";
6358 =item process_batch_import
6360 Load a batch import as a queued JSRPC job
6364 use Storable qw(thaw);
6367 sub process_batch_import {
6370 my $param = thaw(decode_base64(shift));
6371 warn Dumper($param) if $DEBUG;
6373 my $files = $param->{'uploaded_files'}
6374 or die "No files provided.\n";
6376 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
6378 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
6379 my $file = $dir. $files{'file'};
6382 if ( $file =~ /\.(\w+)$/i ) {
6386 warn "can't parse file type from filename $file; defaulting to CSV";
6391 FS::cust_main::batch_import( {
6395 custbatch => $param->{custbatch},
6396 agentnum => $param->{'agentnum'},
6397 refnum => $param->{'refnum'},
6398 pkgpart => $param->{'pkgpart'},
6399 #'fields' => [qw( cust_pkg.setup dayphone first last address1 address2
6400 # city state zip comments )],
6401 'format' => $param->{'format'},
6406 die "$error\n" if $error;
6415 use FS::svc_external;
6417 #some false laziness w/cdr.pm now
6421 my $job = $param->{job};
6423 my $filename = $param->{file};
6424 my $type = $param->{type} || 'csv';
6426 my $custbatch = $param->{custbatch};
6428 my $agentnum = $param->{agentnum};
6429 my $refnum = $param->{refnum};
6430 my $pkgpart = $param->{pkgpart};
6432 my $format = $param->{'format'};
6436 if ( $format eq 'simple' ) {
6437 @fields = qw( cust_pkg.setup dayphone first last
6438 address1 address2 city state zip comments );
6440 } elsif ( $format eq 'extended' ) {
6441 @fields = qw( agent_custid refnum
6442 last first address1 address2 city state zip country
6444 ship_last ship_first ship_address1 ship_address2
6445 ship_city ship_state ship_zip ship_country
6446 payinfo paycvv paydate
6449 svc_acct.username svc_acct._password
6452 } elsif ( $format eq 'extended-plus_company' ) {
6453 @fields = qw( agent_custid refnum
6454 last first company address1 address2 city state zip country
6456 ship_last ship_first ship_company ship_address1 ship_address2
6457 ship_city ship_state ship_zip ship_country
6458 payinfo paycvv paydate
6461 svc_acct.username svc_acct._password
6464 } elsif ( $format eq 'svc_external' ) {
6465 @fields = qw( agent_custid refnum
6466 last first company address1 address2 city state zip country
6468 ship_last ship_first ship_company ship_address1 ship_address2
6469 ship_city ship_state ship_zip ship_country
6470 payinfo paycvv paydate
6472 cust_pkg.pkgpart cust_pkg.bill
6473 svc_external.id svc_external.title
6477 die "unknown format $format";
6483 if ( $type eq 'csv' ) {
6485 eval "use Text::CSV_XS;";
6488 $parser = new Text::CSV_XS;
6490 @buffer = split(/\r?\n/, slurp($filename) );
6491 $count = scalar(@buffer);
6493 } elsif ( $type eq 'xls' ) {
6495 eval "use Spreadsheet::ParseExcel;";
6498 my $excel = new Spreadsheet::ParseExcel::Workbook->Parse($filename);
6499 $parser = $excel->{Worksheet}[0]; #first sheet
6501 $count = $parser->{MaxRow} || $parser->{MinRow};
6505 die "Unknown file type $type\n";
6510 local $SIG{HUP} = 'IGNORE';
6511 local $SIG{INT} = 'IGNORE';
6512 local $SIG{QUIT} = 'IGNORE';
6513 local $SIG{TERM} = 'IGNORE';
6514 local $SIG{TSTP} = 'IGNORE';
6515 local $SIG{PIPE} = 'IGNORE';
6517 my $oldAutoCommit = $FS::UID::AutoCommit;
6518 local $FS::UID::AutoCommit = 0;
6523 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
6527 if ( $type eq 'csv' ) {
6529 last unless scalar(@buffer);
6530 $line = shift(@buffer);
6532 $parser->parse($line) or do {
6533 $dbh->rollback if $oldAutoCommit;
6534 return "can't parse: ". $parser->error_input();
6536 @columns = $parser->fields();
6538 } elsif ( $type eq 'xls' ) {
6540 last if $row > ($parser->{MaxRow} || $parser->{MinRow});
6542 my @row = @{ $parser->{Cells}[$row] };
6543 @columns = map $_->{Val}, @row;
6546 #warn $z++. ": $_\n" for @columns;
6549 die "Unknown file type $type\n";
6552 #warn join('-',@columns);
6555 custbatch => $custbatch,
6556 agentnum => $agentnum,
6558 country => $conf->config('countrydefault') || 'US',
6559 payby => $payby, #default
6560 paydate => '12/2037', #default
6562 my $billtime = time;
6563 my %cust_pkg = ( pkgpart => $pkgpart );
6565 foreach my $field ( @fields ) {
6567 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
6569 #$cust_pkg{$1} = str2time( shift @$columns );
6570 if ( $1 eq 'pkgpart' ) {
6571 $cust_pkg{$1} = shift @columns;
6572 } elsif ( $1 eq 'setup' ) {
6573 $billtime = str2time(shift @columns);
6575 $cust_pkg{$1} = str2time( shift @columns );
6578 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
6580 $svc_x{$1} = shift @columns;
6582 } elsif ( $field =~ /^svc_external\.(id|title)$/ ) {
6584 $svc_x{$1} = shift @columns;
6588 #refnum interception
6589 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
6591 my $referral = $columns[0];
6592 my %hash = ( 'referral' => $referral,
6593 'agentnum' => $agentnum,
6597 my $part_referral = qsearchs('part_referral', \%hash )
6598 || new FS::part_referral \%hash;
6600 unless ( $part_referral->refnum ) {
6601 my $error = $part_referral->insert;
6603 $dbh->rollback if $oldAutoCommit;
6604 return "can't auto-insert advertising source: $referral: $error";
6608 $columns[0] = $part_referral->refnum;
6611 my $value = shift @columns;
6612 $cust_main{$field} = $value if length($value);
6616 $cust_main{'payby'} = 'CARD'
6617 if defined $cust_main{'payinfo'}
6618 && length $cust_main{'payinfo'};
6620 my $invoicing_list = $cust_main{'invoicing_list'}
6621 ? [ delete $cust_main{'invoicing_list'} ]
6624 my $cust_main = new FS::cust_main ( \%cust_main );
6627 tie my %hash, 'Tie::RefHash'; #this part is important
6629 if ( $cust_pkg{'pkgpart'} ) {
6630 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
6634 if ( $svc_x{'username'} ) {
6635 $svcdb = 'svc_acct';
6636 } elsif ( $svc_x{'id'} || $svc_x{'title'} ) {
6637 $svcdb = 'svc_external';
6640 my $part_pkg = $cust_pkg->part_pkg;
6641 unless ( $part_pkg ) {
6642 $dbh->rollback if $oldAutoCommit;
6643 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
6645 $svc_x{svcpart} = $part_pkg->svcpart( $svcdb );
6646 my $class = "FS::$svcdb";
6647 push @svc_x, $class->new( \%svc_x );
6650 $hash{$cust_pkg} = \@svc_x;
6653 my $error = $cust_main->insert( \%hash, $invoicing_list );
6656 $dbh->rollback if $oldAutoCommit;
6657 return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
6660 if ( $format eq 'simple' ) {
6662 #false laziness w/bill.cgi
6663 $error = $cust_main->bill( 'time' => $billtime );
6665 $dbh->rollback if $oldAutoCommit;
6666 return "can't bill customer for $line: $error";
6669 $error = $cust_main->apply_payments_and_credits;
6671 $dbh->rollback if $oldAutoCommit;
6672 return "can't bill customer for $line: $error";
6675 $error = $cust_main->collect();
6677 $dbh->rollback if $oldAutoCommit;
6678 return "can't collect customer for $line: $error";
6685 if ( $job && time - $min_sec > $last ) { #progress bar
6686 $job->update_statustext( int(100 * $row / $count) );
6692 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
6694 return "Empty file!" unless $row;
6706 #warn join('-',keys %$param);
6707 my $fh = $param->{filehandle};
6708 my @fields = @{$param->{fields}};
6710 eval "use Text::CSV_XS;";
6713 my $csv = new Text::CSV_XS;
6720 local $SIG{HUP} = 'IGNORE';
6721 local $SIG{INT} = 'IGNORE';
6722 local $SIG{QUIT} = 'IGNORE';
6723 local $SIG{TERM} = 'IGNORE';
6724 local $SIG{TSTP} = 'IGNORE';
6725 local $SIG{PIPE} = 'IGNORE';
6727 my $oldAutoCommit = $FS::UID::AutoCommit;
6728 local $FS::UID::AutoCommit = 0;
6731 #while ( $columns = $csv->getline($fh) ) {
6733 while ( defined($line=<$fh>) ) {
6735 $csv->parse($line) or do {
6736 $dbh->rollback if $oldAutoCommit;
6737 return "can't parse: ". $csv->error_input();
6740 my @columns = $csv->fields();
6741 #warn join('-',@columns);
6744 foreach my $field ( @fields ) {
6745 $row{$field} = shift @columns;
6748 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6749 unless ( $cust_main ) {
6750 $dbh->rollback if $oldAutoCommit;
6751 return "unknown custnum $row{'custnum'}";
6754 if ( $row{'amount'} > 0 ) {
6755 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6757 $dbh->rollback if $oldAutoCommit;
6761 } elsif ( $row{'amount'} < 0 ) {
6762 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6765 $dbh->rollback if $oldAutoCommit;
6775 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6777 return "Empty file!" unless $imported;
6783 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6785 Sends a templated email notification to the customer (see L<Text::Template>).
6787 OPTIONS is a hash and may include
6789 I<from> - the email sender (default is invoice_from)
6791 I<to> - comma-separated scalar or arrayref of recipients
6792 (default is invoicing_list)
6794 I<subject> - The subject line of the sent email notification
6795 (default is "Notice from company_name")
6797 I<extra_fields> - a hashref of name/value pairs which will be substituted
6800 The following variables are vavailable in the template.
6802 I<$first> - the customer first name
6803 I<$last> - the customer last name
6804 I<$company> - the customer company
6805 I<$payby> - a description of the method of payment for the customer
6806 # would be nice to use FS::payby::shortname
6807 I<$payinfo> - the account information used to collect for this customer
6808 I<$expdate> - the expiration of the customer payment in seconds from epoch
6813 my ($customer, $template, %options) = @_;
6815 return unless $conf->exists($template);
6817 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6818 $from = $options{from} if exists($options{from});
6820 my $to = join(',', $customer->invoicing_list_emailonly);
6821 $to = $options{to} if exists($options{to});
6823 my $subject = "Notice from " . $conf->config('company_name')
6824 if $conf->exists('company_name');
6825 $subject = $options{subject} if exists($options{subject});
6827 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6828 SOURCE => [ map "$_\n",
6829 $conf->config($template)]
6831 or die "can't create new Text::Template object: Text::Template::ERROR";
6832 $notify_template->compile()
6833 or die "can't compile template: Text::Template::ERROR";
6835 $FS::notify_template::_template::company_name = $conf->config('company_name');
6836 $FS::notify_template::_template::company_address =
6837 join("\n", $conf->config('company_address') ). "\n";
6839 my $paydate = $customer->paydate || '2037-12-31';
6840 $FS::notify_template::_template::first = $customer->first;
6841 $FS::notify_template::_template::last = $customer->last;
6842 $FS::notify_template::_template::company = $customer->company;
6843 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6844 my $payby = $customer->payby;
6845 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6846 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6848 #credit cards expire at the end of the month/year of their exp date
6849 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6850 $FS::notify_template::_template::payby = 'credit card';
6851 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6852 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6854 }elsif ($payby eq 'COMP') {
6855 $FS::notify_template::_template::payby = 'complimentary account';
6857 $FS::notify_template::_template::payby = 'current method';
6859 $FS::notify_template::_template::expdate = $expire_time;
6861 for (keys %{$options{extra_fields}}){
6863 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6866 send_email(from => $from,
6868 subject => $subject,
6869 body => $notify_template->fill_in( PACKAGE =>
6870 'FS::notify_template::_template' ),
6875 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6877 Generates a templated notification to the customer (see L<Text::Template>).
6879 OPTIONS is a hash and may include
6881 I<extra_fields> - a hashref of name/value pairs which will be substituted
6882 into the template. These values may override values mentioned below
6883 and those from the customer record.
6885 The following variables are available in the template instead of or in addition
6886 to the fields of the customer record.
6888 I<$payby> - a description of the method of payment for the customer
6889 # would be nice to use FS::payby::shortname
6890 I<$payinfo> - the masked account information used to collect for this customer
6891 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6892 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6896 sub generate_letter {
6897 my ($self, $template, %options) = @_;
6899 return unless $conf->exists($template);
6901 my $letter_template = new Text::Template
6903 SOURCE => [ map "$_\n", $conf->config($template)],
6904 DELIMITERS => [ '[@--', '--@]' ],
6906 or die "can't create new Text::Template object: Text::Template::ERROR";
6908 $letter_template->compile()
6909 or die "can't compile template: Text::Template::ERROR";
6911 my %letter_data = map { $_ => $self->$_ } $self->fields;
6912 $letter_data{payinfo} = $self->mask_payinfo;
6914 #my $paydate = $self->paydate || '2037-12-31';
6915 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6917 my $payby = $self->payby;
6918 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6919 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6921 #credit cards expire at the end of the month/year of their exp date
6922 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6923 $letter_data{payby} = 'credit card';
6924 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6925 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6927 }elsif ($payby eq 'COMP') {
6928 $letter_data{payby} = 'complimentary account';
6930 $letter_data{payby} = 'current method';
6932 $letter_data{expdate} = $expire_time;
6934 for (keys %{$options{extra_fields}}){
6935 $letter_data{$_} = $options{extra_fields}->{$_};
6938 unless(exists($letter_data{returnaddress})){
6939 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6940 $self->agent_template)
6942 if ( length($retadd) ) {
6943 $letter_data{returnaddress} = $retadd;
6944 } elsif ( grep /\S/, $conf->config('company_address') ) {
6945 $letter_data{returnaddress} =
6946 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6947 $conf->config('company_address')
6950 $letter_data{returnaddress} = '~';
6954 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6956 $letter_data{company_name} = $conf->config('company_name');
6958 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6959 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6963 ) or die "can't open temp file: $!\n";
6965 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6967 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6971 =item print_ps TEMPLATE
6973 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6979 my $file = $self->generate_letter(@_);
6980 FS::Misc::generate_ps($file);
6983 =item print TEMPLATE
6985 Prints the filled in template.
6987 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6991 sub queueable_print {
6994 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6995 or die "invalid customer number: " . $opt{custvnum};
6997 my $error = $self->print( $opt{template} );
6998 die $error if $error;
7002 my ($self, $template) = (shift, shift);
7003 do_print [ $self->print_ps($template) ];
7006 sub agent_template {
7008 $self->_agent_plandata('agent_templatename');
7011 sub agent_invoice_from {
7013 $self->_agent_plandata('agent_invoice_from');
7016 sub _agent_plandata {
7017 my( $self, $option ) = @_;
7019 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
7020 #agent-specific Conf
7022 use FS::part_event::Condition;
7024 my $agentnum = $self->agentnum;
7027 if ( driver_name =~ /^Pg/i ) {
7029 } elsif ( driver_name =~ /^mysql/i ) {
7032 die "don't know how to use regular expressions in ". driver_name. " databases";
7035 my $part_event_option =
7037 'select' => 'part_event_option.*',
7038 'table' => 'part_event_option',
7040 LEFT JOIN part_event USING ( eventpart )
7041 LEFT JOIN part_event_option AS peo_agentnum
7042 ON ( part_event.eventpart = peo_agentnum.eventpart
7043 AND peo_agentnum.optionname = 'agentnum'
7044 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
7046 LEFT JOIN part_event_option AS peo_cust_bill_age
7047 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
7048 AND peo_cust_bill_age.optionname = 'cust_bill_age'
7051 #'hashref' => { 'optionname' => $option },
7052 #'hashref' => { 'part_event_option.optionname' => $option },
7054 " WHERE part_event_option.optionname = ". dbh->quote($option).
7055 " AND action = 'cust_bill_send_agent' ".
7056 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
7057 " AND peo_agentnum.optionname = 'agentnum' ".
7058 " AND agentnum IS NULL OR agentnum = $agentnum ".
7060 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
7062 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
7064 , part_event.weight".
7068 unless ( $part_event_option ) {
7069 return $self->agent->invoice_template || ''
7070 if $option eq 'agent_templatename';
7074 $part_event_option->optionvalue;
7079 ## actual sub, not a method, designed to be called from the queue.
7080 ## sets up the customer, and calls the bill_and_collect
7081 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
7082 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
7083 $cust_main->bill_and_collect(
7094 The delete method should possibly take an FS::cust_main object reference
7095 instead of a scalar customer number.
7097 Bill and collect options should probably be passed as references instead of a
7100 There should probably be a configuration file with a list of allowed credit
7103 No multiple currency support (probably a larger project than just this module).
7105 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
7107 Birthdates rely on negative epoch values.
7109 The payby for card/check batches is broken. With mixed batching, bad
7112 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
7116 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
7117 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
7118 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.