4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
6 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 eval "use Time::Local;";
12 die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
13 if $] < 5.006 && !defined($Time::Local::VERSION);
14 #eval "use Time::Local qw(timelocal timelocal_nocheck);";
15 eval "use Time::Local qw(timelocal_nocheck);";
17 use Digest::MD5 qw(md5_base64);
21 use File::Slurp qw( slurp );
22 use File::Temp qw( tempfile );
23 use String::Approx qw(amatch);
24 use Business::CreditCard 0.28;
27 use FS::UID qw( getotaker dbh driver_name );
28 use FS::Record qw( qsearchs qsearch dbdef );
29 use FS::Misc qw( generate_email send_email generate_ps do_print );
30 use FS::Msgcat qw(gettext);
35 use FS::cust_bill_pkg;
37 use FS::cust_pay_pending;
38 use FS::cust_pay_void;
41 use FS::part_referral;
42 use FS::cust_main_county;
44 use FS::cust_main_invoice;
45 use FS::cust_credit_bill;
46 use FS::cust_bill_pay;
47 use FS::prepay_credit;
50 use FS::part_bill_event qw(due_events);
51 use FS::cust_bill_event;
52 use FS::cust_tax_exempt;
53 use FS::cust_tax_exempt_pkg;
55 use FS::payment_gateway;
56 use FS::agent_payment_gateway;
58 use FS::payinfo_Mixin;
60 @ISA = qw( FS::Record FS::payinfo_Mixin );
62 @EXPORT_OK = qw( smart_search );
64 $realtime_bop_decline_quiet = 0;
66 # 1 is mostly method/subroutine entry and options
67 # 2 traces progress of some operations
68 # 3 is even more information including possibly sensitive data
70 $me = '[FS::cust_main]';
74 $ignore_expired_card = 0;
76 @encrypted_fields = ('payinfo', 'paycvv');
77 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
79 #ask FS::UID to run this stuff for us later
80 #$FS::UID::callback{'FS::cust_main'} = sub {
81 install_callback FS::UID sub {
83 #yes, need it for stuff below (prolly should be cached)
88 my ( $hashref, $cache ) = @_;
89 if ( exists $hashref->{'pkgnum'} ) {
90 #@{ $self->{'_pkgnum'} } = ();
91 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
92 $self->{'_pkgnum'} = $subcache;
93 #push @{ $self->{'_pkgnum'} },
94 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
100 FS::cust_main - Object methods for cust_main records
106 $record = new FS::cust_main \%hash;
107 $record = new FS::cust_main { 'column' => 'value' };
109 $error = $record->insert;
111 $error = $new_record->replace($old_record);
113 $error = $record->delete;
115 $error = $record->check;
117 @cust_pkg = $record->all_pkgs;
119 @cust_pkg = $record->ncancelled_pkgs;
121 @cust_pkg = $record->suspended_pkgs;
123 $error = $record->bill;
124 $error = $record->bill %options;
125 $error = $record->bill 'time' => $time;
127 $error = $record->collect;
128 $error = $record->collect %options;
129 $error = $record->collect 'invoice_time' => $time,
134 An FS::cust_main object represents a customer. FS::cust_main inherits from
135 FS::Record. The following fields are currently supported:
139 =item custnum - primary key (assigned automatically for new customers)
141 =item agentnum - agent (see L<FS::agent>)
143 =item refnum - Advertising source (see L<FS::part_referral>)
149 =item ss - social security number (optional)
151 =item company - (optional)
155 =item address2 - (optional)
159 =item county - (optional, see L<FS::cust_main_county>)
161 =item state - (see L<FS::cust_main_county>)
165 =item country - (see L<FS::cust_main_county>)
167 =item daytime - phone (optional)
169 =item night - phone (optional)
171 =item fax - phone (optional)
173 =item ship_first - name
175 =item ship_last - name
177 =item ship_company - (optional)
181 =item ship_address2 - (optional)
185 =item ship_county - (optional, see L<FS::cust_main_county>)
187 =item ship_state - (see L<FS::cust_main_county>)
191 =item ship_country - (see L<FS::cust_main_county>)
193 =item ship_daytime - phone (optional)
195 =item ship_night - phone (optional)
197 =item ship_fax - phone (optional)
199 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
201 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
203 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
207 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
209 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
211 =item paystart_month - start date month (maestro/solo cards only)
213 =item paystart_year - start date year (maestro/solo cards only)
215 =item payissue - issue number (maestro/solo cards only)
217 =item payname - name on card or billing name
219 =item payip - IP address from which payment information was received
221 =item tax - tax exempt, empty or `Y'
223 =item otaker - order taker (assigned automatically, see L<FS::UID>)
225 =item comments - comments (optional)
227 =item referral_custnum - referring customer number
229 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
231 =item dundate - a suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
241 Creates a new customer. To add the customer to the database, see L<"insert">.
243 Note that this stores the hash reference, not a distinct copy of the hash it
244 points to. You can ask the object for a copy with the I<hash> method.
248 sub table { 'cust_main'; }
250 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
252 Adds this customer to the database. If there is an error, returns the error,
253 otherwise returns false.
255 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
256 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
257 are inserted atomicly, or the transaction is rolled back. Passing an empty
258 hash reference is equivalent to not supplying this parameter. There should be
259 a better explanation of this, but until then, here's an example:
262 tie %hash, 'Tie::RefHash'; #this part is important
264 $cust_pkg => [ $svc_acct ],
267 $cust_main->insert( \%hash );
269 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
270 be set as the invoicing list (see L<"invoicing_list">). Errors return as
271 expected and rollback the entire transaction; it is not necessary to call
272 check_invoicing_list first. The invoicing_list is set after the records in the
273 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
274 invoicing_list destination to the newly-created svc_acct. Here's an example:
276 $cust_main->insert( {}, [ $email, 'POST' ] );
278 Currently available options are: I<depend_jobnum> and I<noexport>.
280 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
281 on the supplied jobnum (they will not run until the specific job completes).
282 This can be used to defer provisioning until some action completes (such
283 as running the customer's credit card successfully).
285 The I<noexport> option is deprecated. If I<noexport> is set true, no
286 provisioning jobs (exports) are scheduled. (You can schedule them later with
287 the B<reexport> method.)
293 my $cust_pkgs = @_ ? shift : {};
294 my $invoicing_list = @_ ? shift : '';
296 warn "$me insert called with options ".
297 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
300 local $SIG{HUP} = 'IGNORE';
301 local $SIG{INT} = 'IGNORE';
302 local $SIG{QUIT} = 'IGNORE';
303 local $SIG{TERM} = 'IGNORE';
304 local $SIG{TSTP} = 'IGNORE';
305 local $SIG{PIPE} = 'IGNORE';
307 my $oldAutoCommit = $FS::UID::AutoCommit;
308 local $FS::UID::AutoCommit = 0;
311 my $prepay_identifier = '';
312 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
314 if ( $self->payby eq 'PREPAY' ) {
316 $self->payby('BILL');
317 $prepay_identifier = $self->payinfo;
320 warn " looking up prepaid card $prepay_identifier\n"
323 my $error = $self->get_prepay( $prepay_identifier,
324 'amount_ref' => \$amount,
325 'seconds_ref' => \$seconds,
326 'upbytes_ref' => \$upbytes,
327 'downbytes_ref' => \$downbytes,
328 'totalbytes_ref' => \$totalbytes,
331 $dbh->rollback if $oldAutoCommit;
332 #return "error applying prepaid card (transaction rolled back): $error";
336 $payby = 'PREP' if $amount;
338 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
341 $self->payby('BILL');
342 $amount = $self->paid;
346 warn " inserting $self\n"
349 $self->signupdate(time) unless $self->signupdate;
351 my $error = $self->SUPER::insert;
353 $dbh->rollback if $oldAutoCommit;
354 #return "inserting cust_main record (transaction rolled back): $error";
358 warn " setting invoicing list\n"
361 if ( $invoicing_list ) {
362 $error = $self->check_invoicing_list( $invoicing_list );
364 $dbh->rollback if $oldAutoCommit;
365 #return "checking invoicing_list (transaction rolled back): $error";
368 $self->invoicing_list( $invoicing_list );
371 if ( $conf->config('cust_main-skeleton_tables')
372 && $conf->config('cust_main-skeleton_custnum') ) {
374 warn " inserting skeleton records\n"
377 my $error = $self->start_copy_skel;
379 $dbh->rollback if $oldAutoCommit;
385 warn " ordering packages\n"
388 $error = $self->order_pkgs( $cust_pkgs,
390 'seconds_ref' => \$seconds,
391 'upbytes_ref' => \$upbytes,
392 'downbytes_ref' => \$downbytes,
393 'totalbytes_ref' => \$totalbytes,
396 $dbh->rollback if $oldAutoCommit;
401 $dbh->rollback if $oldAutoCommit;
402 return "No svc_acct record to apply pre-paid time";
404 if ( $upbytes || $downbytes || $totalbytes ) {
405 $dbh->rollback if $oldAutoCommit;
406 return "No svc_acct record to apply pre-paid data";
410 warn " inserting initial $payby payment of $amount\n"
412 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
414 $dbh->rollback if $oldAutoCommit;
415 return "inserting payment (transaction rolled back): $error";
419 unless ( $import || $skip_fuzzyfiles ) {
420 warn " queueing fuzzyfiles update\n"
422 $error = $self->queue_fuzzyfiles_update;
424 $dbh->rollback if $oldAutoCommit;
425 return "updating fuzzy search cache: $error";
429 warn " insert complete; committing transaction\n"
432 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
437 sub start_copy_skel {
440 #'mg_user_preference' => {},
441 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
442 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
443 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
444 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
445 my @tables = eval($conf->config_binary('cust_main-skeleton_tables'));
448 _copy_skel( 'cust_main', #tablename
449 $conf->config('cust_main-skeleton_custnum'), #sourceid
450 $self->custnum, #destid
451 @tables, #child tables
455 #recursive subroutine, not a method
457 my( $table, $sourceid, $destid, %child_tables ) = @_;
460 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
461 ( $table, $primary_key ) = ( $1, $2 );
463 my $dbdef_table = dbdef->table($table);
464 $primary_key = $dbdef_table->primary_key
465 or return "$table has no primary key".
466 " (or do you need to run dbdef-create?)";
469 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
470 join (', ', keys %child_tables). "\n"
473 foreach my $child_table_def ( keys %child_tables ) {
477 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
478 ( $child_table, $child_pkey ) = ( $1, $2 );
480 $child_table = $child_table_def;
482 $child_pkey = dbdef->table($child_table)->primary_key;
483 # or return "$table has no primary key".
484 # " (or do you need to run dbdef-create?)\n";
488 if ( keys %{ $child_tables{$child_table_def} } ) {
490 return "$child_table has no primary key".
491 " (run dbdef-create or try specifying it?)\n"
494 #false laziness w/Record::insert and only works on Pg
495 #refactor the proper last-inserted-id stuff out of Record::insert if this
496 # ever gets use for anything besides a quick kludge for one customer
497 my $default = dbdef->table($child_table)->column($child_pkey)->default;
498 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
499 or return "can't parse $child_table.$child_pkey default value ".
500 " for sequence name: $default";
505 my @sel_columns = grep { $_ ne $primary_key }
506 dbdef->table($child_table)->columns;
507 my $sel_columns = join(', ', @sel_columns );
509 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
510 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
511 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
513 my $sel_st = "SELECT $sel_columns FROM $child_table".
514 " WHERE $primary_key = $sourceid";
517 my $sel_sth = dbh->prepare( $sel_st )
518 or return dbh->errstr;
520 $sel_sth->execute or return $sel_sth->errstr;
522 while ( my $row = $sel_sth->fetchrow_hashref ) {
524 warn " selected row: ".
525 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
529 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
530 my $ins_sth =dbh->prepare($statement)
531 or return dbh->errstr;
532 my @param = ( $destid, map $row->{$_}, @ins_columns );
533 warn " $statement: [ ". join(', ', @param). " ]\n"
535 $ins_sth->execute( @param )
536 or return $ins_sth->errstr;
538 #next unless keys %{ $child_tables{$child_table} };
539 next unless $sequence;
541 #another section of that laziness
542 my $seq_sql = "SELECT currval('$sequence')";
543 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
544 $seq_sth->execute or return $seq_sth->errstr;
545 my $insertid = $seq_sth->fetchrow_arrayref->[0];
547 # don't drink soap! recurse! recurse! okay!
549 _copy_skel( $child_table_def,
550 $row->{$child_pkey}, #sourceid
552 %{ $child_tables{$child_table_def} },
554 return $error if $error;
564 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
565 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
567 Like the insert method on an existing record, this method orders a package
568 and included services atomicaly. Pass a Tie::RefHash data structure to this
569 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
570 be a better explanation of this, but until then, here's an example:
573 tie %hash, 'Tie::RefHash'; #this part is important
575 $cust_pkg => [ $svc_acct ],
578 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
580 Services can be new, in which case they are inserted, or existing unaudited
581 services, in which case they are linked to the newly-created package.
583 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
584 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
586 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
587 on the supplied jobnum (they will not run until the specific job completes).
588 This can be used to defer provisioning until some action completes (such
589 as running the customer's credit card successfully).
591 The I<noexport> option is deprecated. If I<noexport> is set true, no
592 provisioning jobs (exports) are scheduled. (You can schedule them later with
593 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
594 on the cust_main object is not recommended, as existing services will also be
597 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
598 provided, the scalars (provided by references) will be incremented by the
599 values of the prepaid card.`
605 my $cust_pkgs = shift;
606 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
608 $seconds_ref ||= $options{'seconds_ref'};
610 my %svc_options = ();
611 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
612 if exists $options{'depend_jobnum'};
613 warn "$me order_pkgs called with options ".
614 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
617 local $SIG{HUP} = 'IGNORE';
618 local $SIG{INT} = 'IGNORE';
619 local $SIG{QUIT} = 'IGNORE';
620 local $SIG{TERM} = 'IGNORE';
621 local $SIG{TSTP} = 'IGNORE';
622 local $SIG{PIPE} = 'IGNORE';
624 my $oldAutoCommit = $FS::UID::AutoCommit;
625 local $FS::UID::AutoCommit = 0;
628 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
630 foreach my $cust_pkg ( keys %$cust_pkgs ) {
631 $cust_pkg->custnum( $self->custnum );
632 my $error = $cust_pkg->insert;
634 $dbh->rollback if $oldAutoCommit;
635 return "inserting cust_pkg (transaction rolled back): $error";
637 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
638 if ( $svc_something->svcnum ) {
639 my $old_cust_svc = $svc_something->cust_svc;
640 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
641 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
642 $error = $new_cust_svc->replace($old_cust_svc);
644 $svc_something->pkgnum( $cust_pkg->pkgnum );
645 if ( $svc_something->isa('FS::svc_acct') ) {
646 foreach ( grep { $options{$_.'_ref'} && ${ $options{$_.'_ref'} } }
647 qw( seconds upbytes downbytes totalbytes )
649 $svc_something->$_( $svc_something->$_() + ${$options{$_.'_ref'}} );
650 ${ $options{$_.'_ref'} } = 0;
653 $error = $svc_something->insert(%svc_options);
656 $dbh->rollback if $oldAutoCommit;
657 #return "inserting svc_ (transaction rolled back): $error";
663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
667 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
669 Recharges this (existing) customer with the specified prepaid card (see
670 L<FS::prepay_credit>), specified either by I<identifier> or as an
671 FS::prepay_credit object. If there is an error, returns the error, otherwise
674 Optionally, five scalar references can be passed as well. They will have their
675 values filled in with the amount, number of seconds, and number of upload,
676 download, and total bytes applied by this prepaid card.
680 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
681 #the only place that uses these args
682 sub recharge_prepay {
683 my( $self, $prepay_credit, $amountref, $secondsref,
684 $upbytesref, $downbytesref, $totalbytesref ) = @_;
686 local $SIG{HUP} = 'IGNORE';
687 local $SIG{INT} = 'IGNORE';
688 local $SIG{QUIT} = 'IGNORE';
689 local $SIG{TERM} = 'IGNORE';
690 local $SIG{TSTP} = 'IGNORE';
691 local $SIG{PIPE} = 'IGNORE';
693 my $oldAutoCommit = $FS::UID::AutoCommit;
694 local $FS::UID::AutoCommit = 0;
697 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
699 my $error = $self->get_prepay( $prepay_credit,
700 'amount_ref' => \$amount,
701 'seconds_ref' => \$seconds,
702 'upbytes_ref' => \$upbytes,
703 'downbytes_ref' => \$downbytes,
704 'totalbytes_ref' => \$totalbytes,
706 || $self->increment_seconds($seconds)
707 || $self->increment_upbytes($upbytes)
708 || $self->increment_downbytes($downbytes)
709 || $self->increment_totalbytes($totalbytes)
710 || $self->insert_cust_pay_prepay( $amount,
712 ? $prepay_credit->identifier
717 $dbh->rollback if $oldAutoCommit;
721 if ( defined($amountref) ) { $$amountref = $amount; }
722 if ( defined($secondsref) ) { $$secondsref = $seconds; }
723 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
724 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
725 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
727 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
732 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
734 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
735 specified either by I<identifier> or as an FS::prepay_credit object.
737 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>. The scalars (provided by references) will be
738 incremented by the values of the prepaid card.
740 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
741 check or set this customer's I<agentnum>.
743 If there is an error, returns the error, otherwise returns false.
749 my( $self, $prepay_credit, %opt ) = @_;
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 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
795 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
797 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
802 =item increment_upbytes SECONDS
804 Updates this customer's single or primary account (see L<FS::svc_acct>) by
805 the specified number of upbytes. If there is an error, returns the error,
806 otherwise returns false.
810 sub increment_upbytes {
811 _increment_column( shift, 'upbytes', @_);
814 =item increment_downbytes SECONDS
816 Updates this customer's single or primary account (see L<FS::svc_acct>) by
817 the specified number of downbytes. If there is an error, returns the error,
818 otherwise returns false.
822 sub increment_downbytes {
823 _increment_column( shift, 'downbytes', @_);
826 =item increment_totalbytes SECONDS
828 Updates this customer's single or primary account (see L<FS::svc_acct>) by
829 the specified number of totalbytes. If there is an error, returns the error,
830 otherwise returns false.
834 sub increment_totalbytes {
835 _increment_column( shift, 'totalbytes', @_);
838 =item increment_seconds SECONDS
840 Updates this customer's single or primary account (see L<FS::svc_acct>) by
841 the specified number of seconds. If there is an error, returns the error,
842 otherwise returns false.
846 sub increment_seconds {
847 _increment_column( shift, 'seconds', @_);
850 =item _increment_column AMOUNT
852 Updates this customer's single or primary account (see L<FS::svc_acct>) by
853 the specified number of seconds or bytes. If there is an error, returns
854 the error, otherwise returns false.
858 sub _increment_column {
859 my( $self, $column, $amount ) = @_;
860 warn "$me increment_column called: $column, $amount\n"
863 return '' unless $amount;
865 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
866 $self->ncancelled_pkgs;
869 return 'No packages with primary or single services found'.
870 ' to apply pre-paid time';
871 } elsif ( scalar(@cust_pkg) > 1 ) {
872 #maybe have a way to specify the package/account?
873 return 'Multiple packages found to apply pre-paid time';
876 my $cust_pkg = $cust_pkg[0];
877 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
881 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
884 return 'No account found to apply pre-paid time';
885 } elsif ( scalar(@cust_svc) > 1 ) {
886 return 'Multiple accounts found to apply pre-paid time';
889 my $svc_acct = $cust_svc[0]->svc_x;
890 warn " found service svcnum ". $svc_acct->pkgnum.
891 ' ('. $svc_acct->email. ")\n"
894 $column = "increment_$column";
895 $svc_acct->$column($amount);
899 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
901 Inserts a prepayment in the specified amount for this customer. An optional
902 second argument can specify the prepayment identifier for tracking purposes.
903 If there is an error, returns the error, otherwise returns false.
907 sub insert_cust_pay_prepay {
908 shift->insert_cust_pay('PREP', @_);
911 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
913 Inserts a cash payment in the specified amount for this customer. An optional
914 second argument can specify the payment identifier for tracking purposes.
915 If there is an error, returns the error, otherwise returns false.
919 sub insert_cust_pay_cash {
920 shift->insert_cust_pay('CASH', @_);
923 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
925 Inserts a Western Union payment in the specified amount for this customer. An
926 optional second argument can specify the prepayment identifier for tracking
927 purposes. If there is an error, returns the error, otherwise returns false.
931 sub insert_cust_pay_west {
932 shift->insert_cust_pay('WEST', @_);
935 sub insert_cust_pay {
936 my( $self, $payby, $amount ) = splice(@_, 0, 3);
937 my $payinfo = scalar(@_) ? shift : '';
939 my $cust_pay = new FS::cust_pay {
940 'custnum' => $self->custnum,
941 'paid' => sprintf('%.2f', $amount),
942 #'_date' => #date the prepaid card was purchased???
944 'payinfo' => $payinfo,
952 This method is deprecated. See the I<depend_jobnum> option to the insert and
953 order_pkgs methods for a better way to defer provisioning.
955 Re-schedules all exports by calling the B<reexport> method of all associated
956 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
957 otherwise returns false.
964 carp "WARNING: FS::cust_main::reexport is deprectated; ".
965 "use the depend_jobnum option to insert or order_pkgs to delay export";
967 local $SIG{HUP} = 'IGNORE';
968 local $SIG{INT} = 'IGNORE';
969 local $SIG{QUIT} = 'IGNORE';
970 local $SIG{TERM} = 'IGNORE';
971 local $SIG{TSTP} = 'IGNORE';
972 local $SIG{PIPE} = 'IGNORE';
974 my $oldAutoCommit = $FS::UID::AutoCommit;
975 local $FS::UID::AutoCommit = 0;
978 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
979 my $error = $cust_pkg->reexport;
981 $dbh->rollback if $oldAutoCommit;
986 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
991 =item delete NEW_CUSTNUM
993 This deletes the customer. If there is an error, returns the error, otherwise
996 This will completely remove all traces of the customer record. This is not
997 what you want when a customer cancels service; for that, cancel all of the
998 customer's packages (see L</cancel>).
1000 If the customer has any uncancelled packages, you need to pass a new (valid)
1001 customer number for those packages to be transferred to. Cancelled packages
1002 will be deleted. Did I mention that this is NOT what you want when a customer
1003 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1005 You can't delete a customer with invoices (see L<FS::cust_bill>),
1006 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1007 refunds (see L<FS::cust_refund>).
1014 local $SIG{HUP} = 'IGNORE';
1015 local $SIG{INT} = 'IGNORE';
1016 local $SIG{QUIT} = 'IGNORE';
1017 local $SIG{TERM} = 'IGNORE';
1018 local $SIG{TSTP} = 'IGNORE';
1019 local $SIG{PIPE} = 'IGNORE';
1021 my $oldAutoCommit = $FS::UID::AutoCommit;
1022 local $FS::UID::AutoCommit = 0;
1025 if ( $self->cust_bill ) {
1026 $dbh->rollback if $oldAutoCommit;
1027 return "Can't delete a customer with invoices";
1029 if ( $self->cust_credit ) {
1030 $dbh->rollback if $oldAutoCommit;
1031 return "Can't delete a customer with credits";
1033 if ( $self->cust_pay ) {
1034 $dbh->rollback if $oldAutoCommit;
1035 return "Can't delete a customer with payments";
1037 if ( $self->cust_refund ) {
1038 $dbh->rollback if $oldAutoCommit;
1039 return "Can't delete a customer with refunds";
1042 my @cust_pkg = $self->ncancelled_pkgs;
1044 my $new_custnum = shift;
1045 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1046 $dbh->rollback if $oldAutoCommit;
1047 return "Invalid new customer number: $new_custnum";
1049 foreach my $cust_pkg ( @cust_pkg ) {
1050 my %hash = $cust_pkg->hash;
1051 $hash{'custnum'} = $new_custnum;
1052 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1053 my $error = $new_cust_pkg->replace($cust_pkg,
1054 options => { $cust_pkg->options },
1057 $dbh->rollback if $oldAutoCommit;
1062 my @cancelled_cust_pkg = $self->all_pkgs;
1063 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1064 my $error = $cust_pkg->delete;
1066 $dbh->rollback if $oldAutoCommit;
1071 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1072 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1074 my $error = $cust_main_invoice->delete;
1076 $dbh->rollback if $oldAutoCommit;
1081 my $error = $self->SUPER::delete;
1083 $dbh->rollback if $oldAutoCommit;
1087 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1092 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1094 Replaces the OLD_RECORD with this one in the database. If there is an error,
1095 returns the error, otherwise returns false.
1097 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1098 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1099 expected and rollback the entire transaction; it is not necessary to call
1100 check_invoicing_list first. Here's an example:
1102 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1110 warn "$me replace called\n"
1113 local $SIG{HUP} = 'IGNORE';
1114 local $SIG{INT} = 'IGNORE';
1115 local $SIG{QUIT} = 'IGNORE';
1116 local $SIG{TERM} = 'IGNORE';
1117 local $SIG{TSTP} = 'IGNORE';
1118 local $SIG{PIPE} = 'IGNORE';
1120 # We absolutely have to have an old vs. new record to make this work.
1121 if (!defined($old)) {
1122 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1125 my $curuser = $FS::CurrentUser::CurrentUser;
1126 if ( $self->payby eq 'COMP'
1127 && $self->payby ne $old->payby
1128 && ! $curuser->access_right('Complimentary customer')
1131 return "You are not permitted to create complimentary accounts.";
1134 local($ignore_expired_card) = 1
1135 if $old->payby =~ /^(CARD|DCRD)$/
1136 && $self->payby =~ /^(CARD|DCRD)$/
1137 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1139 my $oldAutoCommit = $FS::UID::AutoCommit;
1140 local $FS::UID::AutoCommit = 0;
1143 my $error = $self->SUPER::replace($old);
1146 $dbh->rollback if $oldAutoCommit;
1150 if ( @param ) { # INVOICING_LIST_ARYREF
1151 my $invoicing_list = shift @param;
1152 $error = $self->check_invoicing_list( $invoicing_list );
1154 $dbh->rollback if $oldAutoCommit;
1157 $self->invoicing_list( $invoicing_list );
1160 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1161 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1162 # card/check/lec info has changed, want to retry realtime_ invoice events
1163 my $error = $self->retry_realtime;
1165 $dbh->rollback if $oldAutoCommit;
1170 unless ( $import || $skip_fuzzyfiles ) {
1171 $error = $self->queue_fuzzyfiles_update;
1173 $dbh->rollback if $oldAutoCommit;
1174 return "updating fuzzy search cache: $error";
1178 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1183 =item queue_fuzzyfiles_update
1185 Used by insert & replace to update the fuzzy search cache
1189 sub queue_fuzzyfiles_update {
1192 local $SIG{HUP} = 'IGNORE';
1193 local $SIG{INT} = 'IGNORE';
1194 local $SIG{QUIT} = 'IGNORE';
1195 local $SIG{TERM} = 'IGNORE';
1196 local $SIG{TSTP} = 'IGNORE';
1197 local $SIG{PIPE} = 'IGNORE';
1199 my $oldAutoCommit = $FS::UID::AutoCommit;
1200 local $FS::UID::AutoCommit = 0;
1203 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1204 my $error = $queue->insert( map $self->getfield($_),
1205 qw(first last company)
1208 $dbh->rollback if $oldAutoCommit;
1209 return "queueing job (transaction rolled back): $error";
1212 if ( $self->ship_last ) {
1213 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1214 $error = $queue->insert( map $self->getfield("ship_$_"),
1215 qw(first last company)
1218 $dbh->rollback if $oldAutoCommit;
1219 return "queueing job (transaction rolled back): $error";
1223 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1230 Checks all fields to make sure this is a valid customer record. If there is
1231 an error, returns the error, otherwise returns false. Called by the insert
1232 and replace methods.
1239 warn "$me check BEFORE: \n". $self->_dump
1243 $self->ut_numbern('custnum')
1244 || $self->ut_number('agentnum')
1245 || $self->ut_textn('agent_custid')
1246 || $self->ut_number('refnum')
1247 || $self->ut_textn('custbatch')
1248 || $self->ut_name('last')
1249 || $self->ut_name('first')
1250 || $self->ut_snumbern('birthdate')
1251 || $self->ut_snumbern('signupdate')
1252 || $self->ut_textn('company')
1253 || $self->ut_text('address1')
1254 || $self->ut_textn('address2')
1255 || $self->ut_text('city')
1256 || $self->ut_textn('county')
1257 || $self->ut_textn('state')
1258 || $self->ut_country('country')
1259 || $self->ut_anything('comments')
1260 || $self->ut_numbern('referral_custnum')
1261 || $self->ut_textn('stateid')
1262 || $self->ut_textn('stateid_state')
1264 #barf. need message catalogs. i18n. etc.
1265 $error .= "Please select an advertising source."
1266 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1267 return $error if $error;
1269 return "Unknown agent"
1270 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1272 return "Unknown refnum"
1273 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1275 return "Unknown referring custnum: ". $self->referral_custnum
1276 unless ! $self->referral_custnum
1277 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1279 if ( $self->ss eq '' ) {
1284 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1285 or return "Illegal social security number: ". $self->ss;
1286 $self->ss("$1-$2-$3");
1290 # bad idea to disable, causes billing to fail because of no tax rates later
1291 # unless ( $import ) {
1292 unless ( qsearch('cust_main_county', {
1293 'country' => $self->country,
1296 return "Unknown state/county/country: ".
1297 $self->state. "/". $self->county. "/". $self->country
1298 unless qsearch('cust_main_county',{
1299 'state' => $self->state,
1300 'county' => $self->county,
1301 'country' => $self->country,
1307 $self->ut_phonen('daytime', $self->country)
1308 || $self->ut_phonen('night', $self->country)
1309 || $self->ut_phonen('fax', $self->country)
1310 || $self->ut_zip('zip', $self->country)
1312 return $error if $error;
1314 if ( $conf->exists('cust_main-require_phone')
1315 && ! length($self->daytime) && ! length($self->night)
1318 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1320 : FS::Msgcat::_gettext('daytime');
1321 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1323 : FS::Msgcat::_gettext('night');
1325 return "$daytime_label or $night_label is required"
1329 if ( $self->has_ship_address
1330 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1331 $self->addr_fields )
1335 $self->ut_name('ship_last')
1336 || $self->ut_name('ship_first')
1337 || $self->ut_textn('ship_company')
1338 || $self->ut_text('ship_address1')
1339 || $self->ut_textn('ship_address2')
1340 || $self->ut_text('ship_city')
1341 || $self->ut_textn('ship_county')
1342 || $self->ut_textn('ship_state')
1343 || $self->ut_country('ship_country')
1345 return $error if $error;
1347 #false laziness with above
1348 unless ( qsearchs('cust_main_county', {
1349 'country' => $self->ship_country,
1352 return "Unknown ship_state/ship_county/ship_country: ".
1353 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1354 unless qsearch('cust_main_county',{
1355 'state' => $self->ship_state,
1356 'county' => $self->ship_county,
1357 'country' => $self->ship_country,
1363 $self->ut_phonen('ship_daytime', $self->ship_country)
1364 || $self->ut_phonen('ship_night', $self->ship_country)
1365 || $self->ut_phonen('ship_fax', $self->ship_country)
1366 || $self->ut_zip('ship_zip', $self->ship_country)
1368 return $error if $error;
1370 return "Unit # is required."
1371 if $self->ship_address2 =~ /^\s*$/
1372 && $conf->exists('cust_main-require_address2');
1374 } else { # ship_ info eq billing info, so don't store dup info in database
1376 $self->setfield("ship_$_", '')
1377 foreach $self->addr_fields;
1379 return "Unit # is required."
1380 if $self->address2 =~ /^\s*$/
1381 && $conf->exists('cust_main-require_address2');
1385 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1386 # or return "Illegal payby: ". $self->payby;
1388 FS::payby->can_payby($self->table, $self->payby)
1389 or return "Illegal payby: ". $self->payby;
1391 $error = $self->ut_numbern('paystart_month')
1392 || $self->ut_numbern('paystart_year')
1393 || $self->ut_numbern('payissue')
1394 || $self->ut_textn('paytype')
1396 return $error if $error;
1398 if ( $self->payip eq '' ) {
1401 $error = $self->ut_ip('payip');
1402 return $error if $error;
1405 # If it is encrypted and the private key is not availaible then we can't
1406 # check the credit card.
1408 my $check_payinfo = 1;
1410 if ($self->is_encrypted($self->payinfo)) {
1414 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1416 my $payinfo = $self->payinfo;
1417 $payinfo =~ s/\D//g;
1418 $payinfo =~ /^(\d{13,16})$/
1419 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1421 $self->payinfo($payinfo);
1423 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1425 return gettext('unknown_card_type')
1426 if cardtype($self->payinfo) eq "Unknown";
1428 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1430 return 'Banned credit card: banned on '.
1431 time2str('%a %h %o at %r', $ban->_date).
1432 ' by '. $ban->otaker.
1433 ' (ban# '. $ban->bannum. ')';
1436 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1437 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1438 $self->paycvv =~ /^(\d{4})$/
1439 or return "CVV2 (CID) for American Express cards is four digits.";
1442 $self->paycvv =~ /^(\d{3})$/
1443 or return "CVV2 (CVC2/CID) is three digits.";
1450 my $cardtype = cardtype($payinfo);
1451 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1453 return "Start date or issue number is required for $cardtype cards"
1454 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1456 return "Start month must be between 1 and 12"
1457 if $self->paystart_month
1458 and $self->paystart_month < 1 || $self->paystart_month > 12;
1460 return "Start year must be 1990 or later"
1461 if $self->paystart_year
1462 and $self->paystart_year < 1990;
1464 return "Issue number must be beween 1 and 99"
1466 and $self->payissue < 1 || $self->payissue > 99;
1469 $self->paystart_month('');
1470 $self->paystart_year('');
1471 $self->payissue('');
1474 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1476 my $payinfo = $self->payinfo;
1477 $payinfo =~ s/[^\d\@]//g;
1478 if ( $conf->exists('echeck-nonus') ) {
1479 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1480 $payinfo = "$1\@$2";
1482 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1483 $payinfo = "$1\@$2";
1485 $self->payinfo($payinfo);
1488 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1490 return 'Banned ACH account: banned on '.
1491 time2str('%a %h %o at %r', $ban->_date).
1492 ' by '. $ban->otaker.
1493 ' (ban# '. $ban->bannum. ')';
1496 } elsif ( $self->payby eq 'LECB' ) {
1498 my $payinfo = $self->payinfo;
1499 $payinfo =~ s/\D//g;
1500 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1502 $self->payinfo($payinfo);
1505 } elsif ( $self->payby eq 'BILL' ) {
1507 $error = $self->ut_textn('payinfo');
1508 return "Illegal P.O. number: ". $self->payinfo if $error;
1511 } elsif ( $self->payby eq 'COMP' ) {
1513 my $curuser = $FS::CurrentUser::CurrentUser;
1514 if ( ! $self->custnum
1515 && ! $curuser->access_right('Complimentary customer')
1518 return "You are not permitted to create complimentary accounts."
1521 $error = $self->ut_textn('payinfo');
1522 return "Illegal comp account issuer: ". $self->payinfo if $error;
1525 } elsif ( $self->payby eq 'PREPAY' ) {
1527 my $payinfo = $self->payinfo;
1528 $payinfo =~ s/\W//g; #anything else would just confuse things
1529 $self->payinfo($payinfo);
1530 $error = $self->ut_alpha('payinfo');
1531 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1532 return "Unknown prepayment identifier"
1533 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1538 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1539 return "Expiration date required"
1540 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1544 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1545 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1546 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1547 ( $m, $y ) = ( $3, "20$2" );
1549 return "Illegal expiration date: ". $self->paydate;
1551 $self->paydate("$y-$m-01");
1552 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1553 return gettext('expired_card')
1555 && !$ignore_expired_card
1556 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1559 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1560 ( ! $conf->exists('require_cardname')
1561 || $self->payby !~ /^(CARD|DCRD)$/ )
1563 $self->payname( $self->first. " ". $self->getfield('last') );
1565 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1566 or return gettext('illegal_name'). " payname: ". $self->payname;
1570 foreach my $flag (qw( tax spool_cdr )) {
1571 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1575 $self->otaker(getotaker) unless $self->otaker;
1577 warn "$me check AFTER: \n". $self->_dump
1580 $self->SUPER::check;
1585 Returns a list of fields which have ship_ duplicates.
1590 qw( last first company
1591 address1 address2 city county state zip country
1596 =item has_ship_address
1598 Returns true if this customer record has a separate shipping address.
1602 sub has_ship_address {
1604 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1609 Returns all packages (see L<FS::cust_pkg>) for this customer.
1616 return $self->num_pkgs unless wantarray;
1619 if ( $self->{'_pkgnum'} ) {
1620 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1622 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1625 sort sort_packages @cust_pkg;
1628 =item ncancelled_pkgs
1630 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1634 sub ncancelled_pkgs {
1637 return $self->num_ncancelled_pkgs unless wantarray;
1640 if ( $self->{'_pkgnum'} ) {
1642 @cust_pkg = grep { ! $_->getfield('cancel') }
1643 values %{ $self->{'_pkgnum'}->cache };
1648 qsearch( 'cust_pkg', {
1649 'custnum' => $self->custnum,
1653 qsearch( 'cust_pkg', {
1654 'custnum' => $self->custnum,
1659 sort sort_packages @cust_pkg;
1663 # This should be generalized to use config options to determine order.
1665 if ( $a->get('cancel') and $b->get('cancel') ) {
1666 $a->pkgnum <=> $b->pkgnum;
1667 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1668 return -1 if $b->get('cancel');
1669 return 1 if $a->get('cancel');
1672 $a->pkgnum <=> $b->pkgnum;
1676 =item suspended_pkgs
1678 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1682 sub suspended_pkgs {
1684 grep { $_->susp } $self->ncancelled_pkgs;
1687 =item unflagged_suspended_pkgs
1689 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1690 customer (thouse packages without the `manual_flag' set).
1694 sub unflagged_suspended_pkgs {
1696 return $self->suspended_pkgs
1697 unless dbdef->table('cust_pkg')->column('manual_flag');
1698 grep { ! $_->manual_flag } $self->suspended_pkgs;
1701 =item unsuspended_pkgs
1703 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1708 sub unsuspended_pkgs {
1710 grep { ! $_->susp } $self->ncancelled_pkgs;
1713 =item num_cancelled_pkgs
1715 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1720 sub num_cancelled_pkgs {
1721 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1724 sub num_ncancelled_pkgs {
1725 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1729 my( $self ) = shift;
1730 my $sql = scalar(@_) ? shift : '';
1731 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1732 my $sth = dbh->prepare(
1733 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1734 ) or die dbh->errstr;
1735 $sth->execute($self->custnum) or die $sth->errstr;
1736 $sth->fetchrow_arrayref->[0];
1741 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1742 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1743 on success or a list of errors.
1749 grep { $_->unsuspend } $self->suspended_pkgs;
1754 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1756 Returns a list: an empty list on success or a list of errors.
1762 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1765 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1767 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1768 PKGPARTs (see L<FS::part_pkg>).
1770 Returns a list: an empty list on success or a list of errors.
1774 sub suspend_if_pkgpart {
1776 my (@pkgparts, %opt);
1777 if (ref($_[0]) eq 'HASH'){
1778 @pkgparts = @{$_[0]{pkgparts}};
1783 grep { $_->suspend(%opt) }
1784 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1785 $self->unsuspended_pkgs;
1788 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1790 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1791 listed PKGPARTs (see L<FS::part_pkg>).
1793 Returns a list: an empty list on success or a list of errors.
1797 sub suspend_unless_pkgpart {
1799 my (@pkgparts, %opt);
1800 if (ref($_[0]) eq 'HASH'){
1801 @pkgparts = @{$_[0]{pkgparts}};
1806 grep { $_->suspend(%opt) }
1807 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1808 $self->unsuspended_pkgs;
1811 =item cancel [ OPTION => VALUE ... ]
1813 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1815 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1817 I<quiet> can be set true to supress email cancellation notices.
1819 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1821 I<ban> can be set true to ban this customer's credit card or ACH information,
1824 Always returns a list: an empty list on success or a list of errors.
1832 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1834 #should try decryption (we might have the private key)
1835 # and if not maybe queue a job for the server that does?
1836 return ( "Can't (yet) ban encrypted credit cards" )
1837 if $self->is_encrypted($self->payinfo);
1839 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1840 my $error = $ban->insert;
1841 return ( $error ) if $error;
1845 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1848 sub _banned_pay_hashref {
1859 'payby' => $payby2ban{$self->payby},
1860 'payinfo' => md5_base64($self->payinfo),
1861 #don't ever *search* on reason! #'reason' =>
1867 Returns all notes (see L<FS::cust_main_note>) for this customer.
1874 qsearch( 'cust_main_note',
1875 { 'custnum' => $self->custnum },
1877 'ORDER BY _DATE DESC'
1883 Returns the agent (see L<FS::agent>) for this customer.
1889 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1894 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1895 conjunction with the collect method.
1897 If there is an error, returns the error, otherwise returns false.
1899 Options are passed as name-value pairs. Currently available options are:
1903 =item resetup - if set true, re-charges setup fees.
1905 =item time - 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:
1909 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1911 =item invoice_time - 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.
1918 my( $self, %options ) = @_;
1919 return '' if $self->payby eq 'COMP';
1920 warn "$me bill customer ". $self->custnum. "\n"
1923 my $time = $options{'time'} || time;
1928 local $SIG{HUP} = 'IGNORE';
1929 local $SIG{INT} = 'IGNORE';
1930 local $SIG{QUIT} = 'IGNORE';
1931 local $SIG{TERM} = 'IGNORE';
1932 local $SIG{TSTP} = 'IGNORE';
1933 local $SIG{PIPE} = 'IGNORE';
1935 my $oldAutoCommit = $FS::UID::AutoCommit;
1936 local $FS::UID::AutoCommit = 0;
1939 $self->select_for_update; #mutex
1941 #create a new invoice
1942 #(we'll remove it later if it doesn't actually need to be generated [contains
1943 # no line items] and we're inside a transaciton so nothing else will see it)
1944 my $cust_bill = new FS::cust_bill ( {
1945 'custnum' => $self->custnum,
1946 '_date' => ( $options{'invoice_time'} || $time ),
1947 #'charged' => $charged,
1950 $error = $cust_bill->insert;
1952 $dbh->rollback if $oldAutoCommit;
1953 return "can't create invoice for customer #". $self->custnum. ": $error";
1955 my $invnum = $cust_bill->invnum;
1958 # find the packages which are due for billing, find out how much they are
1959 # & generate invoice database.
1962 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
1964 my @precommit_hooks = ();
1966 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
1967 foreach my $cust_pkg (@cust_pkgs) {
1969 #NO!! next if $cust_pkg->cancel;
1970 next if $cust_pkg->getfield('cancel');
1972 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1974 #? to avoid use of uninitialized value errors... ?
1975 $cust_pkg->setfield('bill', '')
1976 unless defined($cust_pkg->bill);
1978 my $part_pkg = $cust_pkg->part_pkg;
1980 my %hash = $cust_pkg->hash;
1981 my $old_cust_pkg = new FS::cust_pkg \%hash;
1991 if ( ! $cust_pkg->setup &&
1993 ( $conf->exists('disable_setup_suspended_pkgs') &&
1994 ! $cust_pkg->getfield('susp')
1995 ) || ! $conf->exists('disable_setup_suspended_pkgs')
1997 || $options{'resetup'}
2000 warn " bill setup\n" if $DEBUG > 1;
2002 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2004 $dbh->rollback if $oldAutoCommit;
2005 return "$@ running calc_setup for $cust_pkg\n";
2008 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2010 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
2014 # bill recurring fee
2017 #XXX unit stuff here too
2021 if ( $part_pkg->getfield('freq') ne '0' &&
2022 ! $cust_pkg->getfield('susp') &&
2023 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2026 # XXX should this be a package event? probably. events are called
2027 # at collection time at the moment, though...
2028 if ( $part_pkg->can('reset_usage') ) {
2029 warn " resetting usage counters" if $DEBUG > 1;
2030 $part_pkg->reset_usage($cust_pkg);
2033 warn " bill recur\n" if $DEBUG > 1;
2035 # XXX shared with $recur_prog
2036 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2038 #over two params! lets at least switch to a hashref for the rest...
2039 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
2041 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2043 $dbh->rollback if $oldAutoCommit;
2044 return "$@ running calc_recur for $cust_pkg\n";
2047 #change this bit to use Date::Manip? CAREFUL with timezones (see
2048 # mailing list archive)
2049 my ($sec,$min,$hour,$mday,$mon,$year) =
2050 (localtime($sdate) )[0,1,2,3,4,5];
2052 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2053 # only for figuring next bill date, nothing else, so, reset $sdate again
2055 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2056 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2057 $cust_pkg->last_bill($sdate);
2059 if ( $part_pkg->freq =~ /^\d+$/ ) {
2060 $mon += $part_pkg->freq;
2061 until ( $mon < 12 ) { $mon -= 12; $year++; }
2062 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2064 $mday += $weeks * 7;
2065 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2068 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2072 $dbh->rollback if $oldAutoCommit;
2073 return "unparsable frequency: ". $part_pkg->freq;
2075 $cust_pkg->setfield('bill',
2076 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2079 warn "\$setup is undefined" unless defined($setup);
2080 warn "\$recur is undefined" unless defined($recur);
2081 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2084 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2087 if ( $cust_pkg->modified ) { # hmmm.. and if the options are modified?
2089 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2092 $error=$cust_pkg->replace($old_cust_pkg,
2093 options => { $cust_pkg->options },
2095 if ( $error ) { #just in case
2096 $dbh->rollback if $oldAutoCommit;
2097 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2100 $setup = sprintf( "%.2f", $setup );
2101 $recur = sprintf( "%.2f", $recur );
2102 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2103 $dbh->rollback if $oldAutoCommit;
2104 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2106 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2107 $dbh->rollback if $oldAutoCommit;
2108 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2111 if ( $setup != 0 || $recur != 0 ) {
2113 unless ($postal_charge) {
2114 $postal_charge = 1; # try only once
2115 my $postal_pkg = $self->charge_postal_fee();
2116 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2117 $dbh->rollback if $oldAutoCommit;
2118 return "can't charge postal invoice fee for customer ".
2119 $self->custnum. ": $postal_pkg";
2121 push @cust_pkgs, $postal_pkg if $postal_pkg;
2124 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2127 push @details, map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2129 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2130 'invnum' => $invnum,
2131 'pkgnum' => $cust_pkg->pkgnum,
2133 'unitsetup' => $unitsetup,
2135 'unitrecur' => $unitrecur,
2136 'quantity' => $cust_pkg->quantity,
2137 'details' => \@details,
2140 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
2141 $cust_bill_pkg->sdate( $hash{last_bill} );
2142 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2143 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
2144 $cust_bill_pkg->sdate( $sdate );
2145 $cust_bill_pkg->edate( $cust_pkg->bill );
2148 $error = $cust_bill_pkg->insert;
2150 $dbh->rollback if $oldAutoCommit;
2151 return "can't create invoice line item for invoice #$invnum: $error";
2153 $total_setup += $setup;
2154 $total_recur += $recur;
2160 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2163 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2166 my %taxhash = map { $_ => $self->get("$prefix$_") }
2167 qw( state county country );
2169 $taxhash{'taxclass'} = $part_pkg->taxclass;
2171 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2174 $taxhash{'taxclass'} = '';
2175 @taxes = qsearch( 'cust_main_county', \%taxhash );
2178 #one more try at a whole-country tax rate
2180 $taxhash{$_} = '' foreach qw( state county );
2181 @taxes = qsearch( 'cust_main_county', \%taxhash );
2184 # maybe eliminate this entirely, along with all the 0% records
2186 $dbh->rollback if $oldAutoCommit;
2188 "fatal: can't find tax rate for state/county/country/taxclass ".
2189 join('/', ( map $self->get("$prefix$_"),
2190 qw(state county country)
2192 $part_pkg->taxclass ). "\n";
2195 foreach my $tax ( @taxes ) {
2197 my $taxable_charged = 0;
2198 $taxable_charged += $setup
2199 unless $part_pkg->setuptax =~ /^Y$/i
2200 || $tax->setuptax =~ /^Y$/i;
2201 $taxable_charged += $recur
2202 unless $part_pkg->recurtax =~ /^Y$/i
2203 || $tax->recurtax =~ /^Y$/i;
2204 next unless $taxable_charged;
2206 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2207 #my ($mon,$year) = (localtime($sdate) )[4,5];
2208 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2210 my $freq = $part_pkg->freq || 1;
2211 if ( $freq !~ /(\d+)$/ ) {
2212 $dbh->rollback if $oldAutoCommit;
2213 return "daily/weekly package definitions not (yet?)".
2214 " compatible with monthly tax exemptions";
2216 my $taxable_per_month =
2217 sprintf("%.2f", $taxable_charged / $freq );
2219 #call the whole thing off if this customer has any old
2220 #exemption records...
2221 my @cust_tax_exempt =
2222 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2223 if ( @cust_tax_exempt ) {
2224 $dbh->rollback if $oldAutoCommit;
2226 'this customer still has old-style tax exemption records; '.
2227 'run bin/fs-migrate-cust_tax_exempt?';
2230 foreach my $which_month ( 1 .. $freq ) {
2232 #maintain the new exemption table now
2235 FROM cust_tax_exempt_pkg
2236 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2237 LEFT JOIN cust_bill USING ( invnum )
2243 my $sth = dbh->prepare($sql) or do {
2244 $dbh->rollback if $oldAutoCommit;
2245 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2253 $dbh->rollback if $oldAutoCommit;
2254 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2256 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2258 my $remaining_exemption =
2259 $tax->exempt_amount - $existing_exemption;
2260 if ( $remaining_exemption > 0 ) {
2261 my $addl = $remaining_exemption > $taxable_per_month
2262 ? $taxable_per_month
2263 : $remaining_exemption;
2264 $taxable_charged -= $addl;
2266 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2267 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2268 'taxnum' => $tax->taxnum,
2269 'year' => 1900+$year,
2271 'amount' => sprintf("%.2f", $addl ),
2273 $error = $cust_tax_exempt_pkg->insert;
2275 $dbh->rollback if $oldAutoCommit;
2276 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2278 } # if $remaining_exemption > 0
2282 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2283 until ( $mon < 13 ) { $mon -= 12; $year++; }
2285 } #foreach $which_month
2287 } #if $tax->exempt_amount
2289 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2291 #$tax += $taxable_charged * $cust_main_county->tax / 100
2292 $tax{ $tax->taxname || 'Tax' } +=
2293 $taxable_charged * $tax->tax / 100
2295 } #foreach my $tax ( @taxes )
2297 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2299 } #if $setup != 0 || $recur != 0
2301 } #if $cust_pkg->modified
2303 } #foreach my $cust_pkg
2305 unless ( $cust_bill->cust_bill_pkg ) {
2306 $cust_bill->delete; #don't create an invoice w/o line items
2307 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2311 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2313 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2314 my $tax = sprintf("%.2f", $tax{$taxname} );
2315 $charged = sprintf( "%.2f", $charged+$tax );
2317 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2318 'invnum' => $invnum,
2324 'itemdesc' => $taxname,
2326 $error = $cust_bill_pkg->insert;
2328 $dbh->rollback if $oldAutoCommit;
2329 return "can't create invoice line item for invoice #$invnum: $error";
2331 $total_setup += $tax;
2335 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2336 $error = $cust_bill->replace;
2338 $dbh->rollback if $oldAutoCommit;
2339 return "can't update charged for invoice #$invnum: $error";
2342 foreach my $hook ( @precommit_hooks ) {
2344 &{$hook}; #($self) ?
2347 $dbh->rollback if $oldAutoCommit;
2348 return "$@ running precommit hook $hook\n";
2352 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2356 =item collect OPTIONS
2358 (Attempt to) collect money for this customer's outstanding invoices (see
2359 L<FS::cust_bill>). Usually used after the bill method.
2361 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2362 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2363 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2365 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2366 and the invoice events web interface.
2368 If there is an error, returns the error, otherwise returns false.
2370 Options are passed as name-value pairs.
2372 Currently available options are:
2374 invoice_time - Use this time when deciding when to print invoices and
2375 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>
2376 for conversion functions.
2378 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2381 quiet - set true to surpress email card/ACH decline notices.
2383 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2386 payby - allows for one time override of normal customer billing method
2391 my( $self, %options ) = @_;
2392 my $invoice_time = $options{'invoice_time'} || time;
2395 local $SIG{HUP} = 'IGNORE';
2396 local $SIG{INT} = 'IGNORE';
2397 local $SIG{QUIT} = 'IGNORE';
2398 local $SIG{TERM} = 'IGNORE';
2399 local $SIG{TSTP} = 'IGNORE';
2400 local $SIG{PIPE} = 'IGNORE';
2402 my $oldAutoCommit = $FS::UID::AutoCommit;
2403 local $FS::UID::AutoCommit = 0;
2406 $self->select_for_update; #mutex
2408 my $balance = $self->balance;
2409 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2411 unless ( $balance > 0 ) { #redundant?????
2412 $dbh->rollback if $oldAutoCommit; #hmm
2416 if ( exists($options{'retry_card'}) ) {
2417 carp 'retry_card option passed to collect is deprecated; use retry';
2418 $options{'retry'} ||= $options{'retry_card'};
2420 if ( exists($options{'retry'}) && $options{'retry'} ) {
2421 my $error = $self->retry_realtime;
2423 $dbh->rollback if $oldAutoCommit;
2429 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2430 $extra_sql = " AND freq = '1m' ";
2432 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2435 foreach my $cust_bill ( $self->open_cust_bill ) {
2437 # don't try to charge for the same invoice if it's already in a batch
2438 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2440 last if $self->balance <= 0;
2442 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2445 foreach my $part_bill_event ( due_events ( $cust_bill,
2446 exists($options{'payby'})
2452 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2453 || $self->balance <= 0; # or if balance<=0
2456 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2457 warn " do_event " . $cust_bill . " ". (%options) . "\n"
2460 if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2461 # gah, even with transactions.
2462 $dbh->commit if $oldAutoCommit; #well.
2471 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2476 =item retry_realtime
2478 Schedules realtime / batch credit card / electronic check / LEC billing
2479 events for for retry. Useful if card information has changed or manual
2480 retry is desired. The 'collect' method must be called to actually retry
2483 Implementation details: For each of this customer's open invoices, changes
2484 the status of the first "done" (with statustext error) realtime processing
2489 sub retry_realtime {
2492 local $SIG{HUP} = 'IGNORE';
2493 local $SIG{INT} = 'IGNORE';
2494 local $SIG{QUIT} = 'IGNORE';
2495 local $SIG{TERM} = 'IGNORE';
2496 local $SIG{TSTP} = 'IGNORE';
2497 local $SIG{PIPE} = 'IGNORE';
2499 my $oldAutoCommit = $FS::UID::AutoCommit;
2500 local $FS::UID::AutoCommit = 0;
2503 foreach my $cust_bill (
2504 grep { $_->cust_bill_event }
2505 $self->open_cust_bill
2507 my @cust_bill_event =
2508 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2510 #$_->part_bill_event->plan eq 'realtime-card'
2511 $_->part_bill_event->eventcode =~
2512 /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2513 && $_->status eq 'done'
2516 $cust_bill->cust_bill_event;
2517 next unless @cust_bill_event;
2518 my $error = $cust_bill_event[0]->retry;
2520 $dbh->rollback if $oldAutoCommit;
2521 return "error scheduling invoice event for retry: $error";
2526 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2531 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2533 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2534 via a Business::OnlinePayment realtime gateway. See
2535 L<http://420.am/business-onlinepayment> for supported gateways.
2537 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2539 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
2541 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2542 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2543 if set, will override the value from the customer record.
2545 I<description> is a free-text field passed to the gateway. It defaults to
2546 "Internet services".
2548 If an I<invnum> is specified, this payment (if successful) is applied to the
2549 specified invoice. If you don't specify an I<invnum> you might want to
2550 call the B<apply_payments> method.
2552 I<quiet> can be set true to surpress email decline notices.
2554 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
2555 resulting paynum, if any.
2557 I<payunique> is a unique identifier for this payment.
2559 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2566 my( $self, $method, $amount, %options ) = @_;
2568 warn "$me realtime_bop: $method $amount\n";
2569 warn " $_ => $options{$_}\n" foreach keys %options;
2572 $options{'description'} ||= 'Internet services';
2574 eval "use Business::OnlinePayment";
2577 my $payinfo = exists($options{'payinfo'})
2578 ? $options{'payinfo'}
2581 my %method2payby = (
2592 if ( $options{'invnum'} ) {
2593 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2594 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2596 map { $_->part_pkg->taxclass }
2598 map { $_->cust_pkg }
2599 $cust_bill->cust_bill_pkg;
2600 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2601 #different taxclasses
2602 $taxclass = $taxclasses[0];
2606 #look for an agent gateway override first
2608 if ( $method eq 'CC' ) {
2609 $cardtype = cardtype($payinfo);
2610 } elsif ( $method eq 'ECHECK' ) {
2613 $cardtype = $method;
2617 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2618 cardtype => $cardtype,
2619 taxclass => $taxclass, } )
2620 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2622 taxclass => $taxclass, } )
2623 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2624 cardtype => $cardtype,
2626 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2628 taxclass => '', } );
2630 my $payment_gateway = '';
2631 my( $processor, $login, $password, $action, @bop_options );
2632 if ( $override ) { #use a payment gateway override
2634 $payment_gateway = $override->payment_gateway;
2636 $processor = $payment_gateway->gateway_module;
2637 $login = $payment_gateway->gateway_username;
2638 $password = $payment_gateway->gateway_password;
2639 $action = $payment_gateway->gateway_action;
2640 @bop_options = $payment_gateway->options;
2642 } else { #use the standard settings from the config
2644 ( $processor, $login, $password, $action, @bop_options ) =
2645 $self->default_payment_gateway($method);
2653 my $address = exists($options{'address1'})
2654 ? $options{'address1'}
2656 my $address2 = exists($options{'address2'})
2657 ? $options{'address2'}
2659 $address .= ", ". $address2 if length($address2);
2661 my $o_payname = exists($options{'payname'})
2662 ? $options{'payname'}
2664 my($payname, $payfirst, $paylast);
2665 if ( $o_payname && $method ne 'ECHECK' ) {
2666 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2667 or return "Illegal payname $payname";
2668 ($payfirst, $paylast) = ($1, $2);
2670 $payfirst = $self->getfield('first');
2671 $paylast = $self->getfield('last');
2672 $payname = "$payfirst $paylast";
2675 my @invoicing_list = $self->invoicing_list_emailonly;
2676 if ( $conf->exists('emailinvoiceautoalways')
2677 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
2678 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2679 push @invoicing_list, $self->all_emails;
2682 my $email = ($conf->exists('business-onlinepayment-email-override'))
2683 ? $conf->config('business-onlinepayment-email-override')
2684 : $invoicing_list[0];
2688 my $payip = exists($options{'payip'})
2691 $content{customer_ip} = $payip
2694 $content{invoice_number} = $options{'invnum'}
2695 if exists($options{'invnum'}) && length($options{'invnum'});
2697 $content{email_customer} =
2698 ( $conf->exists('business-onlinepayment-email_customer')
2699 || $conf->exists('business-onlinepayment-email-override') );
2702 if ( $method eq 'CC' ) {
2704 $content{card_number} = $payinfo;
2705 $paydate = exists($options{'paydate'})
2706 ? $options{'paydate'}
2708 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2709 $content{expiration} = "$2/$1";
2711 my $paycvv = exists($options{'paycvv'})
2712 ? $options{'paycvv'}
2714 $content{cvv2} = $paycvv
2717 my $paystart_month = exists($options{'paystart_month'})
2718 ? $options{'paystart_month'}
2719 : $self->paystart_month;
2721 my $paystart_year = exists($options{'paystart_year'})
2722 ? $options{'paystart_year'}
2723 : $self->paystart_year;
2725 $content{card_start} = "$paystart_month/$paystart_year"
2726 if $paystart_month && $paystart_year;
2728 my $payissue = exists($options{'payissue'})
2729 ? $options{'payissue'}
2731 $content{issue_number} = $payissue if $payissue;
2733 $content{recurring_billing} = 'YES'
2734 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2736 'payinfo' => $payinfo,
2738 || qsearch('cust_pay', { 'custnum' => $self->custnum,
2740 'paymask' => $self->mask_payinfo('CARD', $payinfo),
2744 } elsif ( $method eq 'ECHECK' ) {
2745 ( $content{account_number}, $content{routing_code} ) =
2746 split('@', $payinfo);
2747 $content{bank_name} = $o_payname;
2748 $content{bank_state} = exists($options{'paystate'})
2749 ? $options{'paystate'}
2750 : $self->getfield('paystate');
2751 $content{account_type} = exists($options{'paytype'})
2752 ? uc($options{'paytype'}) || 'CHECKING'
2753 : uc($self->getfield('paytype')) || 'CHECKING';
2754 $content{account_name} = $payname;
2755 $content{customer_org} = $self->company ? 'B' : 'I';
2756 $content{state_id} = exists($options{'stateid'})
2757 ? $options{'stateid'}
2758 : $self->getfield('stateid');
2759 $content{state_id_state} = exists($options{'stateid_state'})
2760 ? $options{'stateid_state'}
2761 : $self->getfield('stateid_state');
2762 $content{customer_ssn} = exists($options{'ss'})
2765 } elsif ( $method eq 'LEC' ) {
2766 $content{phone} = $payinfo;
2770 # run transaction(s)
2773 my $balance = exists( $options{'balance'} )
2774 ? $options{'balance'}
2777 $self->select_for_update; #mutex ... just until we get our pending record in
2779 #the checks here are intended to catch concurrent payments
2780 #double-form-submission prevention is taken care of in cust_pay_pending::check
2783 return "The customer's balance has changed; $method transaction aborted."
2784 if $self->balance < $balance;
2785 #&& $self->balance < $amount; #might as well anyway?
2787 #also check and make sure there aren't *other* pending payments for this cust
2789 my @pending = qsearch('cust_pay_pending', {
2790 'custnum' => $self->custnum,
2791 'status' => { op=>'!=', value=>'done' }
2793 return "A payment is already being processed for this customer (".
2794 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
2795 "); $method transaction aborted."
2796 if scalar(@pending);
2798 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
2800 my $cust_pay_pending = new FS::cust_pay_pending {
2801 'custnum' => $self->custnum,
2802 #'invnum' => $options{'invnum'},
2805 'payby' => $method2payby{$method},
2806 'payinfo' => $payinfo,
2807 'paydate' => $paydate,
2809 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
2811 $cust_pay_pending->payunique( $options{payunique} )
2812 if defined($options{payunique}) && length($options{payunique});
2813 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
2814 return $cpp_new_err if $cpp_new_err;
2816 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2818 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2819 $transaction->content(
2822 'password' => $password,
2823 'action' => $action1,
2824 'description' => $options{'description'},
2825 'amount' => $amount,
2826 #'invoice_number' => $options{'invnum'},
2827 'customer_id' => $self->custnum,
2828 'last_name' => $paylast,
2829 'first_name' => $payfirst,
2831 'address' => $address,
2832 'city' => ( exists($options{'city'})
2835 'state' => ( exists($options{'state'})
2838 'zip' => ( exists($options{'zip'})
2841 'country' => ( exists($options{'country'})
2842 ? $options{'country'}
2844 'referer' => 'http://cleanwhisker.420.am/',
2846 'phone' => $self->daytime || $self->night,
2850 $cust_pay_pending->status('pending');
2851 my $cpp_pending_err = $cust_pay_pending->replace;
2852 return $cpp_pending_err if $cpp_pending_err;
2854 $transaction->submit();
2856 if ( $transaction->is_success() && $action2 ) {
2858 $cust_pay_pending->status('authorized');
2859 my $cpp_authorized_err = $cust_pay_pending->replace;
2860 return $cpp_authorized_err if $cpp_authorized_err;
2862 my $auth = $transaction->authorization;
2863 my $ordernum = $transaction->can('order_number')
2864 ? $transaction->order_number
2868 new Business::OnlinePayment( $processor, @bop_options );
2875 password => $password,
2876 order_number => $ordernum,
2878 authorization => $auth,
2879 description => $options{'description'},
2882 foreach my $field (qw( authorization_source_code returned_ACI
2883 transaction_identifier validation_code
2884 transaction_sequence_num local_transaction_date
2885 local_transaction_time AVS_result_code )) {
2886 $capture{$field} = $transaction->$field() if $transaction->can($field);
2889 $capture->content( %capture );
2893 unless ( $capture->is_success ) {
2894 my $e = "Authorization successful but capture failed, custnum #".
2895 $self->custnum. ': '. $capture->result_code.
2896 ": ". $capture->error_message;
2903 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
2904 my $cpp_captured_err = $cust_pay_pending->replace;
2905 return $cpp_captured_err if $cpp_captured_err;
2908 # remove paycvv after initial transaction
2911 #false laziness w/misc/process/payment.cgi - check both to make sure working
2913 if ( defined $self->dbdef_table->column('paycvv')
2914 && length($self->paycvv)
2915 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2917 my $error = $self->remove_cvv;
2919 warn "WARNING: error removing cvv: $error\n";
2927 if ( $transaction->is_success() ) {
2930 if ( $payment_gateway ) { # agent override
2931 $paybatch = $payment_gateway->gatewaynum. '-';
2934 $paybatch .= "$processor:". $transaction->authorization;
2936 $paybatch .= ':'. $transaction->order_number
2937 if $transaction->can('order_number')
2938 && length($transaction->order_number);
2940 my $cust_pay = new FS::cust_pay ( {
2941 'custnum' => $self->custnum,
2942 'invnum' => $options{'invnum'},
2945 'payby' => $method2payby{$method},
2946 'payinfo' => $payinfo,
2947 'paybatch' => $paybatch,
2948 'paydate' => $paydate,
2950 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
2951 $cust_pay->payunique( $options{payunique} )
2952 if defined($options{payunique}) && length($options{payunique});
2954 my $oldAutoCommit = $FS::UID::AutoCommit;
2955 local $FS::UID::AutoCommit = 0;
2958 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
2960 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
2963 $cust_pay->invnum(''); #try again with no specific invnum
2964 my $error2 = $cust_pay->insert( $options{'manual'} ?
2965 ( 'manual' => 1 ) : ()
2968 # gah. but at least we have a record of the state we had to abort in
2969 # from cust_pay_pending now.
2970 my $e = "WARNING: $method captured but payment not recorded - ".
2971 "error inserting payment ($processor): $error2".
2972 " (previously tried insert with invnum #$options{'invnum'}" .
2973 ": $error ) - pending payment saved as paypendingnum ".
2974 $cust_pay_pending->paypendingnum. "\n";
2980 if ( $options{'paynum_ref'} ) {
2981 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
2984 $cust_pay_pending->status('done');
2985 $cust_pay_pending->statustext('captured');
2986 my $cpp_done_err = $cust_pay_pending->replace;
2988 if ( $cpp_done_err ) {
2990 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2991 my $e = "WARNING: $method captured but payment not recorded - ".
2992 "error updating status for paypendingnum ".
2993 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
2999 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3000 return ''; #no error
3006 my $perror = "$processor error: ". $transaction->error_message;
3008 unless ( $transaction->error_message ) {
3011 #this should be normalized :/
3013 # bad, ad-hoc B:OP:PayflowPro "transaction_response" BS
3014 if ( $transaction->can('param')
3015 && $transaction->param('transaction_response') ) {
3016 $t_response = $transaction->param('transaction_response')
3018 # slightly better, ad-hoc B:OP:TransactionCentral without "param"
3019 } elsif ( $transaction->can('response_page') ) {
3021 'page' => ( $transaction->can('response_page')
3022 ? $transaction->response_page
3025 'code' => ( $transaction->can('response_code')
3026 ? $transaction->response_code
3029 'headers' => ( $transaction->can('response_headers')
3030 ? $transaction->response_headers
3036 "No additional debugging information available for $processor";
3039 $perror .= "No error_message returned from $processor -- ".
3040 ( ref($t_response) ? Dumper($t_response) : $t_response );
3044 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3045 && $conf->exists('emaildecline')
3046 && grep { $_ ne 'POST' } $self->invoicing_list
3047 && ! grep { $transaction->error_message =~ /$_/ }
3048 $conf->config('emaildecline-exclude')
3050 my @templ = $conf->config('declinetemplate');
3051 my $template = new Text::Template (
3053 SOURCE => [ map "$_\n", @templ ],
3054 ) or return "($perror) can't create template: $Text::Template::ERROR";
3055 $template->compile()
3056 or return "($perror) can't compile template: $Text::Template::ERROR";
3058 my $templ_hash = { error => $transaction->error_message };
3060 my $error = send_email(
3061 'from' => $conf->config('invoice_from'),
3062 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3063 'subject' => 'Your payment could not be processed',
3064 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3067 $perror .= " (also received error sending decline notification: $error)"
3072 $cust_pay_pending->status('done');
3073 $cust_pay_pending->statustext("declined: $perror");
3074 my $cpp_done_err = $cust_pay_pending->replace;
3075 if ( $cpp_done_err ) {
3076 my $e = "WARNING: $method declined but pending payment not resolved - ".
3077 "error updating status for paypendingnum ".
3078 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3080 $perror = "$e ($perror)";
3088 =item default_payment_gateway
3092 sub default_payment_gateway {
3093 my( $self, $method ) = @_;
3095 die "Real-time processing not enabled\n"
3096 unless $conf->exists('business-onlinepayment');
3099 my $bop_config = 'business-onlinepayment';
3100 $bop_config .= '-ach'
3101 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3102 my ( $processor, $login, $password, $action, @bop_options ) =
3103 $conf->config($bop_config);
3104 $action ||= 'normal authorization';
3105 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3106 die "No real-time processor is enabled - ".
3107 "did you set the business-onlinepayment configuration value?\n"
3110 ( $processor, $login, $password, $action, @bop_options )
3115 Removes the I<paycvv> field from the database directly.
3117 If there is an error, returns the error, otherwise returns false.
3123 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3124 or return dbh->errstr;
3125 $sth->execute($self->custnum)
3126 or return $sth->errstr;
3131 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3133 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3134 via a Business::OnlinePayment realtime gateway. See
3135 L<http://420.am/business-onlinepayment> for supported gateways.
3137 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3139 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3141 Most gateways require a reference to an original payment transaction to refund,
3142 so you probably need to specify a I<paynum>.
3144 I<amount> defaults to the original amount of the payment if not specified.
3146 I<reason> specifies a reason for the refund.
3148 I<paydate> specifies the expiration date for a credit card overriding the
3149 value from the customer record or the payment record. Specified as yyyy-mm-dd
3151 Implementation note: If I<amount> is unspecified or equal to the amount of the
3152 orignal payment, first an attempt is made to "void" the transaction via
3153 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3154 the normal attempt is made to "refund" ("credit") the transaction via the
3155 gateway is attempted.
3157 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3158 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3159 #if set, will override the value from the customer record.
3161 #If an I<invnum> is specified, this payment (if successful) is applied to the
3162 #specified invoice. If you don't specify an I<invnum> you might want to
3163 #call the B<apply_payments> method.
3167 #some false laziness w/realtime_bop, not enough to make it worth merging
3168 #but some useful small subs should be pulled out
3169 sub realtime_refund_bop {
3170 my( $self, $method, %options ) = @_;
3172 warn "$me realtime_refund_bop: $method refund\n";
3173 warn " $_ => $options{$_}\n" foreach keys %options;
3176 eval "use Business::OnlinePayment";
3180 # look up the original payment and optionally a gateway for that payment
3184 my $amount = $options{'amount'};
3186 my( $processor, $login, $password, @bop_options ) ;
3187 my( $auth, $order_number ) = ( '', '', '' );
3189 if ( $options{'paynum'} ) {
3191 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3192 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3193 or return "Unknown paynum $options{'paynum'}";
3194 $amount ||= $cust_pay->paid;
3196 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3197 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3198 $cust_pay->paybatch;
3199 my $gatewaynum = '';
3200 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3202 if ( $gatewaynum ) { #gateway for the payment to be refunded
3204 my $payment_gateway =
3205 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3206 die "payment gateway $gatewaynum not found"
3207 unless $payment_gateway;
3209 $processor = $payment_gateway->gateway_module;
3210 $login = $payment_gateway->gateway_username;
3211 $password = $payment_gateway->gateway_password;
3212 @bop_options = $payment_gateway->options;
3214 } else { #try the default gateway
3216 my( $conf_processor, $unused_action );
3217 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3218 $self->default_payment_gateway($method);
3220 return "processor of payment $options{'paynum'} $processor does not".
3221 " match default processor $conf_processor"
3222 unless $processor eq $conf_processor;
3227 } else { # didn't specify a paynum, so look for agent gateway overrides
3228 # like a normal transaction
3231 if ( $method eq 'CC' ) {
3232 $cardtype = cardtype($self->payinfo);
3233 } elsif ( $method eq 'ECHECK' ) {
3236 $cardtype = $method;
3239 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3240 cardtype => $cardtype,
3242 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3244 taxclass => '', } );
3246 if ( $override ) { #use a payment gateway override
3248 my $payment_gateway = $override->payment_gateway;
3250 $processor = $payment_gateway->gateway_module;
3251 $login = $payment_gateway->gateway_username;
3252 $password = $payment_gateway->gateway_password;
3253 #$action = $payment_gateway->gateway_action;
3254 @bop_options = $payment_gateway->options;
3256 } else { #use the standard settings from the config
3259 ( $processor, $login, $password, $unused_action, @bop_options ) =
3260 $self->default_payment_gateway($method);
3265 return "neither amount nor paynum specified" unless $amount;
3270 'password' => $password,
3271 'order_number' => $order_number,
3272 'amount' => $amount,
3273 'referer' => 'http://cleanwhisker.420.am/',
3275 $content{authorization} = $auth
3276 if length($auth); #echeck/ACH transactions have an order # but no auth
3277 #(at least with authorize.net)
3279 my $disable_void_after;
3280 if ($conf->exists('disable_void_after')
3281 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3282 $disable_void_after = $1;
3285 #first try void if applicable
3286 if ( $cust_pay && $cust_pay->paid == $amount
3288 ( not defined($disable_void_after) )
3289 || ( time < ($cust_pay->_date + $disable_void_after ) )
3292 warn " attempting void\n" if $DEBUG > 1;
3293 my $void = new Business::OnlinePayment( $processor, @bop_options );
3294 $void->content( 'action' => 'void', %content );
3296 if ( $void->is_success ) {
3297 my $error = $cust_pay->void($options{'reason'});
3299 # gah, even with transactions.
3300 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3301 "error voiding payment: $error";
3305 warn " void successful\n" if $DEBUG > 1;
3310 warn " void unsuccessful, trying refund\n"
3314 my $address = $self->address1;
3315 $address .= ", ". $self->address2 if $self->address2;
3317 my($payname, $payfirst, $paylast);
3318 if ( $self->payname && $method ne 'ECHECK' ) {
3319 $payname = $self->payname;
3320 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3321 or return "Illegal payname $payname";
3322 ($payfirst, $paylast) = ($1, $2);
3324 $payfirst = $self->getfield('first');
3325 $paylast = $self->getfield('last');
3326 $payname = "$payfirst $paylast";
3329 my @invoicing_list = $self->invoicing_list_emailonly;
3330 if ( $conf->exists('emailinvoiceautoalways')
3331 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3332 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3333 push @invoicing_list, $self->all_emails;
3336 my $email = ($conf->exists('business-onlinepayment-email-override'))
3337 ? $conf->config('business-onlinepayment-email-override')
3338 : $invoicing_list[0];
3340 my $payip = exists($options{'payip'})
3343 $content{customer_ip} = $payip
3347 if ( $method eq 'CC' ) {
3350 $content{card_number} = $payinfo = $cust_pay->payinfo;
3351 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3352 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3353 ($content{expiration} = "$2/$1"); # where available
3355 $content{card_number} = $payinfo = $self->payinfo;
3356 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3357 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3358 $content{expiration} = "$2/$1";
3361 } elsif ( $method eq 'ECHECK' ) {
3364 $payinfo = $cust_pay->payinfo;
3366 $payinfo = $self->payinfo;
3368 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3369 $content{bank_name} = $self->payname;
3370 $content{account_type} = 'CHECKING';
3371 $content{account_name} = $payname;
3372 $content{customer_org} = $self->company ? 'B' : 'I';
3373 $content{customer_ssn} = $self->ss;
3374 } elsif ( $method eq 'LEC' ) {
3375 $content{phone} = $payinfo = $self->payinfo;
3379 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3380 my %sub_content = $refund->content(
3381 'action' => 'credit',
3382 'customer_id' => $self->custnum,
3383 'last_name' => $paylast,
3384 'first_name' => $payfirst,
3386 'address' => $address,
3387 'city' => $self->city,
3388 'state' => $self->state,
3389 'zip' => $self->zip,
3390 'country' => $self->country,
3392 'phone' => $self->daytime || $self->night,
3395 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3399 return "$processor error: ". $refund->error_message
3400 unless $refund->is_success();
3402 my %method2payby = (
3408 my $paybatch = "$processor:". $refund->authorization;
3409 $paybatch .= ':'. $refund->order_number
3410 if $refund->can('order_number') && $refund->order_number;
3412 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3413 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3414 last unless @cust_bill_pay;
3415 my $cust_bill_pay = pop @cust_bill_pay;
3416 my $error = $cust_bill_pay->delete;
3420 my $cust_refund = new FS::cust_refund ( {
3421 'custnum' => $self->custnum,
3422 'paynum' => $options{'paynum'},
3423 'refund' => $amount,
3425 'payby' => $method2payby{$method},
3426 'payinfo' => $payinfo,
3427 'paybatch' => $paybatch,
3428 'reason' => $options{'reason'} || 'card or ACH refund',
3430 my $error = $cust_refund->insert;
3432 $cust_refund->paynum(''); #try again with no specific paynum
3433 my $error2 = $cust_refund->insert;
3435 # gah, even with transactions.
3436 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3437 "error inserting refund ($processor): $error2".
3438 " (previously tried insert with paynum #$options{'paynum'}" .
3449 =item batch_card OPTION => VALUE...
3451 Adds a payment for this invoice to the pending credit card batch (see
3452 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3453 runs the payment using a realtime gateway.
3458 my ($self, %options) = @_;
3461 if (exists($options{amount})) {
3462 $amount = $options{amount};
3464 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3466 return '' unless $amount > 0;
3468 my $invnum = delete $options{invnum};
3469 my $payby = $options{invnum} || $self->payby; #dubious
3471 if ($options{'realtime'}) {
3472 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3478 my $oldAutoCommit = $FS::UID::AutoCommit;
3479 local $FS::UID::AutoCommit = 0;
3482 #this needs to handle mysql as well as Pg, like svc_acct.pm
3483 #(make it into a common function if folks need to do batching with mysql)
3484 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3485 or return "Cannot lock pay_batch: " . $dbh->errstr;
3489 'payby' => FS::payby->payby2payment($payby),
3492 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3494 unless ( $pay_batch ) {
3495 $pay_batch = new FS::pay_batch \%pay_batch;
3496 my $error = $pay_batch->insert;
3498 $dbh->rollback if $oldAutoCommit;
3499 die "error creating new batch: $error\n";
3503 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3504 'batchnum' => $pay_batch->batchnum,
3505 'custnum' => $self->custnum,
3508 foreach (qw( address1 address2 city state zip country payby payinfo paydate
3510 $options{$_} = '' unless exists($options{$_});
3513 my $cust_pay_batch = new FS::cust_pay_batch ( {
3514 'batchnum' => $pay_batch->batchnum,
3515 'invnum' => $invnum || 0, # is there a better value?
3516 # this field should be
3518 # cust_bill_pay_batch now
3519 'custnum' => $self->custnum,
3520 'last' => $self->getfield('last'),
3521 'first' => $self->getfield('first'),
3522 'address1' => $options{address1} || $self->address1,
3523 'address2' => $options{address2} || $self->address2,
3524 'city' => $options{city} || $self->city,
3525 'state' => $options{state} || $self->state,
3526 'zip' => $options{zip} || $self->zip,
3527 'country' => $options{country} || $self->country,
3528 'payby' => $options{payby} || $self->payby,
3529 'payinfo' => $options{payinfo} || $self->payinfo,
3530 'exp' => $options{paydate} || $self->paydate,
3531 'payname' => $options{payname} || $self->payname,
3532 'amount' => $amount, # consolidating
3535 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3536 if $old_cust_pay_batch;
3539 if ($old_cust_pay_batch) {
3540 $error = $cust_pay_batch->replace($old_cust_pay_batch)
3542 $error = $cust_pay_batch->insert;
3546 $dbh->rollback if $oldAutoCommit;
3550 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
3551 foreach my $cust_bill ($self->open_cust_bill) {
3552 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3553 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3554 'invnum' => $cust_bill->invnum,
3555 'paybatchnum' => $cust_pay_batch->paybatchnum,
3556 'amount' => $cust_bill->owed,
3559 if ($unapplied >= $cust_bill_pay_batch->amount){
3560 $unapplied -= $cust_bill_pay_batch->amount;
3563 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
3564 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
3566 $error = $cust_bill_pay_batch->insert;
3568 $dbh->rollback if $oldAutoCommit;
3573 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3579 Returns the total owed for this customer on all invoices
3580 (see L<FS::cust_bill/owed>).
3586 $self->total_owed_date(2145859200); #12/31/2037
3589 =item total_owed_date TIME
3591 Returns the total owed for this customer on all invoices with date earlier than
3592 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3593 see L<Time::Local> and L<Date::Parse> for conversion functions.
3597 sub total_owed_date {
3601 foreach my $cust_bill (
3602 grep { $_->_date <= $time }
3603 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3605 $total_bill += $cust_bill->owed;
3607 sprintf( "%.2f", $total_bill );
3610 =item apply_payments_and_credits
3612 Applies unapplied payments and credits.
3614 In most cases, this new method should be used in place of sequential
3615 apply_payments and apply_credits methods.
3617 If there is an error, returns the error, otherwise returns false.
3621 sub apply_payments_and_credits {
3624 local $SIG{HUP} = 'IGNORE';
3625 local $SIG{INT} = 'IGNORE';
3626 local $SIG{QUIT} = 'IGNORE';
3627 local $SIG{TERM} = 'IGNORE';
3628 local $SIG{TSTP} = 'IGNORE';
3629 local $SIG{PIPE} = 'IGNORE';
3631 my $oldAutoCommit = $FS::UID::AutoCommit;
3632 local $FS::UID::AutoCommit = 0;
3635 $self->select_for_update; #mutex
3637 foreach my $cust_bill ( $self->open_cust_bill ) {
3638 my $error = $cust_bill->apply_payments_and_credits;
3640 $dbh->rollback if $oldAutoCommit;
3641 return "Error applying: $error";
3645 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3650 =item apply_credits OPTION => VALUE ...
3652 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3653 to outstanding invoice balances in chronological order (or reverse
3654 chronological order if the I<order> option is set to B<newest>) and returns the
3655 value of any remaining unapplied credits available for refund (see
3656 L<FS::cust_refund>).
3658 Dies if there is an error.
3666 local $SIG{HUP} = 'IGNORE';
3667 local $SIG{INT} = 'IGNORE';
3668 local $SIG{QUIT} = 'IGNORE';
3669 local $SIG{TERM} = 'IGNORE';
3670 local $SIG{TSTP} = 'IGNORE';
3671 local $SIG{PIPE} = 'IGNORE';
3673 my $oldAutoCommit = $FS::UID::AutoCommit;
3674 local $FS::UID::AutoCommit = 0;
3677 $self->select_for_update; #mutex
3679 unless ( $self->total_credited ) {
3680 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3684 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3685 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3687 my @invoices = $self->open_cust_bill;
3688 @invoices = sort { $b->_date <=> $a->_date } @invoices
3689 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3692 foreach my $cust_bill ( @invoices ) {
3695 if ( !defined($credit) || $credit->credited == 0) {
3696 $credit = pop @credits or last;
3699 if ($cust_bill->owed >= $credit->credited) {
3700 $amount=$credit->credited;
3702 $amount=$cust_bill->owed;
3705 my $cust_credit_bill = new FS::cust_credit_bill ( {
3706 'crednum' => $credit->crednum,
3707 'invnum' => $cust_bill->invnum,
3708 'amount' => $amount,
3710 my $error = $cust_credit_bill->insert;
3712 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3716 redo if ($cust_bill->owed > 0);
3720 my $total_credited = $self->total_credited;
3722 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3724 return $total_credited;
3727 =item apply_payments
3729 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3730 to outstanding invoice balances in chronological order.
3732 #and returns the value of any remaining unapplied payments.
3734 Dies if there is an error.
3738 sub apply_payments {
3741 local $SIG{HUP} = 'IGNORE';
3742 local $SIG{INT} = 'IGNORE';
3743 local $SIG{QUIT} = 'IGNORE';
3744 local $SIG{TERM} = 'IGNORE';
3745 local $SIG{TSTP} = 'IGNORE';
3746 local $SIG{PIPE} = 'IGNORE';
3748 my $oldAutoCommit = $FS::UID::AutoCommit;
3749 local $FS::UID::AutoCommit = 0;
3752 $self->select_for_update; #mutex
3756 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3757 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3759 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3760 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3764 foreach my $cust_bill ( @invoices ) {
3767 if ( !defined($payment) || $payment->unapplied == 0 ) {
3768 $payment = pop @payments or last;
3771 if ( $cust_bill->owed >= $payment->unapplied ) {
3772 $amount = $payment->unapplied;
3774 $amount = $cust_bill->owed;
3777 my $cust_bill_pay = new FS::cust_bill_pay ( {
3778 'paynum' => $payment->paynum,
3779 'invnum' => $cust_bill->invnum,
3780 'amount' => $amount,
3782 my $error = $cust_bill_pay->insert;
3784 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3788 redo if ( $cust_bill->owed > 0);
3792 my $total_unapplied_payments = $self->total_unapplied_payments;
3794 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3796 return $total_unapplied_payments;
3799 =item total_credited
3801 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3802 customer. See L<FS::cust_credit/credited>.
3806 sub total_credited {
3808 my $total_credit = 0;
3809 foreach my $cust_credit ( qsearch('cust_credit', {
3810 'custnum' => $self->custnum,
3812 $total_credit += $cust_credit->credited;
3814 sprintf( "%.2f", $total_credit );
3817 =item total_unapplied_payments
3819 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3820 See L<FS::cust_pay/unapplied>.
3824 sub total_unapplied_payments {
3826 my $total_unapplied = 0;
3827 foreach my $cust_pay ( qsearch('cust_pay', {
3828 'custnum' => $self->custnum,
3830 $total_unapplied += $cust_pay->unapplied;
3832 sprintf( "%.2f", $total_unapplied );
3835 =item total_unapplied_refunds
3837 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
3838 customer. See L<FS::cust_refund/unapplied>.
3842 sub total_unapplied_refunds {
3844 my $total_unapplied = 0;
3845 foreach my $cust_refund ( qsearch('cust_refund', {
3846 'custnum' => $self->custnum,
3848 $total_unapplied += $cust_refund->unapplied;
3850 sprintf( "%.2f", $total_unapplied );
3855 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3856 total_credited minus total_unapplied_payments).
3864 + $self->total_unapplied_refunds
3865 - $self->total_credited
3866 - $self->total_unapplied_payments
3870 =item balance_date TIME
3872 Returns the balance for this customer, only considering invoices with date
3873 earlier than TIME (total_owed_date minus total_credited minus
3874 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3875 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3884 $self->total_owed_date($time)
3885 + $self->total_unapplied_refunds
3886 - $self->total_credited
3887 - $self->total_unapplied_payments
3891 =item in_transit_payments
3893 Returns the total of requests for payments for this customer pending in
3894 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3898 sub in_transit_payments {
3900 my $in_transit_payments = 0;
3901 foreach my $pay_batch ( qsearch('pay_batch', {
3904 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3905 'batchnum' => $pay_batch->batchnum,
3906 'custnum' => $self->custnum,
3908 $in_transit_payments += $cust_pay_batch->amount;
3911 sprintf( "%.2f", $in_transit_payments );
3914 =item paydate_monthyear
3916 Returns a two-element list consisting of the month and year of this customer's
3917 paydate (credit card expiration date for CARD customers)
3921 sub paydate_monthyear {
3923 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3925 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3932 =item invoicing_list [ ARRAYREF ]
3934 If an arguement is given, sets these email addresses as invoice recipients
3935 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3936 (except as warnings), so use check_invoicing_list first.
3938 Returns a list of email addresses (with svcnum entries expanded).
3940 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3941 check it without disturbing anything by passing nothing.
3943 This interface may change in the future.
3947 sub invoicing_list {
3948 my( $self, $arrayref ) = @_;
3951 my @cust_main_invoice;
3952 if ( $self->custnum ) {
3953 @cust_main_invoice =
3954 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3956 @cust_main_invoice = ();
3958 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3959 #warn $cust_main_invoice->destnum;
3960 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3961 #warn $cust_main_invoice->destnum;
3962 my $error = $cust_main_invoice->delete;
3963 warn $error if $error;
3966 if ( $self->custnum ) {
3967 @cust_main_invoice =
3968 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3970 @cust_main_invoice = ();
3972 my %seen = map { $_->address => 1 } @cust_main_invoice;
3973 foreach my $address ( @{$arrayref} ) {
3974 next if exists $seen{$address} && $seen{$address};
3975 $seen{$address} = 1;
3976 my $cust_main_invoice = new FS::cust_main_invoice ( {
3977 'custnum' => $self->custnum,
3980 my $error = $cust_main_invoice->insert;
3981 warn $error if $error;
3985 if ( $self->custnum ) {
3987 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3994 =item check_invoicing_list ARRAYREF
3996 Checks these arguements as valid input for the invoicing_list method. If there
3997 is an error, returns the error, otherwise returns false.
4001 sub check_invoicing_list {
4002 my( $self, $arrayref ) = @_;
4004 foreach my $address ( @$arrayref ) {
4006 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4007 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4010 my $cust_main_invoice = new FS::cust_main_invoice ( {
4011 'custnum' => $self->custnum,
4014 my $error = $self->custnum
4015 ? $cust_main_invoice->check
4016 : $cust_main_invoice->checkdest
4018 return $error if $error;
4022 return "Email address required"
4023 if $conf->exists('cust_main-require_invoicing_list_email')
4024 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4029 =item set_default_invoicing_list
4031 Sets the invoicing list to all accounts associated with this customer,
4032 overwriting any previous invoicing list.
4036 sub set_default_invoicing_list {
4038 $self->invoicing_list($self->all_emails);
4043 Returns the email addresses of all accounts provisioned for this customer.
4050 foreach my $cust_pkg ( $self->all_pkgs ) {
4051 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4053 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4054 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4056 $list{$_}=1 foreach map { $_->email } @svc_acct;
4061 =item invoicing_list_addpost
4063 Adds postal invoicing to this customer. If this customer is already configured
4064 to receive postal invoices, does nothing.
4068 sub invoicing_list_addpost {
4070 return if grep { $_ eq 'POST' } $self->invoicing_list;
4071 my @invoicing_list = $self->invoicing_list;
4072 push @invoicing_list, 'POST';
4073 $self->invoicing_list(\@invoicing_list);
4076 =item invoicing_list_emailonly
4078 Returns the list of email invoice recipients (invoicing_list without non-email
4079 destinations such as POST and FAX).
4083 sub invoicing_list_emailonly {
4085 warn "$me invoicing_list_emailonly called"
4087 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4090 =item invoicing_list_emailonly_scalar
4092 Returns the list of email invoice recipients (invoicing_list without non-email
4093 destinations such as POST and FAX) as a comma-separated scalar.
4097 sub invoicing_list_emailonly_scalar {
4099 warn "$me invoicing_list_emailonly_scalar called"
4101 join(', ', $self->invoicing_list_emailonly);
4104 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4106 Returns an array of customers referred by this customer (referral_custnum set
4107 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4108 customers referred by customers referred by this customer and so on, inclusive.
4109 The default behavior is DEPTH 1 (no recursion).
4113 sub referral_cust_main {
4115 my $depth = @_ ? shift : 1;
4116 my $exclude = @_ ? shift : {};
4119 map { $exclude->{$_->custnum}++; $_; }
4120 grep { ! $exclude->{ $_->custnum } }
4121 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4125 map { $_->referral_cust_main($depth-1, $exclude) }
4132 =item referral_cust_main_ncancelled
4134 Same as referral_cust_main, except only returns customers with uncancelled
4139 sub referral_cust_main_ncancelled {
4141 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4144 =item referral_cust_pkg [ DEPTH ]
4146 Like referral_cust_main, except returns a flat list of all unsuspended (and
4147 uncancelled) packages for each customer. The number of items in this list may
4148 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4152 sub referral_cust_pkg {
4154 my $depth = @_ ? shift : 1;
4156 map { $_->unsuspended_pkgs }
4157 grep { $_->unsuspended_pkgs }
4158 $self->referral_cust_main($depth);
4161 =item referring_cust_main
4163 Returns the single cust_main record for the customer who referred this customer
4164 (referral_custnum), or false.
4168 sub referring_cust_main {
4170 return '' unless $self->referral_custnum;
4171 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4174 =item credit AMOUNT, REASON
4176 Applies a credit to this customer. If there is an error, returns the error,
4177 otherwise returns false.
4182 my( $self, $amount, $reason, %options ) = @_;
4183 my $cust_credit = new FS::cust_credit {
4184 'custnum' => $self->custnum,
4185 'amount' => $amount,
4186 'reason' => $reason,
4188 $cust_credit->insert(%options);
4191 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4193 Creates a one-time charge for this customer. If there is an error, returns
4194 the error, otherwise returns false.
4200 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4201 if ( ref( $_[0] ) ) {
4202 $amount = $_[0]->{amount};
4203 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4204 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4205 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4206 : '$'. sprintf("%.2f",$amount);
4207 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4208 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4209 $additional = $_[0]->{additional};
4213 $pkg = @_ ? shift : 'One-time charge';
4214 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4215 $taxclass = @_ ? shift : '';
4219 local $SIG{HUP} = 'IGNORE';
4220 local $SIG{INT} = 'IGNORE';
4221 local $SIG{QUIT} = 'IGNORE';
4222 local $SIG{TERM} = 'IGNORE';
4223 local $SIG{TSTP} = 'IGNORE';
4224 local $SIG{PIPE} = 'IGNORE';
4226 my $oldAutoCommit = $FS::UID::AutoCommit;
4227 local $FS::UID::AutoCommit = 0;
4230 my $part_pkg = new FS::part_pkg ( {
4232 'comment' => $comment,
4236 'classnum' => $classnum ? $classnum : '',
4237 'taxclass' => $taxclass,
4240 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4241 ( 0 .. @$additional - 1 )
4243 'additional_count' => scalar(@$additional),
4244 'setup_fee' => $amount,
4247 my $error = $part_pkg->insert( options => \%options );
4249 $dbh->rollback if $oldAutoCommit;
4253 my $pkgpart = $part_pkg->pkgpart;
4254 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4255 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4256 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4257 $error = $type_pkgs->insert;
4259 $dbh->rollback if $oldAutoCommit;
4264 my $cust_pkg = new FS::cust_pkg ( {
4265 'custnum' => $self->custnum,
4266 'pkgpart' => $pkgpart,
4267 'quantity' => $quantity,
4270 $error = $cust_pkg->insert;
4272 $dbh->rollback if $oldAutoCommit;
4276 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4281 #=item charge_postal_fee
4283 #Applies a one time charge this customer. If there is an error,
4284 #returns the error, returns the cust_pkg charge object or false
4285 #if there was no charge.
4289 # This should be a customer event. For that to work requires that bill
4290 # also be a customer event.
4292 sub charge_postal_fee {
4295 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4296 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4298 my $cust_pkg = new FS::cust_pkg ( {
4299 'custnum' => $self->custnum,
4300 'pkgpart' => $pkgpart,
4304 my $error = $cust_pkg->insert;
4305 $error ? $error : $cust_pkg;
4310 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4316 sort { $a->_date <=> $b->_date }
4317 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4320 =item open_cust_bill
4322 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4327 sub open_cust_bill {
4329 grep { $_->owed > 0 } $self->cust_bill;
4334 Returns all the credits (see L<FS::cust_credit>) for this customer.
4340 sort { $a->_date <=> $b->_date }
4341 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4346 Returns all the payments (see L<FS::cust_pay>) for this customer.
4352 sort { $a->_date <=> $b->_date }
4353 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4358 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4364 sort { $a->_date <=> $b->_date }
4365 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4371 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4377 sort { $a->_date <=> $b->_date }
4378 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4383 Returns a name string for this customer, either "Company (Last, First)" or
4390 my $name = $self->contact;
4391 $name = $self->company. " ($name)" if $self->company;
4397 Returns a name string for this (service/shipping) contact, either
4398 "Company (Last, First)" or "Last, First".
4404 if ( $self->get('ship_last') ) {
4405 my $name = $self->ship_contact;
4406 $name = $self->ship_company. " ($name)" if $self->ship_company;
4415 Returns a name string for this customer, either "Company" or "First Last".
4421 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4424 =item ship_name_short
4426 Returns a name string for this (service/shipping) contact, either "Company"
4431 sub ship_name_short {
4433 if ( $self->get('ship_last') ) {
4434 $self->ship_company !~ /^\s*$/
4435 ? $self->ship_company
4436 : $self->ship_contact_firstlast;
4438 $self->name_company_or_firstlast;
4444 Returns this customer's full (billing) contact name only, "Last, First"
4450 $self->get('last'). ', '. $self->first;
4455 Returns this customer's full (shipping) contact name only, "Last, First"
4461 $self->get('ship_last')
4462 ? $self->get('ship_last'). ', '. $self->ship_first
4466 =item contact_firstlast
4468 Returns this customers full (billing) contact name only, "First Last".
4472 sub contact_firstlast {
4474 $self->first. ' '. $self->get('last');
4477 =item ship_contact_firstlast
4479 Returns this customer's full (shipping) contact name only, "First Last".
4483 sub ship_contact_firstlast {
4485 $self->get('ship_last')
4486 ? $self->first. ' '. $self->get('ship_last')
4487 : $self->contact_firstlast;
4492 Returns this customer's full country name
4498 code2country($self->country);
4505 Returns a status string for this customer, currently:
4509 =item prospect - No packages have ever been ordered
4511 =item active - One or more recurring packages is active
4513 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4515 =item suspended - All non-cancelled recurring packages are suspended
4517 =item cancelled - All recurring packages are cancelled
4523 sub status { shift->cust_status(@_); }
4527 for my $status (qw( prospect active inactive suspended cancelled )) {
4528 my $method = $status.'_sql';
4529 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4530 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4531 $sth->execute( ($self->custnum) x $numnum )
4532 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4533 return $status if $sth->fetchrow_arrayref->[0];
4537 =item ucfirst_cust_status
4539 =item ucfirst_status
4541 Returns the status with the first character capitalized.
4545 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4547 sub ucfirst_cust_status {
4549 ucfirst($self->cust_status);
4554 Returns a hex triplet color string for this customer's status.
4558 use vars qw(%statuscolor);
4559 tie %statuscolor, 'Tie::IxHash',
4560 'prospect' => '7e0079', #'000000', #black? naw, purple
4561 'active' => '00CC00', #green
4562 'inactive' => '0000CC', #blue
4563 'suspended' => 'FF9900', #yellow
4564 'cancelled' => 'FF0000', #red
4567 sub statuscolor { shift->cust_statuscolor(@_); }
4569 sub cust_statuscolor {
4571 $statuscolor{$self->cust_status};
4576 =head1 CLASS METHODS
4582 Class method that returns the list of possible status strings for customers
4583 (see L<the status method|/status>). For example:
4585 @statuses = FS::cust_main->statuses();
4590 #my $self = shift; #could be class...
4596 Returns an SQL expression identifying prospective cust_main records (customers
4597 with no packages ever ordered)
4601 use vars qw($select_count_pkgs);
4602 $select_count_pkgs =
4603 "SELECT COUNT(*) FROM cust_pkg
4604 WHERE cust_pkg.custnum = cust_main.custnum";
4606 sub select_count_pkgs_sql {
4610 sub prospect_sql { "
4611 0 = ( $select_count_pkgs )
4616 Returns an SQL expression identifying active cust_main records (customers with
4617 active recurring packages).
4622 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
4628 Returns an SQL expression identifying inactive cust_main records (customers with
4629 no active recurring packages, but otherwise unsuspended/uncancelled).
4633 sub inactive_sql { "
4634 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4636 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4642 Returns an SQL expression identifying suspended cust_main records.
4647 sub suspended_sql { susp_sql(@_); }
4649 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
4651 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4657 Returns an SQL expression identifying cancelled cust_main records.
4661 sub cancelled_sql { cancel_sql(@_); }
4664 my $recurring_sql = FS::cust_pkg->recurring_sql;
4665 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
4668 0 < ( $select_count_pkgs )
4669 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
4670 AND 0 = ( $select_count_pkgs AND $recurring_sql
4671 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4673 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4679 =item uncancelled_sql
4681 Returns an SQL expression identifying un-cancelled cust_main records.
4685 sub uncancelled_sql { uncancel_sql(@_); }
4686 sub uncancel_sql { "
4687 ( 0 < ( $select_count_pkgs
4688 AND ( cust_pkg.cancel IS NULL
4689 OR cust_pkg.cancel = 0
4692 OR 0 = ( $select_count_pkgs )
4698 Returns an SQL fragment to retreive the balance.
4703 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4704 WHERE cust_bill.custnum = cust_main.custnum )
4705 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4706 WHERE cust_pay.custnum = cust_main.custnum )
4707 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4708 WHERE cust_credit.custnum = cust_main.custnum )
4709 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4710 WHERE cust_refund.custnum = cust_main.custnum )
4713 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4715 Returns an SQL fragment to retreive the balance for this customer, only
4716 considering invoices with date earlier than START_TIME, and optionally not
4717 later than END_TIME (total_owed_date minus total_credited minus
4718 total_unapplied_payments).
4720 Times are specified as SQL fragments or numeric
4721 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4722 L<Date::Parse> for conversion functions. The empty string can be passed
4723 to disable that time constraint completely.
4725 Available options are:
4729 =item unapplied_date - set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
4731 =item total - set to true to remove all customer comparison clauses, for totals
4733 =item where - WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4735 =item join - JOIN clause (typically used with the total option)
4743 sub balance_date_sql {
4744 my( $class, $start, $end, %opt ) = @_;
4746 my $owed = FS::cust_bill->owed_sql;
4747 my $unapp_refund = FS::cust_refund->unapplied_sql;
4748 my $unapp_credit = FS::cust_credit->unapplied_sql;
4749 my $unapp_pay = FS::cust_pay->unapplied_sql;
4751 my $j = $opt{'join'} || '';
4753 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4754 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4755 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4756 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4758 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4759 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4760 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4761 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4766 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4768 Helper method for balance_date_sql; name (and usage) subject to change
4769 (suggestions welcome).
4771 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4772 cust_refund, cust_credit or cust_pay).
4774 If TABLE is "cust_bill" or the unapplied_date option is true, only
4775 considers records with date earlier than START_TIME, and optionally not
4776 later than END_TIME .
4780 sub _money_table_where {
4781 my( $class, $table, $start, $end, %opt ) = @_;
4784 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4785 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4786 push @where, "$table._date <= $start" if defined($start) && length($start);
4787 push @where, "$table._date > $end" if defined($end) && length($end);
4789 push @where, @{$opt{'where'}} if $opt{'where'};
4790 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4796 =item search_sql HASHREF
4800 Returns a qsearch hash expression to search for parameters specified in HREF.
4801 Valid parameters are
4809 =item cancelled_pkgs
4815 listref of start date, end date
4821 =item current_balance
4823 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
4827 =item flattened_pkgs
4836 my ($class, $params) = @_;
4847 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4849 "cust_main.agentnum = $1";
4856 #prospect active inactive suspended cancelled
4857 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
4858 my $method = $params->{'status'}. '_sql';
4859 #push @where, $class->$method();
4860 push @where, FS::cust_main->$method();
4864 # parse cancelled package checkbox
4869 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
4870 unless $params->{'cancelled_pkgs'};
4876 foreach my $field (qw( signupdate )) {
4878 next unless exists($params->{$field});
4880 my($beginning, $ending) = @{$params->{$field}};
4883 "cust_main.$field IS NOT NULL",
4884 "cust_main.$field >= $beginning",
4885 "cust_main.$field <= $ending";
4887 $orderby ||= "ORDER BY cust_main.$field";
4895 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
4897 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
4904 #my $balance_sql = $class->balance_sql();
4905 my $balance_sql = FS::cust_main->balance_sql();
4907 push @where, map { s/current_balance/$balance_sql/; $_ }
4908 @{ $params->{'current_balance'} };
4914 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4916 "cust_main.custbatch = '$1'";
4920 # setup queries, subs, etc. for the search
4923 $orderby ||= 'ORDER BY custnum';
4925 # here is the agent virtualization
4926 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
4928 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4930 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
4932 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
4934 my $select = join(', ',
4935 'cust_main.custnum',
4936 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
4939 my(@extra_headers) = ();
4940 my(@extra_fields) = ();
4942 if ($params->{'flattened_pkgs'}) {
4944 if ($dbh->{Driver}->{Name} eq 'Pg') {
4946 $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";
4948 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
4949 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
4950 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
4952 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
4953 "omitting packing information from report.";
4956 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";
4958 my $sth = dbh->prepare($header_query) or die dbh->errstr;
4959 $sth->execute() or die $sth->errstr;
4960 my $headerrow = $sth->fetchrow_arrayref;
4961 my $headercount = $headerrow ? $headerrow->[0] : 0;
4962 while($headercount) {
4963 unshift @extra_headers, "Package ". $headercount;
4964 unshift @extra_fields, eval q!sub {my $c = shift;
4965 my @a = split '\|', $c->magic;
4966 my $p = $a[!.--$headercount. q!];
4974 'table' => 'cust_main',
4975 'select' => $select,
4977 'extra_sql' => $extra_sql,
4978 'order_by' => $orderby,
4979 'count_query' => $count_query,
4980 'extra_headers' => \@extra_headers,
4981 'extra_fields' => \@extra_fields,
4986 =item email_search_sql HASHREF
4990 Emails a notice to the specified customers.
4992 Valid parameters are those of the L<search_sql> method, plus the following:
5014 Optional job queue job for status updates.
5018 Returns an error message, or false for success.
5020 If an error occurs during any email, stops the enture send and returns that
5021 error. Presumably if you're getting SMTP errors aborting is better than
5022 retrying everything.
5026 sub email_search_sql {
5027 my($class, $params) = @_;
5029 my $from = delete $params->{from};
5030 my $subject = delete $params->{subject};
5031 my $html_body = delete $params->{html_body};
5032 my $text_body = delete $params->{text_body};
5034 my $job = delete $params->{'job'};
5036 my $sql_query = $class->search_sql($params);
5038 my $count_query = delete($sql_query->{'count_query'});
5039 my $count_sth = dbh->prepare($count_query)
5040 or die "Error preparing $count_query: ". dbh->errstr;
5042 or die "Error executing $count_query: ". $count_sth->errstr;
5043 my $count_arrayref = $count_sth->fetchrow_arrayref;
5044 my $num_cust = $count_arrayref->[0];
5046 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5047 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5050 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5052 #eventually order+limit magic to reduce memory use?
5053 foreach my $cust_main ( qsearch($sql_query) ) {
5055 my $to = $cust_main->invoicing_list_emailonly_scalar;
5058 my $error = send_email(
5062 'subject' => $subject,
5063 'html_body' => $html_body,
5064 'text_body' => $text_body,
5067 return $error if $error;
5069 if ( $job ) { #progressbar foo
5071 if ( time - $min_sec > $last ) {
5072 my $error = $job->update_statustext(
5073 int( 100 * $num / $num_cust )
5075 die $error if $error;
5085 use Storable qw(thaw);
5088 sub process_email_search_sql {
5090 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5092 my $param = thaw(decode_base64(shift));
5093 warn Dumper($param) if $DEBUG;
5095 $param->{'job'} = $job;
5097 my $error = FS::cust_main->email_search_sql( $param );
5098 die $error if $error;
5102 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5104 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5105 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5106 appropriate ship_ field is also searched).
5108 Additional options are the same as FS::Record::qsearch
5113 my( $self, $fuzzy, $hash, @opt) = @_;
5118 check_and_rebuild_fuzzyfiles();
5119 foreach my $field ( keys %$fuzzy ) {
5121 my $all = $self->all_X($field);
5122 next unless scalar(@$all);
5125 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5128 foreach ( keys %match ) {
5129 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5130 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5133 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5136 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5138 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5146 Returns a masked version of the named field
5151 my ($self, $field) = @_;
5155 'x'x(length($self->getfield($field))-4).
5156 substr($self->getfield($field), (length($self->getfield($field))-4));
5166 =item smart_search OPTION => VALUE ...
5168 Accepts the following options: I<search>, the string to search for. The string
5169 will be searched for as a customer number, phone number, name or company name,
5170 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5171 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5172 skip fuzzy matching when an exact match is found.
5174 Any additional options are treated as an additional qualifier on the search
5177 Returns a (possibly empty) array of FS::cust_main objects.
5184 #here is the agent virtualization
5185 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5189 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5190 my $search = delete $options{'search'};
5191 ( my $alphanum_search = $search ) =~ s/\W//g;
5193 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5195 #false laziness w/Record::ut_phone
5196 my $phonen = "$1-$2-$3";
5197 $phonen .= " x$4" if $4;
5199 push @cust_main, qsearch( {
5200 'table' => 'cust_main',
5201 'hashref' => { %options },
5202 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5204 join(' OR ', map "$_ = '$phonen'",
5205 qw( daytime night fax
5206 ship_daytime ship_night ship_fax )
5209 " AND $agentnums_sql", #agent virtualization
5212 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5213 #try looking for matches with extensions unless one was specified
5215 push @cust_main, qsearch( {
5216 'table' => 'cust_main',
5217 'hashref' => { %options },
5218 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5220 join(' OR ', map "$_ LIKE '$phonen\%'",
5222 ship_daytime ship_night )
5225 " AND $agentnums_sql", #agent virtualization
5230 # custnum search (also try agent_custid), with some tweaking options if your
5231 # legacy cust "numbers" have letters
5232 } elsif ( $search =~ /^\s*(\d+)\s*$/
5233 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5234 && $search =~ /^\s*(\w\w?\d+)\s*$/
5239 push @cust_main, qsearch( {
5240 'table' => 'cust_main',
5241 'hashref' => { 'custnum' => $1, %options },
5242 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5245 push @cust_main, qsearch( {
5246 'table' => 'cust_main',
5247 'hashref' => { 'agent_custid' => $1, %options },
5248 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5251 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5253 my($company, $last, $first) = ( $1, $2, $3 );
5255 # "Company (Last, First)"
5256 #this is probably something a browser remembered,
5257 #so just do an exact search
5259 foreach my $prefix ( '', 'ship_' ) {
5260 push @cust_main, qsearch( {
5261 'table' => 'cust_main',
5262 'hashref' => { $prefix.'first' => $first,
5263 $prefix.'last' => $last,
5264 $prefix.'company' => $company,
5267 'extra_sql' => " AND $agentnums_sql",
5271 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5272 # try (ship_){last,company}
5276 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5277 # # full strings the browser remembers won't work
5278 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5280 use Lingua::EN::NameParse;
5281 my $NameParse = new Lingua::EN::NameParse(
5283 allow_reversed => 1,
5286 my($last, $first) = ( '', '' );
5287 #maybe disable this too and just rely on NameParse?
5288 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5290 ($last, $first) = ( $1, $2 );
5292 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5293 } elsif ( ! $NameParse->parse($value) ) {
5295 my %name = $NameParse->components;
5296 $first = $name{'given_name_1'};
5297 $last = $name{'surname_1'};
5301 if ( $first && $last ) {
5303 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5306 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5308 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5309 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5312 push @cust_main, qsearch( {
5313 'table' => 'cust_main',
5314 'hashref' => \%options,
5315 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5318 # or it just be something that was typed in... (try that in a sec)
5322 my $q_value = dbh->quote($value);
5325 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5326 $sql .= " ( LOWER(last) = $q_value
5327 OR LOWER(company) = $q_value
5328 OR LOWER(ship_last) = $q_value
5329 OR LOWER(ship_company) = $q_value
5332 push @cust_main, qsearch( {
5333 'table' => 'cust_main',
5334 'hashref' => \%options,
5335 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5338 #always do substring & fuzzy,
5339 #getting complains searches are not returning enough
5340 unless ( @cust_main && $skip_fuzzy ) { #no exact match, trying substring/fuzzy
5342 #still some false laziness w/search_sql (was search/cust_main.cgi)
5347 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
5348 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5351 if ( $first && $last ) {
5354 { 'first' => { op=>'ILIKE', value=>"%$first%" },
5355 'last' => { op=>'ILIKE', value=>"%$last%" },
5357 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
5358 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
5365 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
5366 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
5370 foreach my $hashref ( @hashrefs ) {
5372 push @cust_main, qsearch( {
5373 'table' => 'cust_main',
5374 'hashref' => { %$hashref,
5377 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
5386 " AND $agentnums_sql", #extra_sql #agent virtualization
5389 if ( $first && $last ) {
5390 push @cust_main, FS::cust_main->fuzzy_search(
5391 { 'last' => $last, #fuzzy hashref
5392 'first' => $first }, #
5396 foreach my $field ( 'last', 'company' ) {
5398 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
5403 #eliminate duplicates
5405 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5415 Accepts the following options: I<email>, the email address to search for. The
5416 email address will be searched for as an email invoice destination and as an
5419 #Any additional options are treated as an additional qualifier on the search
5420 #(i.e. I<agentnum>).
5422 Returns a (possibly empty) array of FS::cust_main objects (but usually just
5432 my $email = delete $options{'email'};
5434 #we're only being used by RT at the moment... no agent virtualization yet
5435 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5439 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
5441 my ( $user, $domain ) = ( $1, $2 );
5443 warn "$me smart_search: searching for $user in domain $domain"
5449 'table' => 'cust_main_invoice',
5450 'hashref' => { 'dest' => $email },
5457 map $_->cust_svc->cust_pkg,
5459 'table' => 'svc_acct',
5460 'hashref' => { 'username' => $user, },
5462 'AND ( SELECT domain FROM svc_domain
5463 WHERE svc_acct.domsvc = svc_domain.svcnum
5464 ) = '. dbh->quote($domain),
5470 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5472 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
5479 =item check_and_rebuild_fuzzyfiles
5483 use vars qw(@fuzzyfields);
5484 @fuzzyfields = ( 'last', 'first', 'company' );
5486 sub check_and_rebuild_fuzzyfiles {
5487 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5488 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
5491 =item rebuild_fuzzyfiles
5495 sub rebuild_fuzzyfiles {
5497 use Fcntl qw(:flock);
5499 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5500 mkdir $dir, 0700 unless -d $dir;
5502 foreach my $fuzzy ( @fuzzyfields ) {
5504 open(LOCK,">>$dir/cust_main.$fuzzy")
5505 or die "can't open $dir/cust_main.$fuzzy: $!";
5507 or die "can't lock $dir/cust_main.$fuzzy: $!";
5509 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
5510 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
5512 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
5513 my $sth = dbh->prepare("SELECT $field FROM cust_main".
5514 " WHERE $field != '' AND $field IS NOT NULL");
5515 $sth->execute or die $sth->errstr;
5517 while ( my $row = $sth->fetchrow_arrayref ) {
5518 print CACHE $row->[0]. "\n";
5523 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
5525 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
5536 my( $self, $field ) = @_;
5537 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5538 open(CACHE,"<$dir/cust_main.$field")
5539 or die "can't open $dir/cust_main.$field: $!";
5540 my @array = map { chomp; $_; } <CACHE>;
5545 =item append_fuzzyfiles LASTNAME COMPANY
5549 sub append_fuzzyfiles {
5550 #my( $first, $last, $company ) = @_;
5552 &check_and_rebuild_fuzzyfiles;
5554 use Fcntl qw(:flock);
5556 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5558 foreach my $field (qw( first last company )) {
5563 open(CACHE,">>$dir/cust_main.$field")
5564 or die "can't open $dir/cust_main.$field: $!";
5565 flock(CACHE,LOCK_EX)
5566 or die "can't lock $dir/cust_main.$field: $!";
5568 print CACHE "$value\n";
5570 flock(CACHE,LOCK_UN)
5571 or die "can't unlock $dir/cust_main.$field: $!";
5580 =item process_batch_import
5582 Load a batch import as a queued JSRPC job
5586 use Storable qw(thaw);
5589 sub process_batch_import {
5592 my $param = thaw(decode_base64(shift));
5593 warn Dumper($param) if $DEBUG;
5595 my $files = $param->{'uploaded_files'}
5596 or die "No files provided.\n";
5598 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
5600 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
5601 my $file = $dir. $files{'file'};
5604 if ( $file =~ /\.(\w+)$/i ) {
5608 warn "can't parse file type from filename $file; defaulting to CSV";
5613 FS::cust_main::batch_import( {
5617 custbatch => $param->{custbatch},
5618 agentnum => $param->{'agentnum'},
5619 refnum => $param->{'refnum'},
5620 pkgpart => $param->{'pkgpart'},
5621 #'fields' => [qw( cust_pkg.setup dayphone first last address1 address2
5622 # city state zip comments )],
5623 'format' => $param->{'format'},
5628 die "$error\n" if $error;
5636 #some false laziness w/cdr.pm now
5640 my $job = $param->{job};
5642 my $filename = $param->{file};
5643 my $type = $param->{type} || 'csv';
5645 my $custbatch = $param->{custbatch};
5647 my $agentnum = $param->{agentnum};
5648 my $refnum = $param->{refnum};
5649 my $pkgpart = $param->{pkgpart};
5651 my $format = $param->{'format'};
5655 if ( $format eq 'simple' ) {
5656 @fields = qw( cust_pkg.setup dayphone first last
5657 address1 address2 city state zip comments );
5659 } elsif ( $format eq 'extended' ) {
5660 @fields = qw( agent_custid refnum
5661 last first address1 address2 city state zip country
5663 ship_last ship_first ship_address1 ship_address2
5664 ship_city ship_state ship_zip ship_country
5665 payinfo paycvv paydate
5668 svc_acct.username svc_acct._password
5671 } elsif ( $format eq 'extended-plus_company' ) {
5672 @fields = qw( agent_custid refnum
5673 last first company address1 address2 city state zip country
5675 ship_last ship_first ship_company ship_address1 ship_address2
5676 ship_city ship_state ship_zip ship_country
5677 payinfo paycvv paydate
5680 svc_acct.username svc_acct._password
5684 die "unknown format $format";
5690 if ( $type eq 'csv' ) {
5692 eval "use Text::CSV_XS;";
5695 $parser = new Text::CSV_XS;
5697 @buffer = split(/\r?\n/, slurp($filename) );
5698 $count = scalar(@buffer);
5700 } elsif ( $type eq 'xls' ) {
5702 eval "use Spreadsheet::ParseExcel;";
5705 my $excel = new Spreadsheet::ParseExcel::Workbook->Parse($filename);
5706 $parser = $excel->{Worksheet}[0]; #first sheet
5708 $count = $parser->{MaxRow} || $parser->{MinRow};
5712 die "Unknown file type $type\n";
5717 local $SIG{HUP} = 'IGNORE';
5718 local $SIG{INT} = 'IGNORE';
5719 local $SIG{QUIT} = 'IGNORE';
5720 local $SIG{TERM} = 'IGNORE';
5721 local $SIG{TSTP} = 'IGNORE';
5722 local $SIG{PIPE} = 'IGNORE';
5724 my $oldAutoCommit = $FS::UID::AutoCommit;
5725 local $FS::UID::AutoCommit = 0;
5730 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
5734 if ( $type eq 'csv' ) {
5736 last unless scalar(@buffer);
5737 $line = shift(@buffer);
5739 $parser->parse($line) or do {
5740 $dbh->rollback if $oldAutoCommit;
5741 return "can't parse: ". $parser->error_input();
5743 @columns = $parser->fields();
5745 } elsif ( $type eq 'xls' ) {
5747 last if $row > ($parser->{MaxRow} || $parser->{MinRow});
5749 my @row = @{ $parser->{Cells}[$row] };
5750 @columns = map $_->{Val}, @row;
5753 #warn $z++. ": $_\n" for @columns;
5756 die "Unknown file type $type\n";
5759 #warn join('-',@columns);
5762 custbatch => $custbatch,
5763 agentnum => $agentnum,
5765 country => $conf->config('countrydefault') || 'US',
5766 payby => $payby, #default
5767 paydate => '12/2037', #default
5769 my $billtime = time;
5770 my %cust_pkg = ( pkgpart => $pkgpart );
5772 foreach my $field ( @fields ) {
5774 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
5776 #$cust_pkg{$1} = str2time( shift @$columns );
5777 if ( $1 eq 'pkgpart' ) {
5778 $cust_pkg{$1} = shift @columns;
5779 } elsif ( $1 eq 'setup' ) {
5780 $billtime = str2time(shift @columns);
5782 $cust_pkg{$1} = str2time( shift @columns );
5785 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
5787 $svc_acct{$1} = shift @columns;
5791 #refnum interception
5792 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
5794 my $referral = $columns[0];
5795 my %hash = ( 'referral' => $referral,
5796 'agentnum' => $agentnum,
5800 my $part_referral = qsearchs('part_referral', \%hash )
5801 || new FS::part_referral \%hash;
5803 unless ( $part_referral->refnum ) {
5804 my $error = $part_referral->insert;
5806 $dbh->rollback if $oldAutoCommit;
5807 return "can't auto-insert advertising source: $referral: $error";
5811 $columns[0] = $part_referral->refnum;
5814 my $value = shift @columns;
5815 $cust_main{$field} = $value if length($value);
5819 $cust_main{'payby'} = 'CARD'
5820 if defined $cust_main{'payinfo'}
5821 && length $cust_main{'payinfo'};
5823 my $invoicing_list = $cust_main{'invoicing_list'}
5824 ? [ delete $cust_main{'invoicing_list'} ]
5827 my $cust_main = new FS::cust_main ( \%cust_main );
5830 tie my %hash, 'Tie::RefHash'; #this part is important
5832 if ( $cust_pkg{'pkgpart'} ) {
5833 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
5836 if ( $svc_acct{'username'} ) {
5837 my $part_pkg = $cust_pkg->part_pkg;
5838 unless ( $part_pkg ) {
5839 $dbh->rollback if $oldAutoCommit;
5840 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
5842 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
5843 push @svc_acct, new FS::svc_acct ( \%svc_acct )
5846 $hash{$cust_pkg} = \@svc_acct;
5849 my $error = $cust_main->insert( \%hash, $invoicing_list );
5852 $dbh->rollback if $oldAutoCommit;
5853 return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
5856 if ( $format eq 'simple' ) {
5858 #false laziness w/bill.cgi
5859 $error = $cust_main->bill( 'time' => $billtime );
5861 $dbh->rollback if $oldAutoCommit;
5862 return "can't bill customer for $line: $error";
5865 $error = $cust_main->apply_payments_and_credits;
5867 $dbh->rollback if $oldAutoCommit;
5868 return "can't bill customer for $line: $error";
5871 $error = $cust_main->collect();
5873 $dbh->rollback if $oldAutoCommit;
5874 return "can't collect customer for $line: $error";
5881 if ( $job && time - $min_sec > $last ) { #progress bar
5882 $job->update_statustext( int(100 * $row / $count) );
5888 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
5890 return "Empty file!" unless $row;
5902 #warn join('-',keys %$param);
5903 my $fh = $param->{filehandle};
5904 my @fields = @{$param->{fields}};
5906 eval "use Text::CSV_XS;";
5909 my $csv = new Text::CSV_XS;
5916 local $SIG{HUP} = 'IGNORE';
5917 local $SIG{INT} = 'IGNORE';
5918 local $SIG{QUIT} = 'IGNORE';
5919 local $SIG{TERM} = 'IGNORE';
5920 local $SIG{TSTP} = 'IGNORE';
5921 local $SIG{PIPE} = 'IGNORE';
5923 my $oldAutoCommit = $FS::UID::AutoCommit;
5924 local $FS::UID::AutoCommit = 0;
5927 #while ( $columns = $csv->getline($fh) ) {
5929 while ( defined($line=<$fh>) ) {
5931 $csv->parse($line) or do {
5932 $dbh->rollback if $oldAutoCommit;
5933 return "can't parse: ". $csv->error_input();
5936 my @columns = $csv->fields();
5937 #warn join('-',@columns);
5940 foreach my $field ( @fields ) {
5941 $row{$field} = shift @columns;
5944 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
5945 unless ( $cust_main ) {
5946 $dbh->rollback if $oldAutoCommit;
5947 return "unknown custnum $row{'custnum'}";
5950 if ( $row{'amount'} > 0 ) {
5951 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5953 $dbh->rollback if $oldAutoCommit;
5957 } elsif ( $row{'amount'} < 0 ) {
5958 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5961 $dbh->rollback if $oldAutoCommit;
5971 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5973 return "Empty file!" unless $imported;
5979 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5981 Sends a templated email notification to the customer (see L<Text::Template>).
5983 OPTIONS is a hash and may include
5985 I<from> - the email sender (default is invoice_from)
5987 I<to> - comma-separated scalar or arrayref of recipients
5988 (default is invoicing_list)
5990 I<subject> - The subject line of the sent email notification
5991 (default is "Notice from company_name")
5993 I<extra_fields> - a hashref of name/value pairs which will be substituted
5996 The following variables are vavailable in the template.
5998 I<$first> - the customer first name
5999 I<$last> - the customer last name
6000 I<$company> - the customer company
6001 I<$payby> - a description of the method of payment for the customer
6002 # would be nice to use FS::payby::shortname
6003 I<$payinfo> - the account information used to collect for this customer
6004 I<$expdate> - the expiration of the customer payment in seconds from epoch
6009 my ($customer, $template, %options) = @_;
6011 return unless $conf->exists($template);
6013 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6014 $from = $options{from} if exists($options{from});
6016 my $to = join(',', $customer->invoicing_list_emailonly);
6017 $to = $options{to} if exists($options{to});
6019 my $subject = "Notice from " . $conf->config('company_name')
6020 if $conf->exists('company_name');
6021 $subject = $options{subject} if exists($options{subject});
6023 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6024 SOURCE => [ map "$_\n",
6025 $conf->config($template)]
6027 or die "can't create new Text::Template object: Text::Template::ERROR";
6028 $notify_template->compile()
6029 or die "can't compile template: Text::Template::ERROR";
6031 my $paydate = $customer->paydate || '2037-12-31';
6032 $FS::notify_template::_template::first = $customer->first;
6033 $FS::notify_template::_template::last = $customer->last;
6034 $FS::notify_template::_template::company = $customer->company;
6035 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6036 my $payby = $customer->payby;
6037 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6038 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6040 #credit cards expire at the end of the month/year of their exp date
6041 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6042 $FS::notify_template::_template::payby = 'credit card';
6043 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6044 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6046 }elsif ($payby eq 'COMP') {
6047 $FS::notify_template::_template::payby = 'complimentary account';
6049 $FS::notify_template::_template::payby = 'current method';
6051 $FS::notify_template::_template::expdate = $expire_time;
6053 for (keys %{$options{extra_fields}}){
6055 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6058 send_email(from => $from,
6060 subject => $subject,
6061 body => $notify_template->fill_in( PACKAGE =>
6062 'FS::notify_template::_template' ),
6067 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6069 Generates a templated notification to the customer (see L<Text::Template>).
6071 OPTIONS is a hash and may include
6073 I<extra_fields> - a hashref of name/value pairs which will be substituted
6074 into the template. These values may override values mentioned below
6075 and those from the customer record.
6077 The following variables are available in the template instead of or in addition
6078 to the fields of the customer record.
6080 I<$payby> - a description of the method of payment for the customer
6081 # would be nice to use FS::payby::shortname
6082 I<$payinfo> - the masked account information used to collect for this customer
6083 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6084 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress
6088 sub generate_letter {
6089 my ($self, $template, %options) = @_;
6091 return unless $conf->exists($template);
6093 my $letter_template = new Text::Template
6095 SOURCE => [ map "$_\n", $conf->config($template)],
6096 DELIMITERS => [ '[@--', '--@]' ],
6098 or die "can't create new Text::Template object: Text::Template::ERROR";
6100 $letter_template->compile()
6101 or die "can't compile template: Text::Template::ERROR";
6103 my %letter_data = map { $_ => $self->$_ } $self->fields;
6104 $letter_data{payinfo} = $self->mask_payinfo;
6106 my $paydate = $self->paydate || '2037-12-31';
6107 my $payby = $self->payby;
6108 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6109 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6111 #credit cards expire at the end of the month/year of their exp date
6112 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6113 $letter_data{payby} = 'credit card';
6114 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6115 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6117 }elsif ($payby eq 'COMP') {
6118 $letter_data{payby} = 'complimentary account';
6120 $letter_data{payby} = 'current method';
6122 $letter_data{expdate} = $expire_time;
6124 for (keys %{$options{extra_fields}}){
6125 $letter_data{$_} = $options{extra_fields}->{$_};
6128 unless(exists($letter_data{returnaddress})){
6129 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6130 $self->_agent_template)
6133 $letter_data{returnaddress} = length($retadd) ? $retadd : '~';
6136 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6138 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6139 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6143 ) or die "can't open temp file: $!\n";
6145 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6147 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6151 =item print_ps TEMPLATE
6153 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6159 my $file = $self->generate_letter(@_);
6160 FS::Misc::generate_ps($file);
6163 =item print TEMPLATE
6165 Prints the filled in template.
6167 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6171 sub queueable_print {
6174 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6175 or die "invalid customer number: " . $opt{custvnum};
6177 my $error = $self->print( $opt{template} );
6178 die $error if $error;
6182 my ($self, $template) = (shift, shift);
6183 do_print [ $self->print_ps($template) ];
6186 sub agent_template {
6188 $self->_agent_plandata('agent_templatename');
6191 sub agent_invoice_from {
6193 $self->_agent_plandata('agent_invoice_from');
6196 sub _agent_plandata {
6197 my( $self, $option ) = @_;
6200 if ( driver_name =~ /^Pg/i ) {
6202 } elsif ( driver_name =~ /^mysql/i ) {
6205 die "don't know how to use regular expressions in ". driver_name. " databases";
6208 my $part_bill_event = qsearchs( 'part_bill_event',
6210 'payby' => $self->payby,
6211 'plan' => 'send_agent',
6212 'plandata' => { 'op' => $regexp,
6213 'value' => "(^|\n)agentnum ".
6221 'ORDER BY seconds LIMIT 1'
6224 return '' unless $part_bill_event;
6226 if ( $part_bill_event->plandata =~ /^$option (.*)$/m ) {
6229 warn "can't parse part_bill_event eventpart#". $part_bill_event->eventpart.
6230 " plandata for $option";
6242 The delete method should possibly take an FS::cust_main object reference
6243 instead of a scalar customer number.
6245 Bill and collect options should probably be passed as references instead of a
6248 There should probably be a configuration file with a list of allowed credit
6251 No multiple currency support (probably a larger project than just this module).
6253 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6255 Birthdates rely on negative epoch values.
6257 The payby for card/check batches is broken. With mixed batching, bad
6262 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6263 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6264 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.