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 String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
25 use FS::UID qw( getotaker dbh driver_name );
26 use FS::Record qw( qsearchs qsearch dbdef );
27 use FS::Misc qw( generate_email send_email generate_ps do_print );
28 use FS::Msgcat qw(gettext);
32 use FS::cust_bill_pkg;
34 use FS::cust_pay_pending;
35 use FS::cust_pay_void;
38 use FS::part_referral;
39 use FS::cust_main_county;
41 use FS::cust_main_invoice;
42 use FS::cust_credit_bill;
43 use FS::cust_bill_pay;
44 use FS::prepay_credit;
47 use FS::part_bill_event qw(due_events);
48 use FS::cust_bill_event;
49 use FS::cust_tax_exempt;
50 use FS::cust_tax_exempt_pkg;
52 use FS::payment_gateway;
53 use FS::agent_payment_gateway;
55 use FS::payinfo_Mixin;
57 @ISA = qw( FS::Record FS::payinfo_Mixin );
59 @EXPORT_OK = qw( smart_search );
61 $realtime_bop_decline_quiet = 0;
63 # 1 is mostly method/subroutine entry and options
64 # 2 traces progress of some operations
65 # 3 is even more information including possibly sensitive data
67 $me = '[FS::cust_main]';
71 $ignore_expired_card = 0;
73 @encrypted_fields = ('payinfo', 'paycvv');
74 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
76 #ask FS::UID to run this stuff for us later
77 #$FS::UID::callback{'FS::cust_main'} = sub {
78 install_callback FS::UID sub {
80 #yes, need it for stuff below (prolly should be cached)
85 my ( $hashref, $cache ) = @_;
86 if ( exists $hashref->{'pkgnum'} ) {
87 #@{ $self->{'_pkgnum'} } = ();
88 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
89 $self->{'_pkgnum'} = $subcache;
90 #push @{ $self->{'_pkgnum'} },
91 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
97 FS::cust_main - Object methods for cust_main records
103 $record = new FS::cust_main \%hash;
104 $record = new FS::cust_main { 'column' => 'value' };
106 $error = $record->insert;
108 $error = $new_record->replace($old_record);
110 $error = $record->delete;
112 $error = $record->check;
114 @cust_pkg = $record->all_pkgs;
116 @cust_pkg = $record->ncancelled_pkgs;
118 @cust_pkg = $record->suspended_pkgs;
120 $error = $record->bill;
121 $error = $record->bill %options;
122 $error = $record->bill 'time' => $time;
124 $error = $record->collect;
125 $error = $record->collect %options;
126 $error = $record->collect 'invoice_time' => $time,
131 An FS::cust_main object represents a customer. FS::cust_main inherits from
132 FS::Record. The following fields are currently supported:
136 =item custnum - primary key (assigned automatically for new customers)
138 =item agentnum - agent (see L<FS::agent>)
140 =item refnum - Advertising source (see L<FS::part_referral>)
146 =item ss - social security number (optional)
148 =item company - (optional)
152 =item address2 - (optional)
156 =item county - (optional, see L<FS::cust_main_county>)
158 =item state - (see L<FS::cust_main_county>)
162 =item country - (see L<FS::cust_main_county>)
164 =item daytime - phone (optional)
166 =item night - phone (optional)
168 =item fax - phone (optional)
170 =item ship_first - name
172 =item ship_last - name
174 =item ship_company - (optional)
178 =item ship_address2 - (optional)
182 =item ship_county - (optional, see L<FS::cust_main_county>)
184 =item ship_state - (see L<FS::cust_main_county>)
188 =item ship_country - (see L<FS::cust_main_county>)
190 =item ship_daytime - phone (optional)
192 =item ship_night - phone (optional)
194 =item ship_fax - phone (optional)
196 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
198 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
200 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
204 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
206 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
208 =item paystart_month - start date month (maestro/solo cards only)
210 =item paystart_year - start date year (maestro/solo cards only)
212 =item payissue - issue number (maestro/solo cards only)
214 =item payname - name on card or billing name
216 =item payip - IP address from which payment information was received
218 =item tax - tax exempt, empty or `Y'
220 =item otaker - order taker (assigned automatically, see L<FS::UID>)
222 =item comments - comments (optional)
224 =item referral_custnum - referring customer number
226 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
236 Creates a new customer. To add the customer to the database, see L<"insert">.
238 Note that this stores the hash reference, not a distinct copy of the hash it
239 points to. You can ask the object for a copy with the I<hash> method.
243 sub table { 'cust_main'; }
245 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
247 Adds this customer to the database. If there is an error, returns the error,
248 otherwise returns false.
250 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
251 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
252 are inserted atomicly, or the transaction is rolled back. Passing an empty
253 hash reference is equivalent to not supplying this parameter. There should be
254 a better explanation of this, but until then, here's an example:
257 tie %hash, 'Tie::RefHash'; #this part is important
259 $cust_pkg => [ $svc_acct ],
262 $cust_main->insert( \%hash );
264 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
265 be set as the invoicing list (see L<"invoicing_list">). Errors return as
266 expected and rollback the entire transaction; it is not necessary to call
267 check_invoicing_list first. The invoicing_list is set after the records in the
268 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
269 invoicing_list destination to the newly-created svc_acct. Here's an example:
271 $cust_main->insert( {}, [ $email, 'POST' ] );
273 Currently available options are: I<depend_jobnum> and I<noexport>.
275 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
276 on the supplied jobnum (they will not run until the specific job completes).
277 This can be used to defer provisioning until some action completes (such
278 as running the customer's credit card successfully).
280 The I<noexport> option is deprecated. If I<noexport> is set true, no
281 provisioning jobs (exports) are scheduled. (You can schedule them later with
282 the B<reexport> method.)
288 my $cust_pkgs = @_ ? shift : {};
289 my $invoicing_list = @_ ? shift : '';
291 warn "$me insert called with options ".
292 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
295 local $SIG{HUP} = 'IGNORE';
296 local $SIG{INT} = 'IGNORE';
297 local $SIG{QUIT} = 'IGNORE';
298 local $SIG{TERM} = 'IGNORE';
299 local $SIG{TSTP} = 'IGNORE';
300 local $SIG{PIPE} = 'IGNORE';
302 my $oldAutoCommit = $FS::UID::AutoCommit;
303 local $FS::UID::AutoCommit = 0;
306 my $prepay_identifier = '';
307 my( $amount, $seconds ) = ( 0, 0 );
309 if ( $self->payby eq 'PREPAY' ) {
311 $self->payby('BILL');
312 $prepay_identifier = $self->payinfo;
315 warn " looking up prepaid card $prepay_identifier\n"
318 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
320 $dbh->rollback if $oldAutoCommit;
321 #return "error applying prepaid card (transaction rolled back): $error";
325 $payby = 'PREP' if $amount;
327 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
330 $self->payby('BILL');
331 $amount = $self->paid;
335 warn " inserting $self\n"
338 $self->signupdate(time) unless $self->signupdate;
340 my $error = $self->SUPER::insert;
342 $dbh->rollback if $oldAutoCommit;
343 #return "inserting cust_main record (transaction rolled back): $error";
347 warn " setting invoicing list\n"
350 if ( $invoicing_list ) {
351 $error = $self->check_invoicing_list( $invoicing_list );
353 $dbh->rollback if $oldAutoCommit;
354 #return "checking invoicing_list (transaction rolled back): $error";
357 $self->invoicing_list( $invoicing_list );
360 if ( $conf->config('cust_main-skeleton_tables')
361 && $conf->config('cust_main-skeleton_custnum') ) {
363 warn " inserting skeleton records\n"
366 my $error = $self->start_copy_skel;
368 $dbh->rollback if $oldAutoCommit;
374 warn " ordering packages\n"
377 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
379 $dbh->rollback if $oldAutoCommit;
384 $dbh->rollback if $oldAutoCommit;
385 return "No svc_acct record to apply pre-paid time";
389 warn " inserting initial $payby payment of $amount\n"
391 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
393 $dbh->rollback if $oldAutoCommit;
394 return "inserting payment (transaction rolled back): $error";
398 unless ( $import || $skip_fuzzyfiles ) {
399 warn " queueing fuzzyfiles update\n"
401 $error = $self->queue_fuzzyfiles_update;
403 $dbh->rollback if $oldAutoCommit;
404 return "updating fuzzy search cache: $error";
408 warn " insert complete; committing transaction\n"
411 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
416 sub start_copy_skel {
419 #'mg_user_preference' => {},
420 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
421 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
422 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
423 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
424 my @tables = eval($conf->config_binary('cust_main-skeleton_tables'));
427 _copy_skel( 'cust_main', #tablename
428 $conf->config('cust_main-skeleton_custnum'), #sourceid
429 $self->custnum, #destid
430 @tables, #child tables
434 #recursive subroutine, not a method
436 my( $table, $sourceid, $destid, %child_tables ) = @_;
439 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
440 ( $table, $primary_key ) = ( $1, $2 );
442 my $dbdef_table = dbdef->table($table);
443 $primary_key = $dbdef_table->primary_key
444 or return "$table has no primary key".
445 " (or do you need to run dbdef-create?)";
448 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
449 join (', ', keys %child_tables). "\n"
452 foreach my $child_table_def ( keys %child_tables ) {
456 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
457 ( $child_table, $child_pkey ) = ( $1, $2 );
459 $child_table = $child_table_def;
461 $child_pkey = dbdef->table($child_table)->primary_key;
462 # or return "$table has no primary key".
463 # " (or do you need to run dbdef-create?)\n";
467 if ( keys %{ $child_tables{$child_table_def} } ) {
469 return "$child_table has no primary key".
470 " (run dbdef-create or try specifying it?)\n"
473 #false laziness w/Record::insert and only works on Pg
474 #refactor the proper last-inserted-id stuff out of Record::insert if this
475 # ever gets use for anything besides a quick kludge for one customer
476 my $default = dbdef->table($child_table)->column($child_pkey)->default;
477 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
478 or return "can't parse $child_table.$child_pkey default value ".
479 " for sequence name: $default";
484 my @sel_columns = grep { $_ ne $primary_key }
485 dbdef->table($child_table)->columns;
486 my $sel_columns = join(', ', @sel_columns );
488 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
489 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
490 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
492 my $sel_st = "SELECT $sel_columns FROM $child_table".
493 " WHERE $primary_key = $sourceid";
496 my $sel_sth = dbh->prepare( $sel_st )
497 or return dbh->errstr;
499 $sel_sth->execute or return $sel_sth->errstr;
501 while ( my $row = $sel_sth->fetchrow_hashref ) {
503 warn " selected row: ".
504 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
508 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
509 my $ins_sth =dbh->prepare($statement)
510 or return dbh->errstr;
511 my @param = ( $destid, map $row->{$_}, @ins_columns );
512 warn " $statement: [ ". join(', ', @param). " ]\n"
514 $ins_sth->execute( @param )
515 or return $ins_sth->errstr;
517 #next unless keys %{ $child_tables{$child_table} };
518 next unless $sequence;
520 #another section of that laziness
521 my $seq_sql = "SELECT currval('$sequence')";
522 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
523 $seq_sth->execute or return $seq_sth->errstr;
524 my $insertid = $seq_sth->fetchrow_arrayref->[0];
526 # don't drink soap! recurse! recurse! okay!
528 _copy_skel( $child_table_def,
529 $row->{$child_pkey}, #sourceid
531 %{ $child_tables{$child_table_def} },
533 return $error if $error;
543 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
545 Like the insert method on an existing record, this method orders a package
546 and included services atomicaly. Pass a Tie::RefHash data structure to this
547 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
548 be a better explanation of this, but until then, here's an example:
551 tie %hash, 'Tie::RefHash'; #this part is important
553 $cust_pkg => [ $svc_acct ],
556 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
558 Services can be new, in which case they are inserted, or existing unaudited
559 services, in which case they are linked to the newly-created package.
561 Currently available options are: I<depend_jobnum> and I<noexport>.
563 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
564 on the supplied jobnum (they will not run until the specific job completes).
565 This can be used to defer provisioning until some action completes (such
566 as running the customer's credit card successfully).
568 The I<noexport> option is deprecated. If I<noexport> is set true, no
569 provisioning jobs (exports) are scheduled. (You can schedule them later with
570 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
571 on the cust_main object is not recommended, as existing services will also be
578 my $cust_pkgs = shift;
581 my %svc_options = ();
582 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
583 if exists $options{'depend_jobnum'};
584 warn "$me order_pkgs called with options ".
585 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
588 local $SIG{HUP} = 'IGNORE';
589 local $SIG{INT} = 'IGNORE';
590 local $SIG{QUIT} = 'IGNORE';
591 local $SIG{TERM} = 'IGNORE';
592 local $SIG{TSTP} = 'IGNORE';
593 local $SIG{PIPE} = 'IGNORE';
595 my $oldAutoCommit = $FS::UID::AutoCommit;
596 local $FS::UID::AutoCommit = 0;
599 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
601 foreach my $cust_pkg ( keys %$cust_pkgs ) {
602 $cust_pkg->custnum( $self->custnum );
603 my $error = $cust_pkg->insert;
605 $dbh->rollback if $oldAutoCommit;
606 return "inserting cust_pkg (transaction rolled back): $error";
608 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
609 if ( $svc_something->svcnum ) {
610 my $old_cust_svc = $svc_something->cust_svc;
611 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
612 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
613 $error = $new_cust_svc->replace($old_cust_svc);
615 $svc_something->pkgnum( $cust_pkg->pkgnum );
616 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
617 $svc_something->seconds( $svc_something->seconds + $$seconds );
620 $error = $svc_something->insert(%svc_options);
623 $dbh->rollback if $oldAutoCommit;
624 #return "inserting svc_ (transaction rolled back): $error";
630 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
634 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
636 Recharges this (existing) customer with the specified prepaid card (see
637 L<FS::prepay_credit>), specified either by I<identifier> or as an
638 FS::prepay_credit object. If there is an error, returns the error, otherwise
641 Optionally, four scalar references can be passed as well. They will have their
642 values filled in with the amount, number of seconds, and number of upload and
643 download bytes applied by this prepaid
648 sub recharge_prepay {
649 my( $self, $prepay_credit, $amountref, $secondsref,
650 $upbytesref, $downbytesref, $totalbytesref ) = @_;
652 local $SIG{HUP} = 'IGNORE';
653 local $SIG{INT} = 'IGNORE';
654 local $SIG{QUIT} = 'IGNORE';
655 local $SIG{TERM} = 'IGNORE';
656 local $SIG{TSTP} = 'IGNORE';
657 local $SIG{PIPE} = 'IGNORE';
659 my $oldAutoCommit = $FS::UID::AutoCommit;
660 local $FS::UID::AutoCommit = 0;
663 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
665 my $error = $self->get_prepay($prepay_credit, \$amount,
666 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
667 || $self->increment_seconds($seconds)
668 || $self->increment_upbytes($upbytes)
669 || $self->increment_downbytes($downbytes)
670 || $self->increment_totalbytes($totalbytes)
671 || $self->insert_cust_pay_prepay( $amount,
673 ? $prepay_credit->identifier
678 $dbh->rollback if $oldAutoCommit;
682 if ( defined($amountref) ) { $$amountref = $amount; }
683 if ( defined($secondsref) ) { $$secondsref = $seconds; }
684 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
685 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
686 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
688 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
693 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
695 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
696 specified either by I<identifier> or as an FS::prepay_credit object.
698 References to I<amount> and I<seconds> scalars should be passed as arguments
699 and will be incremented by the values of the prepaid card.
701 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
702 check or set this customer's I<agentnum>.
704 If there is an error, returns the error, otherwise returns false.
710 my( $self, $prepay_credit, $amountref, $secondsref,
711 $upref, $downref, $totalref) = @_;
713 local $SIG{HUP} = 'IGNORE';
714 local $SIG{INT} = 'IGNORE';
715 local $SIG{QUIT} = 'IGNORE';
716 local $SIG{TERM} = 'IGNORE';
717 local $SIG{TSTP} = 'IGNORE';
718 local $SIG{PIPE} = 'IGNORE';
720 my $oldAutoCommit = $FS::UID::AutoCommit;
721 local $FS::UID::AutoCommit = 0;
724 unless ( ref($prepay_credit) ) {
726 my $identifier = $prepay_credit;
728 $prepay_credit = qsearchs(
730 { 'identifier' => $prepay_credit },
735 unless ( $prepay_credit ) {
736 $dbh->rollback if $oldAutoCommit;
737 return "Invalid prepaid card: ". $identifier;
742 if ( $prepay_credit->agentnum ) {
743 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
744 $dbh->rollback if $oldAutoCommit;
745 return "prepaid card not valid for agent ". $self->agentnum;
747 $self->agentnum($prepay_credit->agentnum);
750 my $error = $prepay_credit->delete;
752 $dbh->rollback if $oldAutoCommit;
753 return "removing prepay_credit (transaction rolled back): $error";
756 $$amountref += $prepay_credit->amount;
757 $$secondsref += $prepay_credit->seconds;
758 $$upref += $prepay_credit->upbytes;
759 $$downref += $prepay_credit->downbytes;
760 $$totalref += $prepay_credit->totalbytes;
762 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
767 =item increment_upbytes SECONDS
769 Updates this customer's single or primary account (see L<FS::svc_acct>) by
770 the specified number of upbytes. If there is an error, returns the error,
771 otherwise returns false.
775 sub increment_upbytes {
776 _increment_column( shift, 'upbytes', @_);
779 =item increment_downbytes SECONDS
781 Updates this customer's single or primary account (see L<FS::svc_acct>) by
782 the specified number of downbytes. If there is an error, returns the error,
783 otherwise returns false.
787 sub increment_downbytes {
788 _increment_column( shift, 'downbytes', @_);
791 =item increment_totalbytes SECONDS
793 Updates this customer's single or primary account (see L<FS::svc_acct>) by
794 the specified number of totalbytes. If there is an error, returns the error,
795 otherwise returns false.
799 sub increment_totalbytes {
800 _increment_column( shift, 'totalbytes', @_);
803 =item increment_seconds SECONDS
805 Updates this customer's single or primary account (see L<FS::svc_acct>) by
806 the specified number of seconds. If there is an error, returns the error,
807 otherwise returns false.
811 sub increment_seconds {
812 _increment_column( shift, 'seconds', @_);
815 =item _increment_column AMOUNT
817 Updates this customer's single or primary account (see L<FS::svc_acct>) by
818 the specified number of seconds or bytes. If there is an error, returns
819 the error, otherwise returns false.
823 sub _increment_column {
824 my( $self, $column, $amount ) = @_;
825 warn "$me increment_column called: $column, $amount\n"
828 return '' unless $amount;
830 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
831 $self->ncancelled_pkgs;
834 return 'No packages with primary or single services found'.
835 ' to apply pre-paid time';
836 } elsif ( scalar(@cust_pkg) > 1 ) {
837 #maybe have a way to specify the package/account?
838 return 'Multiple packages found to apply pre-paid time';
841 my $cust_pkg = $cust_pkg[0];
842 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
846 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
849 return 'No account found to apply pre-paid time';
850 } elsif ( scalar(@cust_svc) > 1 ) {
851 return 'Multiple accounts found to apply pre-paid time';
854 my $svc_acct = $cust_svc[0]->svc_x;
855 warn " found service svcnum ". $svc_acct->pkgnum.
856 ' ('. $svc_acct->email. ")\n"
859 $column = "increment_$column";
860 $svc_acct->$column($amount);
864 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
866 Inserts a prepayment in the specified amount for this customer. An optional
867 second argument can specify the prepayment identifier for tracking purposes.
868 If there is an error, returns the error, otherwise returns false.
872 sub insert_cust_pay_prepay {
873 shift->insert_cust_pay('PREP', @_);
876 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
878 Inserts a cash payment in the specified amount for this customer. An optional
879 second argument can specify the payment identifier for tracking purposes.
880 If there is an error, returns the error, otherwise returns false.
884 sub insert_cust_pay_cash {
885 shift->insert_cust_pay('CASH', @_);
888 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
890 Inserts a Western Union payment in the specified amount for this customer. An
891 optional second argument can specify the prepayment identifier for tracking
892 purposes. If there is an error, returns the error, otherwise returns false.
896 sub insert_cust_pay_west {
897 shift->insert_cust_pay('WEST', @_);
900 sub insert_cust_pay {
901 my( $self, $payby, $amount ) = splice(@_, 0, 3);
902 my $payinfo = scalar(@_) ? shift : '';
904 my $cust_pay = new FS::cust_pay {
905 'custnum' => $self->custnum,
906 'paid' => sprintf('%.2f', $amount),
907 #'_date' => #date the prepaid card was purchased???
909 'payinfo' => $payinfo,
917 This method is deprecated. See the I<depend_jobnum> option to the insert and
918 order_pkgs methods for a better way to defer provisioning.
920 Re-schedules all exports by calling the B<reexport> method of all associated
921 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
922 otherwise returns false.
929 carp "WARNING: FS::cust_main::reexport is deprectated; ".
930 "use the depend_jobnum option to insert or order_pkgs to delay export";
932 local $SIG{HUP} = 'IGNORE';
933 local $SIG{INT} = 'IGNORE';
934 local $SIG{QUIT} = 'IGNORE';
935 local $SIG{TERM} = 'IGNORE';
936 local $SIG{TSTP} = 'IGNORE';
937 local $SIG{PIPE} = 'IGNORE';
939 my $oldAutoCommit = $FS::UID::AutoCommit;
940 local $FS::UID::AutoCommit = 0;
943 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
944 my $error = $cust_pkg->reexport;
946 $dbh->rollback if $oldAutoCommit;
951 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
956 =item delete NEW_CUSTNUM
958 This deletes the customer. If there is an error, returns the error, otherwise
961 This will completely remove all traces of the customer record. This is not
962 what you want when a customer cancels service; for that, cancel all of the
963 customer's packages (see L</cancel>).
965 If the customer has any uncancelled packages, you need to pass a new (valid)
966 customer number for those packages to be transferred to. Cancelled packages
967 will be deleted. Did I mention that this is NOT what you want when a customer
968 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
970 You can't delete a customer with invoices (see L<FS::cust_bill>),
971 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
972 refunds (see L<FS::cust_refund>).
979 local $SIG{HUP} = 'IGNORE';
980 local $SIG{INT} = 'IGNORE';
981 local $SIG{QUIT} = 'IGNORE';
982 local $SIG{TERM} = 'IGNORE';
983 local $SIG{TSTP} = 'IGNORE';
984 local $SIG{PIPE} = 'IGNORE';
986 my $oldAutoCommit = $FS::UID::AutoCommit;
987 local $FS::UID::AutoCommit = 0;
990 if ( $self->cust_bill ) {
991 $dbh->rollback if $oldAutoCommit;
992 return "Can't delete a customer with invoices";
994 if ( $self->cust_credit ) {
995 $dbh->rollback if $oldAutoCommit;
996 return "Can't delete a customer with credits";
998 if ( $self->cust_pay ) {
999 $dbh->rollback if $oldAutoCommit;
1000 return "Can't delete a customer with payments";
1002 if ( $self->cust_refund ) {
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Can't delete a customer with refunds";
1007 my @cust_pkg = $self->ncancelled_pkgs;
1009 my $new_custnum = shift;
1010 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1011 $dbh->rollback if $oldAutoCommit;
1012 return "Invalid new customer number: $new_custnum";
1014 foreach my $cust_pkg ( @cust_pkg ) {
1015 my %hash = $cust_pkg->hash;
1016 $hash{'custnum'} = $new_custnum;
1017 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1018 my $error = $new_cust_pkg->replace($cust_pkg,
1019 options => { $cust_pkg->options },
1022 $dbh->rollback if $oldAutoCommit;
1027 my @cancelled_cust_pkg = $self->all_pkgs;
1028 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1029 my $error = $cust_pkg->delete;
1031 $dbh->rollback if $oldAutoCommit;
1036 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1037 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1039 my $error = $cust_main_invoice->delete;
1041 $dbh->rollback if $oldAutoCommit;
1046 my $error = $self->SUPER::delete;
1048 $dbh->rollback if $oldAutoCommit;
1052 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1057 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1059 Replaces the OLD_RECORD with this one in the database. If there is an error,
1060 returns the error, otherwise returns false.
1062 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1063 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1064 expected and rollback the entire transaction; it is not necessary to call
1065 check_invoicing_list first. Here's an example:
1067 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1075 warn "$me replace called\n"
1078 local $SIG{HUP} = 'IGNORE';
1079 local $SIG{INT} = 'IGNORE';
1080 local $SIG{QUIT} = 'IGNORE';
1081 local $SIG{TERM} = 'IGNORE';
1082 local $SIG{TSTP} = 'IGNORE';
1083 local $SIG{PIPE} = 'IGNORE';
1085 # We absolutely have to have an old vs. new record to make this work.
1086 if (!defined($old)) {
1087 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1090 my $curuser = $FS::CurrentUser::CurrentUser;
1091 if ( $self->payby eq 'COMP'
1092 && $self->payby ne $old->payby
1093 && ! $curuser->access_right('Complimentary customer')
1096 return "You are not permitted to create complimentary accounts.";
1099 local($ignore_expired_card) = 1
1100 if $old->payby =~ /^(CARD|DCRD)$/
1101 && $self->payby =~ /^(CARD|DCRD)$/
1102 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1104 my $oldAutoCommit = $FS::UID::AutoCommit;
1105 local $FS::UID::AutoCommit = 0;
1108 my $error = $self->SUPER::replace($old);
1111 $dbh->rollback if $oldAutoCommit;
1115 if ( @param ) { # INVOICING_LIST_ARYREF
1116 my $invoicing_list = shift @param;
1117 $error = $self->check_invoicing_list( $invoicing_list );
1119 $dbh->rollback if $oldAutoCommit;
1122 $self->invoicing_list( $invoicing_list );
1125 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1126 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1127 # card/check/lec info has changed, want to retry realtime_ invoice events
1128 my $error = $self->retry_realtime;
1130 $dbh->rollback if $oldAutoCommit;
1135 unless ( $import || $skip_fuzzyfiles ) {
1136 $error = $self->queue_fuzzyfiles_update;
1138 $dbh->rollback if $oldAutoCommit;
1139 return "updating fuzzy search cache: $error";
1143 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1148 =item queue_fuzzyfiles_update
1150 Used by insert & replace to update the fuzzy search cache
1154 sub queue_fuzzyfiles_update {
1157 local $SIG{HUP} = 'IGNORE';
1158 local $SIG{INT} = 'IGNORE';
1159 local $SIG{QUIT} = 'IGNORE';
1160 local $SIG{TERM} = 'IGNORE';
1161 local $SIG{TSTP} = 'IGNORE';
1162 local $SIG{PIPE} = 'IGNORE';
1164 my $oldAutoCommit = $FS::UID::AutoCommit;
1165 local $FS::UID::AutoCommit = 0;
1168 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1169 my $error = $queue->insert( map $self->getfield($_),
1170 qw(first last company)
1173 $dbh->rollback if $oldAutoCommit;
1174 return "queueing job (transaction rolled back): $error";
1177 if ( $self->ship_last ) {
1178 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1179 $error = $queue->insert( map $self->getfield("ship_$_"),
1180 qw(first last company)
1183 $dbh->rollback if $oldAutoCommit;
1184 return "queueing job (transaction rolled back): $error";
1188 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1195 Checks all fields to make sure this is a valid customer record. If there is
1196 an error, returns the error, otherwise returns false. Called by the insert
1197 and replace methods.
1204 warn "$me check BEFORE: \n". $self->_dump
1208 $self->ut_numbern('custnum')
1209 || $self->ut_number('agentnum')
1210 || $self->ut_textn('agent_custid')
1211 || $self->ut_number('refnum')
1212 || $self->ut_name('last')
1213 || $self->ut_name('first')
1214 || $self->ut_snumbern('birthdate')
1215 || $self->ut_snumbern('signupdate')
1216 || $self->ut_textn('company')
1217 || $self->ut_text('address1')
1218 || $self->ut_textn('address2')
1219 || $self->ut_text('city')
1220 || $self->ut_textn('county')
1221 || $self->ut_textn('state')
1222 || $self->ut_country('country')
1223 || $self->ut_anything('comments')
1224 || $self->ut_numbern('referral_custnum')
1225 || $self->ut_textn('stateid')
1226 || $self->ut_textn('stateid_state')
1228 #barf. need message catalogs. i18n. etc.
1229 $error .= "Please select an advertising source."
1230 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1231 return $error if $error;
1233 return "Unknown agent"
1234 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1236 return "Unknown refnum"
1237 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1239 return "Unknown referring custnum: ". $self->referral_custnum
1240 unless ! $self->referral_custnum
1241 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1243 if ( $self->ss eq '' ) {
1248 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1249 or return "Illegal social security number: ". $self->ss;
1250 $self->ss("$1-$2-$3");
1254 # bad idea to disable, causes billing to fail because of no tax rates later
1255 # unless ( $import ) {
1256 unless ( qsearch('cust_main_county', {
1257 'country' => $self->country,
1260 return "Unknown state/county/country: ".
1261 $self->state. "/". $self->county. "/". $self->country
1262 unless qsearch('cust_main_county',{
1263 'state' => $self->state,
1264 'county' => $self->county,
1265 'country' => $self->country,
1271 $self->ut_phonen('daytime', $self->country)
1272 || $self->ut_phonen('night', $self->country)
1273 || $self->ut_phonen('fax', $self->country)
1274 || $self->ut_zip('zip', $self->country)
1276 return $error if $error;
1278 if ( $conf->exists('cust_main-require_phone')
1279 && ! length($self->daytime) && ! length($self->night)
1282 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1284 : FS::Msgcat::_gettext('daytime');
1285 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1287 : FS::Msgcat::_gettext('night');
1289 return "$daytime_label or $night_label is required"
1293 if ( $self->has_ship_address
1294 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1295 $self->addr_fields )
1299 $self->ut_name('ship_last')
1300 || $self->ut_name('ship_first')
1301 || $self->ut_textn('ship_company')
1302 || $self->ut_text('ship_address1')
1303 || $self->ut_textn('ship_address2')
1304 || $self->ut_text('ship_city')
1305 || $self->ut_textn('ship_county')
1306 || $self->ut_textn('ship_state')
1307 || $self->ut_country('ship_country')
1309 return $error if $error;
1311 #false laziness with above
1312 unless ( qsearchs('cust_main_county', {
1313 'country' => $self->ship_country,
1316 return "Unknown ship_state/ship_county/ship_country: ".
1317 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1318 unless qsearch('cust_main_county',{
1319 'state' => $self->ship_state,
1320 'county' => $self->ship_county,
1321 'country' => $self->ship_country,
1327 $self->ut_phonen('ship_daytime', $self->ship_country)
1328 || $self->ut_phonen('ship_night', $self->ship_country)
1329 || $self->ut_phonen('ship_fax', $self->ship_country)
1330 || $self->ut_zip('ship_zip', $self->ship_country)
1332 return $error if $error;
1334 return "Unit # is required."
1335 if $self->ship_address2 =~ /^\s*$/
1336 && $conf->exists('cust_main-require_address2');
1338 } else { # ship_ info eq billing info, so don't store dup info in database
1340 $self->setfield("ship_$_", '')
1341 foreach $self->addr_fields;
1343 return "Unit # is required."
1344 if $self->address2 =~ /^\s*$/
1345 && $conf->exists('cust_main-require_address2');
1349 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1350 # or return "Illegal payby: ". $self->payby;
1352 FS::payby->can_payby($self->table, $self->payby)
1353 or return "Illegal payby: ". $self->payby;
1355 $error = $self->ut_numbern('paystart_month')
1356 || $self->ut_numbern('paystart_year')
1357 || $self->ut_numbern('payissue')
1358 || $self->ut_textn('paytype')
1360 return $error if $error;
1362 if ( $self->payip eq '' ) {
1365 $error = $self->ut_ip('payip');
1366 return $error if $error;
1369 # If it is encrypted and the private key is not availaible then we can't
1370 # check the credit card.
1372 my $check_payinfo = 1;
1374 if ($self->is_encrypted($self->payinfo)) {
1378 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1380 my $payinfo = $self->payinfo;
1381 $payinfo =~ s/\D//g;
1382 $payinfo =~ /^(\d{13,16})$/
1383 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1385 $self->payinfo($payinfo);
1387 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1389 return gettext('unknown_card_type')
1390 if cardtype($self->payinfo) eq "Unknown";
1392 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1394 return 'Banned credit card: banned on '.
1395 time2str('%a %h %o at %r', $ban->_date).
1396 ' by '. $ban->otaker.
1397 ' (ban# '. $ban->bannum. ')';
1400 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1401 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1402 $self->paycvv =~ /^(\d{4})$/
1403 or return "CVV2 (CID) for American Express cards is four digits.";
1406 $self->paycvv =~ /^(\d{3})$/
1407 or return "CVV2 (CVC2/CID) is three digits.";
1414 my $cardtype = cardtype($payinfo);
1415 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1417 return "Start date or issue number is required for $cardtype cards"
1418 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1420 return "Start month must be between 1 and 12"
1421 if $self->paystart_month
1422 and $self->paystart_month < 1 || $self->paystart_month > 12;
1424 return "Start year must be 1990 or later"
1425 if $self->paystart_year
1426 and $self->paystart_year < 1990;
1428 return "Issue number must be beween 1 and 99"
1430 and $self->payissue < 1 || $self->payissue > 99;
1433 $self->paystart_month('');
1434 $self->paystart_year('');
1435 $self->payissue('');
1438 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1440 my $payinfo = $self->payinfo;
1441 $payinfo =~ s/[^\d\@]//g;
1442 if ( $conf->exists('echeck-nonus') ) {
1443 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1444 $payinfo = "$1\@$2";
1446 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1447 $payinfo = "$1\@$2";
1449 $self->payinfo($payinfo);
1452 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1454 return 'Banned ACH account: banned on '.
1455 time2str('%a %h %o at %r', $ban->_date).
1456 ' by '. $ban->otaker.
1457 ' (ban# '. $ban->bannum. ')';
1460 } elsif ( $self->payby eq 'LECB' ) {
1462 my $payinfo = $self->payinfo;
1463 $payinfo =~ s/\D//g;
1464 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1466 $self->payinfo($payinfo);
1469 } elsif ( $self->payby eq 'BILL' ) {
1471 $error = $self->ut_textn('payinfo');
1472 return "Illegal P.O. number: ". $self->payinfo if $error;
1475 } elsif ( $self->payby eq 'COMP' ) {
1477 my $curuser = $FS::CurrentUser::CurrentUser;
1478 if ( ! $self->custnum
1479 && ! $curuser->access_right('Complimentary customer')
1482 return "You are not permitted to create complimentary accounts."
1485 $error = $self->ut_textn('payinfo');
1486 return "Illegal comp account issuer: ". $self->payinfo if $error;
1489 } elsif ( $self->payby eq 'PREPAY' ) {
1491 my $payinfo = $self->payinfo;
1492 $payinfo =~ s/\W//g; #anything else would just confuse things
1493 $self->payinfo($payinfo);
1494 $error = $self->ut_alpha('payinfo');
1495 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1496 return "Unknown prepayment identifier"
1497 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1502 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1503 return "Expiration date required"
1504 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1508 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1509 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1510 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1511 ( $m, $y ) = ( $3, "20$2" );
1513 return "Illegal expiration date: ". $self->paydate;
1515 $self->paydate("$y-$m-01");
1516 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1517 return gettext('expired_card')
1519 && !$ignore_expired_card
1520 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1523 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1524 ( ! $conf->exists('require_cardname')
1525 || $self->payby !~ /^(CARD|DCRD)$/ )
1527 $self->payname( $self->first. " ". $self->getfield('last') );
1529 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1530 or return gettext('illegal_name'). " payname: ". $self->payname;
1534 foreach my $flag (qw( tax spool_cdr )) {
1535 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1539 $self->otaker(getotaker) unless $self->otaker;
1541 warn "$me check AFTER: \n". $self->_dump
1544 $self->SUPER::check;
1549 Returns a list of fields which have ship_ duplicates.
1554 qw( last first company
1555 address1 address2 city county state zip country
1560 =item has_ship_address
1562 Returns true if this customer record has a separate shipping address.
1566 sub has_ship_address {
1568 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1573 Returns all packages (see L<FS::cust_pkg>) for this customer.
1580 return $self->num_pkgs unless wantarray;
1583 if ( $self->{'_pkgnum'} ) {
1584 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1586 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1589 sort sort_packages @cust_pkg;
1592 =item ncancelled_pkgs
1594 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1598 sub ncancelled_pkgs {
1601 return $self->num_ncancelled_pkgs unless wantarray;
1604 if ( $self->{'_pkgnum'} ) {
1606 @cust_pkg = grep { ! $_->getfield('cancel') }
1607 values %{ $self->{'_pkgnum'}->cache };
1612 qsearch( 'cust_pkg', {
1613 'custnum' => $self->custnum,
1617 qsearch( 'cust_pkg', {
1618 'custnum' => $self->custnum,
1623 sort sort_packages @cust_pkg;
1627 # This should be generalized to use config options to determine order.
1629 if ( $a->get('cancel') and $b->get('cancel') ) {
1630 $a->pkgnum <=> $b->pkgnum;
1631 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1632 return -1 if $b->get('cancel');
1633 return 1 if $a->get('cancel');
1636 $a->pkgnum <=> $b->pkgnum;
1640 =item suspended_pkgs
1642 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1646 sub suspended_pkgs {
1648 grep { $_->susp } $self->ncancelled_pkgs;
1651 =item unflagged_suspended_pkgs
1653 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1654 customer (thouse packages without the `manual_flag' set).
1658 sub unflagged_suspended_pkgs {
1660 return $self->suspended_pkgs
1661 unless dbdef->table('cust_pkg')->column('manual_flag');
1662 grep { ! $_->manual_flag } $self->suspended_pkgs;
1665 =item unsuspended_pkgs
1667 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1672 sub unsuspended_pkgs {
1674 grep { ! $_->susp } $self->ncancelled_pkgs;
1677 =item num_cancelled_pkgs
1679 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1684 sub num_cancelled_pkgs {
1685 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1688 sub num_ncancelled_pkgs {
1689 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1693 my( $self ) = shift;
1694 my $sql = scalar(@_) ? shift : '';
1695 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1696 my $sth = dbh->prepare(
1697 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1698 ) or die dbh->errstr;
1699 $sth->execute($self->custnum) or die $sth->errstr;
1700 $sth->fetchrow_arrayref->[0];
1705 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1706 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1707 on success or a list of errors.
1713 grep { $_->unsuspend } $self->suspended_pkgs;
1718 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1720 Returns a list: an empty list on success or a list of errors.
1726 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1729 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1731 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1732 PKGPARTs (see L<FS::part_pkg>).
1734 Returns a list: an empty list on success or a list of errors.
1738 sub suspend_if_pkgpart {
1740 my (@pkgparts, %opt);
1741 if (ref($_[0]) eq 'HASH'){
1742 @pkgparts = @{$_[0]{pkgparts}};
1747 grep { $_->suspend(%opt) }
1748 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1749 $self->unsuspended_pkgs;
1752 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1754 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1755 listed PKGPARTs (see L<FS::part_pkg>).
1757 Returns a list: an empty list on success or a list of errors.
1761 sub suspend_unless_pkgpart {
1763 my (@pkgparts, %opt);
1764 if (ref($_[0]) eq 'HASH'){
1765 @pkgparts = @{$_[0]{pkgparts}};
1770 grep { $_->suspend(%opt) }
1771 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1772 $self->unsuspended_pkgs;
1775 =item cancel [ OPTION => VALUE ... ]
1777 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1779 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1781 I<quiet> can be set true to supress email cancellation notices.
1783 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1785 I<ban> can be set true to ban this customer's credit card or ACH information,
1788 Always returns a list: an empty list on success or a list of errors.
1796 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1798 #should try decryption (we might have the private key)
1799 # and if not maybe queue a job for the server that does?
1800 return ( "Can't (yet) ban encrypted credit cards" )
1801 if $self->is_encrypted($self->payinfo);
1803 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1804 my $error = $ban->insert;
1805 return ( $error ) if $error;
1809 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1812 sub _banned_pay_hashref {
1823 'payby' => $payby2ban{$self->payby},
1824 'payinfo' => md5_base64($self->payinfo),
1825 #don't ever *search* on reason! #'reason' =>
1831 Returns all notes (see L<FS::cust_main_note>) for this customer.
1838 qsearch( 'cust_main_note',
1839 { 'custnum' => $self->custnum },
1841 'ORDER BY _DATE DESC'
1847 Returns the agent (see L<FS::agent>) for this customer.
1853 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1858 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1859 conjunction with the collect method.
1861 If there is an error, returns the error, otherwise returns false.
1863 Options are passed as name-value pairs. Currently available options are:
1867 =item resetup - if set true, re-charges setup fees.
1869 =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:
1873 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1875 =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.
1882 my( $self, %options ) = @_;
1883 return '' if $self->payby eq 'COMP';
1884 warn "$me bill customer ". $self->custnum. "\n"
1887 my $time = $options{'time'} || time;
1892 local $SIG{HUP} = 'IGNORE';
1893 local $SIG{INT} = 'IGNORE';
1894 local $SIG{QUIT} = 'IGNORE';
1895 local $SIG{TERM} = 'IGNORE';
1896 local $SIG{TSTP} = 'IGNORE';
1897 local $SIG{PIPE} = 'IGNORE';
1899 my $oldAutoCommit = $FS::UID::AutoCommit;
1900 local $FS::UID::AutoCommit = 0;
1903 $self->select_for_update; #mutex
1905 #create a new invoice
1906 #(we'll remove it later if it doesn't actually need to be generated [contains
1907 # no line items] and we're inside a transaciton so nothing else will see it)
1908 my $cust_bill = new FS::cust_bill ( {
1909 'custnum' => $self->custnum,
1910 '_date' => ( $options{'invoice_time'} || $time ),
1911 #'charged' => $charged,
1914 $error = $cust_bill->insert;
1916 $dbh->rollback if $oldAutoCommit;
1917 return "can't create invoice for customer #". $self->custnum. ": $error";
1919 my $invnum = $cust_bill->invnum;
1922 # find the packages which are due for billing, find out how much they are
1923 # & generate invoice database.
1926 my( $total_setup, $total_recur ) = ( 0, 0 );
1928 my @precommit_hooks = ();
1930 foreach my $cust_pkg (
1931 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1934 #NO!! next if $cust_pkg->cancel;
1935 next if $cust_pkg->getfield('cancel');
1937 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1939 #? to avoid use of uninitialized value errors... ?
1940 $cust_pkg->setfield('bill', '')
1941 unless defined($cust_pkg->bill);
1943 my $part_pkg = $cust_pkg->part_pkg;
1945 my %hash = $cust_pkg->hash;
1946 my $old_cust_pkg = new FS::cust_pkg \%hash;
1956 if ( ! $cust_pkg->setup &&
1958 ( $conf->exists('disable_setup_suspended_pkgs') &&
1959 ! $cust_pkg->getfield('susp')
1960 ) || ! $conf->exists('disable_setup_suspended_pkgs')
1962 || $options{'resetup'}
1965 warn " bill setup\n" if $DEBUG > 1;
1967 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
1969 $dbh->rollback if $oldAutoCommit;
1970 return "$@ running calc_setup for $cust_pkg\n";
1973 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
1975 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1979 # bill recurring fee
1982 #XXX unit stuff here too
1986 if ( $part_pkg->getfield('freq') ne '0' &&
1987 ! $cust_pkg->getfield('susp') &&
1988 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1991 # XXX should this be a package event? probably. events are called
1992 # at collection time at the moment, though...
1993 if ( $part_pkg->can('reset_usage') ) {
1994 warn " resetting usage counters" if $DEBUG > 1;
1995 $part_pkg->reset_usage($cust_pkg);
1998 warn " bill recur\n" if $DEBUG > 1;
2000 # XXX shared with $recur_prog
2001 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2003 #over two params! lets at least switch to a hashref for the rest...
2004 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
2006 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2008 $dbh->rollback if $oldAutoCommit;
2009 return "$@ running calc_recur for $cust_pkg\n";
2012 #change this bit to use Date::Manip? CAREFUL with timezones (see
2013 # mailing list archive)
2014 my ($sec,$min,$hour,$mday,$mon,$year) =
2015 (localtime($sdate) )[0,1,2,3,4,5];
2017 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2018 # only for figuring next bill date, nothing else, so, reset $sdate again
2020 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2021 $cust_pkg->last_bill($sdate);
2023 if ( $part_pkg->freq =~ /^\d+$/ ) {
2024 $mon += $part_pkg->freq;
2025 until ( $mon < 12 ) { $mon -= 12; $year++; }
2026 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2028 $mday += $weeks * 7;
2029 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2032 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2036 $dbh->rollback if $oldAutoCommit;
2037 return "unparsable frequency: ". $part_pkg->freq;
2039 $cust_pkg->setfield('bill',
2040 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2043 warn "\$setup is undefined" unless defined($setup);
2044 warn "\$recur is undefined" unless defined($recur);
2045 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2048 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2051 if ( $cust_pkg->modified ) { # hmmm.. and if the options are modified?
2053 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2056 $error=$cust_pkg->replace($old_cust_pkg,
2057 options => { $cust_pkg->options },
2059 if ( $error ) { #just in case
2060 $dbh->rollback if $oldAutoCommit;
2061 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2064 $setup = sprintf( "%.2f", $setup );
2065 $recur = sprintf( "%.2f", $recur );
2066 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2067 $dbh->rollback if $oldAutoCommit;
2068 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2070 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2071 $dbh->rollback if $oldAutoCommit;
2072 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2075 if ( $setup != 0 || $recur != 0 ) {
2077 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2079 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2080 'invnum' => $invnum,
2081 'pkgnum' => $cust_pkg->pkgnum,
2083 'unitsetup' => $unitsetup,
2085 'unitrecur' => $unitrecur,
2086 'quantity' => $cust_pkg->quantity,
2088 'edate' => $cust_pkg->bill,
2089 'details' => \@details,
2091 $error = $cust_bill_pkg->insert;
2093 $dbh->rollback if $oldAutoCommit;
2094 return "can't create invoice line item for invoice #$invnum: $error";
2096 $total_setup += $setup;
2097 $total_recur += $recur;
2103 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2106 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2109 my %taxhash = map { $_ => $self->get("$prefix$_") }
2110 qw( state county country );
2112 $taxhash{'taxclass'} = $part_pkg->taxclass;
2114 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2117 $taxhash{'taxclass'} = '';
2118 @taxes = qsearch( 'cust_main_county', \%taxhash );
2121 #one more try at a whole-country tax rate
2123 $taxhash{$_} = '' foreach qw( state county );
2124 @taxes = qsearch( 'cust_main_county', \%taxhash );
2127 # maybe eliminate this entirely, along with all the 0% records
2129 $dbh->rollback if $oldAutoCommit;
2131 "fatal: can't find tax rate for state/county/country/taxclass ".
2132 join('/', ( map $self->get("$prefix$_"),
2133 qw(state county country)
2135 $part_pkg->taxclass ). "\n";
2138 foreach my $tax ( @taxes ) {
2140 my $taxable_charged = 0;
2141 $taxable_charged += $setup
2142 unless $part_pkg->setuptax =~ /^Y$/i
2143 || $tax->setuptax =~ /^Y$/i;
2144 $taxable_charged += $recur
2145 unless $part_pkg->recurtax =~ /^Y$/i
2146 || $tax->recurtax =~ /^Y$/i;
2147 next unless $taxable_charged;
2149 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2150 #my ($mon,$year) = (localtime($sdate) )[4,5];
2151 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2153 my $freq = $part_pkg->freq || 1;
2154 if ( $freq !~ /(\d+)$/ ) {
2155 $dbh->rollback if $oldAutoCommit;
2156 return "daily/weekly package definitions not (yet?)".
2157 " compatible with monthly tax exemptions";
2159 my $taxable_per_month =
2160 sprintf("%.2f", $taxable_charged / $freq );
2162 #call the whole thing off if this customer has any old
2163 #exemption records...
2164 my @cust_tax_exempt =
2165 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2166 if ( @cust_tax_exempt ) {
2167 $dbh->rollback if $oldAutoCommit;
2169 'this customer still has old-style tax exemption records; '.
2170 'run bin/fs-migrate-cust_tax_exempt?';
2173 foreach my $which_month ( 1 .. $freq ) {
2175 #maintain the new exemption table now
2178 FROM cust_tax_exempt_pkg
2179 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2180 LEFT JOIN cust_bill USING ( invnum )
2186 my $sth = dbh->prepare($sql) or do {
2187 $dbh->rollback if $oldAutoCommit;
2188 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2196 $dbh->rollback if $oldAutoCommit;
2197 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2199 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2201 my $remaining_exemption =
2202 $tax->exempt_amount - $existing_exemption;
2203 if ( $remaining_exemption > 0 ) {
2204 my $addl = $remaining_exemption > $taxable_per_month
2205 ? $taxable_per_month
2206 : $remaining_exemption;
2207 $taxable_charged -= $addl;
2209 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2210 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2211 'taxnum' => $tax->taxnum,
2212 'year' => 1900+$year,
2214 'amount' => sprintf("%.2f", $addl ),
2216 $error = $cust_tax_exempt_pkg->insert;
2218 $dbh->rollback if $oldAutoCommit;
2219 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2221 } # if $remaining_exemption > 0
2225 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2226 until ( $mon < 13 ) { $mon -= 12; $year++; }
2228 } #foreach $which_month
2230 } #if $tax->exempt_amount
2232 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2234 #$tax += $taxable_charged * $cust_main_county->tax / 100
2235 $tax{ $tax->taxname || 'Tax' } +=
2236 $taxable_charged * $tax->tax / 100
2238 } #foreach my $tax ( @taxes )
2240 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2242 } #if $setup != 0 || $recur != 0
2244 } #if $cust_pkg->modified
2246 } #foreach my $cust_pkg
2248 unless ( $cust_bill->cust_bill_pkg ) {
2249 $cust_bill->delete; #don't create an invoice w/o line items
2250 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2254 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2256 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2257 my $tax = sprintf("%.2f", $tax{$taxname} );
2258 $charged = sprintf( "%.2f", $charged+$tax );
2260 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2261 'invnum' => $invnum,
2267 'itemdesc' => $taxname,
2269 $error = $cust_bill_pkg->insert;
2271 $dbh->rollback if $oldAutoCommit;
2272 return "can't create invoice line item for invoice #$invnum: $error";
2274 $total_setup += $tax;
2278 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2279 $error = $cust_bill->replace;
2281 $dbh->rollback if $oldAutoCommit;
2282 return "can't update charged for invoice #$invnum: $error";
2285 foreach my $hook ( @precommit_hooks ) {
2287 &{$hook}; #($self) ?
2290 $dbh->rollback if $oldAutoCommit;
2291 return "$@ running precommit hook $hook\n";
2295 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2299 =item collect OPTIONS
2301 (Attempt to) collect money for this customer's outstanding invoices (see
2302 L<FS::cust_bill>). Usually used after the bill method.
2304 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2305 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2306 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2308 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2309 and the invoice events web interface.
2311 If there is an error, returns the error, otherwise returns false.
2313 Options are passed as name-value pairs.
2315 Currently available options are:
2317 invoice_time - Use this time when deciding when to print invoices and
2318 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>
2319 for conversion functions.
2321 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2324 quiet - set true to surpress email card/ACH decline notices.
2326 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2329 payby - allows for one time override of normal customer billing method
2334 my( $self, %options ) = @_;
2335 my $invoice_time = $options{'invoice_time'} || time;
2338 local $SIG{HUP} = 'IGNORE';
2339 local $SIG{INT} = 'IGNORE';
2340 local $SIG{QUIT} = 'IGNORE';
2341 local $SIG{TERM} = 'IGNORE';
2342 local $SIG{TSTP} = 'IGNORE';
2343 local $SIG{PIPE} = 'IGNORE';
2345 my $oldAutoCommit = $FS::UID::AutoCommit;
2346 local $FS::UID::AutoCommit = 0;
2349 $self->select_for_update; #mutex
2351 my $balance = $self->balance;
2352 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2354 unless ( $balance > 0 ) { #redundant?????
2355 $dbh->rollback if $oldAutoCommit; #hmm
2359 if ( exists($options{'retry_card'}) ) {
2360 carp 'retry_card option passed to collect is deprecated; use retry';
2361 $options{'retry'} ||= $options{'retry_card'};
2363 if ( exists($options{'retry'}) && $options{'retry'} ) {
2364 my $error = $self->retry_realtime;
2366 $dbh->rollback if $oldAutoCommit;
2372 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2373 $extra_sql = " AND freq = '1m' ";
2375 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2378 foreach my $cust_bill ( $self->open_cust_bill ) {
2380 # don't try to charge for the same invoice if it's already in a batch
2381 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2383 last if $self->balance <= 0;
2385 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2388 foreach my $part_bill_event ( due_events ( $cust_bill,
2389 exists($options{'payby'})
2395 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2396 || $self->balance <= 0; # or if balance<=0
2399 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2400 warn " do_event " . $cust_bill . " ". (%options) . "\n"
2403 if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2404 # gah, even with transactions.
2405 $dbh->commit if $oldAutoCommit; #well.
2414 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2419 =item retry_realtime
2421 Schedules realtime / batch credit card / electronic check / LEC billing
2422 events for for retry. Useful if card information has changed or manual
2423 retry is desired. The 'collect' method must be called to actually retry
2426 Implementation details: For each of this customer's open invoices, changes
2427 the status of the first "done" (with statustext error) realtime processing
2432 sub retry_realtime {
2435 local $SIG{HUP} = 'IGNORE';
2436 local $SIG{INT} = 'IGNORE';
2437 local $SIG{QUIT} = 'IGNORE';
2438 local $SIG{TERM} = 'IGNORE';
2439 local $SIG{TSTP} = 'IGNORE';
2440 local $SIG{PIPE} = 'IGNORE';
2442 my $oldAutoCommit = $FS::UID::AutoCommit;
2443 local $FS::UID::AutoCommit = 0;
2446 foreach my $cust_bill (
2447 grep { $_->cust_bill_event }
2448 $self->open_cust_bill
2450 my @cust_bill_event =
2451 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2453 #$_->part_bill_event->plan eq 'realtime-card'
2454 $_->part_bill_event->eventcode =~
2455 /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2456 && $_->status eq 'done'
2459 $cust_bill->cust_bill_event;
2460 next unless @cust_bill_event;
2461 my $error = $cust_bill_event[0]->retry;
2463 $dbh->rollback if $oldAutoCommit;
2464 return "error scheduling invoice event for retry: $error";
2469 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2474 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2476 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2477 via a Business::OnlinePayment realtime gateway. See
2478 L<http://420.am/business-onlinepayment> for supported gateways.
2480 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2482 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
2484 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2485 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2486 if set, will override the value from the customer record.
2488 I<description> is a free-text field passed to the gateway. It defaults to
2489 "Internet services".
2491 If an I<invnum> is specified, this payment (if successful) is applied to the
2492 specified invoice. If you don't specify an I<invnum> you might want to
2493 call the B<apply_payments> method.
2495 I<quiet> can be set true to surpress email decline notices.
2497 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
2498 resulting paynum, if any.
2500 I<payunique> is a unique identifier for this payment.
2502 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2509 my( $self, $method, $amount, %options ) = @_;
2511 warn "$me realtime_bop: $method $amount\n";
2512 warn " $_ => $options{$_}\n" foreach keys %options;
2515 $options{'description'} ||= 'Internet services';
2517 eval "use Business::OnlinePayment";
2520 my $payinfo = exists($options{'payinfo'})
2521 ? $options{'payinfo'}
2524 my %method2payby = (
2535 if ( $options{'invnum'} ) {
2536 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2537 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2539 map { $_->part_pkg->taxclass }
2541 map { $_->cust_pkg }
2542 $cust_bill->cust_bill_pkg;
2543 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2544 #different taxclasses
2545 $taxclass = $taxclasses[0];
2549 #look for an agent gateway override first
2551 if ( $method eq 'CC' ) {
2552 $cardtype = cardtype($payinfo);
2553 } elsif ( $method eq 'ECHECK' ) {
2556 $cardtype = $method;
2560 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2561 cardtype => $cardtype,
2562 taxclass => $taxclass, } )
2563 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2565 taxclass => $taxclass, } )
2566 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2567 cardtype => $cardtype,
2569 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2571 taxclass => '', } );
2573 my $payment_gateway = '';
2574 my( $processor, $login, $password, $action, @bop_options );
2575 if ( $override ) { #use a payment gateway override
2577 $payment_gateway = $override->payment_gateway;
2579 $processor = $payment_gateway->gateway_module;
2580 $login = $payment_gateway->gateway_username;
2581 $password = $payment_gateway->gateway_password;
2582 $action = $payment_gateway->gateway_action;
2583 @bop_options = $payment_gateway->options;
2585 } else { #use the standard settings from the config
2587 ( $processor, $login, $password, $action, @bop_options ) =
2588 $self->default_payment_gateway($method);
2596 my $address = exists($options{'address1'})
2597 ? $options{'address1'}
2599 my $address2 = exists($options{'address2'})
2600 ? $options{'address2'}
2602 $address .= ", ". $address2 if length($address2);
2604 my $o_payname = exists($options{'payname'})
2605 ? $options{'payname'}
2607 my($payname, $payfirst, $paylast);
2608 if ( $o_payname && $method ne 'ECHECK' ) {
2609 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2610 or return "Illegal payname $payname";
2611 ($payfirst, $paylast) = ($1, $2);
2613 $payfirst = $self->getfield('first');
2614 $paylast = $self->getfield('last');
2615 $payname = "$payfirst $paylast";
2618 my @invoicing_list = $self->invoicing_list_emailonly;
2619 if ( $conf->exists('emailinvoiceautoalways')
2620 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
2621 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2622 push @invoicing_list, $self->all_emails;
2625 my $email = ($conf->exists('business-onlinepayment-email-override'))
2626 ? $conf->config('business-onlinepayment-email-override')
2627 : $invoicing_list[0];
2631 my $payip = exists($options{'payip'})
2634 $content{customer_ip} = $payip
2637 $content{invoice_number} = $options{'invnum'}
2638 if exists($options{'invnum'}) && length($options{'invnum'});
2640 $content{email_customer} =
2641 ( $conf->exists('business-onlinepayment-email_customer')
2642 || $conf->exists('business-onlinepayment-email-override') );
2645 if ( $method eq 'CC' ) {
2647 $content{card_number} = $payinfo;
2648 $paydate = exists($options{'paydate'})
2649 ? $options{'paydate'}
2651 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2652 $content{expiration} = "$2/$1";
2654 my $paycvv = exists($options{'paycvv'})
2655 ? $options{'paycvv'}
2657 $content{cvv2} = $paycvv
2660 my $paystart_month = exists($options{'paystart_month'})
2661 ? $options{'paystart_month'}
2662 : $self->paystart_month;
2664 my $paystart_year = exists($options{'paystart_year'})
2665 ? $options{'paystart_year'}
2666 : $self->paystart_year;
2668 $content{card_start} = "$paystart_month/$paystart_year"
2669 if $paystart_month && $paystart_year;
2671 my $payissue = exists($options{'payissue'})
2672 ? $options{'payissue'}
2674 $content{issue_number} = $payissue if $payissue;
2676 $content{recurring_billing} = 'YES'
2677 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2679 'payinfo' => $payinfo,
2681 || qsearch('cust_pay', { 'custnum' => $self->custnum,
2683 'paymask' => $self->mask_payinfo('CARD', $payinfo),
2687 } elsif ( $method eq 'ECHECK' ) {
2688 ( $content{account_number}, $content{routing_code} ) =
2689 split('@', $payinfo);
2690 $content{bank_name} = $o_payname;
2691 $content{bank_state} = exists($options{'paystate'})
2692 ? $options{'paystate'}
2693 : $self->getfield('paystate');
2694 $content{account_type} = exists($options{'paytype'})
2695 ? uc($options{'paytype'}) || 'CHECKING'
2696 : uc($self->getfield('paytype')) || 'CHECKING';
2697 $content{account_name} = $payname;
2698 $content{customer_org} = $self->company ? 'B' : 'I';
2699 $content{state_id} = exists($options{'stateid'})
2700 ? $options{'stateid'}
2701 : $self->getfield('stateid');
2702 $content{state_id_state} = exists($options{'stateid_state'})
2703 ? $options{'stateid_state'}
2704 : $self->getfield('stateid_state');
2705 $content{customer_ssn} = exists($options{'ss'})
2708 } elsif ( $method eq 'LEC' ) {
2709 $content{phone} = $payinfo;
2713 # run transaction(s)
2716 my $balance = exists( $options{'balance'} )
2717 ? $options{'balance'}
2720 $self->select_for_update; #mutex ... just until we get our pending record in
2722 #the checks here are intended to catch concurrent payments
2723 #double-form-submission prevention is taken care of in cust_pay_pending::check
2726 return "The customer's balance has changed; $method transaction aborted."
2727 if $self->balance < $balance;
2728 #&& $self->balance < $amount; #might as well anyway?
2730 #also check and make sure there aren't *other* pending payments for this cust
2732 my @pending = qsearch('cust_pay_pending', {
2733 'custnum' => $self->custnum,
2734 'status' => { op=>'!=', value=>'done' }
2736 return "A payment is already being processed for this customer (".
2737 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
2738 "); $method transaction aborted."
2739 if scalar(@pending);
2741 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
2743 my $cust_pay_pending = new FS::cust_pay_pending {
2744 'custnum' => $self->custnum,
2745 #'invnum' => $options{'invnum'},
2748 'payby' => $method2payby{$method},
2749 'payinfo' => $payinfo,
2750 'paydate' => $paydate,
2752 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
2754 $cust_pay_pending->payunique( $options{payunique} )
2755 if defined($options{payunique}) && length($options{payunique});
2756 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
2757 return $cpp_new_err if $cpp_new_err;
2759 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2761 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2762 $transaction->content(
2765 'password' => $password,
2766 'action' => $action1,
2767 'description' => $options{'description'},
2768 'amount' => $amount,
2769 #'invoice_number' => $options{'invnum'},
2770 'customer_id' => $self->custnum,
2771 'last_name' => $paylast,
2772 'first_name' => $payfirst,
2774 'address' => $address,
2775 'city' => ( exists($options{'city'})
2778 'state' => ( exists($options{'state'})
2781 'zip' => ( exists($options{'zip'})
2784 'country' => ( exists($options{'country'})
2785 ? $options{'country'}
2787 'referer' => 'http://cleanwhisker.420.am/',
2789 'phone' => $self->daytime || $self->night,
2793 $cust_pay_pending->status('pending');
2794 my $cpp_pending_err = $cust_pay_pending->replace;
2795 return $cpp_pending_err if $cpp_pending_err;
2797 $transaction->submit();
2799 if ( $transaction->is_success() && $action2 ) {
2801 $cust_pay_pending->status('authorized');
2802 my $cpp_authorized_err = $cust_pay_pending->replace;
2803 return $cpp_authorized_err if $cpp_authorized_err;
2805 my $auth = $transaction->authorization;
2806 my $ordernum = $transaction->can('order_number')
2807 ? $transaction->order_number
2811 new Business::OnlinePayment( $processor, @bop_options );
2818 password => $password,
2819 order_number => $ordernum,
2821 authorization => $auth,
2822 description => $options{'description'},
2825 foreach my $field (qw( authorization_source_code returned_ACI
2826 transaction_identifier validation_code
2827 transaction_sequence_num local_transaction_date
2828 local_transaction_time AVS_result_code )) {
2829 $capture{$field} = $transaction->$field() if $transaction->can($field);
2832 $capture->content( %capture );
2836 unless ( $capture->is_success ) {
2837 my $e = "Authorization successful but capture failed, custnum #".
2838 $self->custnum. ': '. $capture->result_code.
2839 ": ". $capture->error_message;
2846 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
2847 my $cpp_captured_err = $cust_pay_pending->replace;
2848 return $cpp_captured_err if $cpp_captured_err;
2851 # remove paycvv after initial transaction
2854 #false laziness w/misc/process/payment.cgi - check both to make sure working
2856 if ( defined $self->dbdef_table->column('paycvv')
2857 && length($self->paycvv)
2858 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2860 my $error = $self->remove_cvv;
2862 warn "WARNING: error removing cvv: $error\n";
2870 if ( $transaction->is_success() ) {
2873 if ( $payment_gateway ) { # agent override
2874 $paybatch = $payment_gateway->gatewaynum. '-';
2877 $paybatch .= "$processor:". $transaction->authorization;
2879 $paybatch .= ':'. $transaction->order_number
2880 if $transaction->can('order_number')
2881 && length($transaction->order_number);
2883 my $cust_pay = new FS::cust_pay ( {
2884 'custnum' => $self->custnum,
2885 'invnum' => $options{'invnum'},
2888 'payby' => $method2payby{$method},
2889 'payinfo' => $payinfo,
2890 'paybatch' => $paybatch,
2891 'paydate' => $paydate,
2893 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
2894 $cust_pay->payunique( $options{payunique} )
2895 if defined($options{payunique}) && length($options{payunique});
2897 my $oldAutoCommit = $FS::UID::AutoCommit;
2898 local $FS::UID::AutoCommit = 0;
2901 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
2903 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
2906 $cust_pay->invnum(''); #try again with no specific invnum
2907 my $error2 = $cust_pay->insert( $options{'manual'} ?
2908 ( 'manual' => 1 ) : ()
2911 # gah. but at least we have a record of the state we had to abort in
2912 # from cust_pay_pending now.
2913 my $e = "WARNING: $method captured but payment not recorded - ".
2914 "error inserting payment ($processor): $error2".
2915 " (previously tried insert with invnum #$options{'invnum'}" .
2916 ": $error ) - pending payment saved as paypendingnum ".
2917 $cust_pay_pending->paypendingnum. "\n";
2923 if ( $options{'paynum_ref'} ) {
2924 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
2927 $cust_pay_pending->status('done');
2928 $cust_pay_pending->statustext('captured');
2929 my $cpp_done_err = $cust_pay_pending->replace;
2931 if ( $cpp_done_err ) {
2933 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2934 my $e = "WARNING: $method captured but payment not recorded - ".
2935 "error updating status for paypendingnum ".
2936 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
2942 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2943 return ''; #no error
2949 my $perror = "$processor error: ". $transaction->error_message;
2951 unless ( $transaction->error_message ) {
2954 #this should be normalized :/
2956 # bad, ad-hoc B:OP:PayflowPro "transaction_response" BS
2957 if ( $transaction->can('param')
2958 && $transaction->param('transaction_response') ) {
2959 $t_response = $transaction->param('transaction_response')
2961 # slightly better, ad-hoc B:OP:TransactionCentral without "param"
2962 } elsif ( $transaction->can('response_page') ) {
2964 'page' => ( $transaction->can('response_page')
2965 ? $transaction->response_page
2968 'code' => ( $transaction->can('response_code')
2969 ? $transaction->response_code
2972 'headers' => ( $transaction->can('response_headers')
2973 ? $transaction->response_headers
2979 "No additional debugging information available for $processor";
2982 $perror .= "No error_message returned from $processor -- ".
2983 ( ref($t_response) ? Dumper($t_response) : $t_response );
2987 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2988 && $conf->exists('emaildecline')
2989 && grep { $_ ne 'POST' } $self->invoicing_list
2990 && ! grep { $transaction->error_message =~ /$_/ }
2991 $conf->config('emaildecline-exclude')
2993 my @templ = $conf->config('declinetemplate');
2994 my $template = new Text::Template (
2996 SOURCE => [ map "$_\n", @templ ],
2997 ) or return "($perror) can't create template: $Text::Template::ERROR";
2998 $template->compile()
2999 or return "($perror) can't compile template: $Text::Template::ERROR";
3001 my $templ_hash = { error => $transaction->error_message };
3003 my $error = send_email(
3004 'from' => $conf->config('invoice_from'),
3005 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3006 'subject' => 'Your payment could not be processed',
3007 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3010 $perror .= " (also received error sending decline notification: $error)"
3015 $cust_pay_pending->status('done');
3016 $cust_pay_pending->statustext("declined: $perror");
3017 my $cpp_done_err = $cust_pay_pending->replace;
3018 if ( $cpp_done_err ) {
3019 my $e = "WARNING: $method declined but pending payment not resolved - ".
3020 "error updating status for paypendingnum ".
3021 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3023 $perror = "$e ($perror)";
3031 =item default_payment_gateway
3035 sub default_payment_gateway {
3036 my( $self, $method ) = @_;
3038 die "Real-time processing not enabled\n"
3039 unless $conf->exists('business-onlinepayment');
3042 my $bop_config = 'business-onlinepayment';
3043 $bop_config .= '-ach'
3044 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3045 my ( $processor, $login, $password, $action, @bop_options ) =
3046 $conf->config($bop_config);
3047 $action ||= 'normal authorization';
3048 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3049 die "No real-time processor is enabled - ".
3050 "did you set the business-onlinepayment configuration value?\n"
3053 ( $processor, $login, $password, $action, @bop_options )
3058 Removes the I<paycvv> field from the database directly.
3060 If there is an error, returns the error, otherwise returns false.
3066 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3067 or return dbh->errstr;
3068 $sth->execute($self->custnum)
3069 or return $sth->errstr;
3074 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3076 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3077 via a Business::OnlinePayment realtime gateway. See
3078 L<http://420.am/business-onlinepayment> for supported gateways.
3080 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3082 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3084 Most gateways require a reference to an original payment transaction to refund,
3085 so you probably need to specify a I<paynum>.
3087 I<amount> defaults to the original amount of the payment if not specified.
3089 I<reason> specifies a reason for the refund.
3091 I<paydate> specifies the expiration date for a credit card overriding the
3092 value from the customer record or the payment record. Specified as yyyy-mm-dd
3094 Implementation note: If I<amount> is unspecified or equal to the amount of the
3095 orignal payment, first an attempt is made to "void" the transaction via
3096 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3097 the normal attempt is made to "refund" ("credit") the transaction via the
3098 gateway is attempted.
3100 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3101 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3102 #if set, will override the value from the customer record.
3104 #If an I<invnum> is specified, this payment (if successful) is applied to the
3105 #specified invoice. If you don't specify an I<invnum> you might want to
3106 #call the B<apply_payments> method.
3110 #some false laziness w/realtime_bop, not enough to make it worth merging
3111 #but some useful small subs should be pulled out
3112 sub realtime_refund_bop {
3113 my( $self, $method, %options ) = @_;
3115 warn "$me realtime_refund_bop: $method refund\n";
3116 warn " $_ => $options{$_}\n" foreach keys %options;
3119 eval "use Business::OnlinePayment";
3123 # look up the original payment and optionally a gateway for that payment
3127 my $amount = $options{'amount'};
3129 my( $processor, $login, $password, @bop_options ) ;
3130 my( $auth, $order_number ) = ( '', '', '' );
3132 if ( $options{'paynum'} ) {
3134 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3135 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3136 or return "Unknown paynum $options{'paynum'}";
3137 $amount ||= $cust_pay->paid;
3139 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3140 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3141 $cust_pay->paybatch;
3142 my $gatewaynum = '';
3143 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3145 if ( $gatewaynum ) { #gateway for the payment to be refunded
3147 my $payment_gateway =
3148 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3149 die "payment gateway $gatewaynum not found"
3150 unless $payment_gateway;
3152 $processor = $payment_gateway->gateway_module;
3153 $login = $payment_gateway->gateway_username;
3154 $password = $payment_gateway->gateway_password;
3155 @bop_options = $payment_gateway->options;
3157 } else { #try the default gateway
3159 my( $conf_processor, $unused_action );
3160 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3161 $self->default_payment_gateway($method);
3163 return "processor of payment $options{'paynum'} $processor does not".
3164 " match default processor $conf_processor"
3165 unless $processor eq $conf_processor;
3170 } else { # didn't specify a paynum, so look for agent gateway overrides
3171 # like a normal transaction
3174 if ( $method eq 'CC' ) {
3175 $cardtype = cardtype($self->payinfo);
3176 } elsif ( $method eq 'ECHECK' ) {
3179 $cardtype = $method;
3182 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3183 cardtype => $cardtype,
3185 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3187 taxclass => '', } );
3189 if ( $override ) { #use a payment gateway override
3191 my $payment_gateway = $override->payment_gateway;
3193 $processor = $payment_gateway->gateway_module;
3194 $login = $payment_gateway->gateway_username;
3195 $password = $payment_gateway->gateway_password;
3196 #$action = $payment_gateway->gateway_action;
3197 @bop_options = $payment_gateway->options;
3199 } else { #use the standard settings from the config
3202 ( $processor, $login, $password, $unused_action, @bop_options ) =
3203 $self->default_payment_gateway($method);
3208 return "neither amount nor paynum specified" unless $amount;
3213 'password' => $password,
3214 'order_number' => $order_number,
3215 'amount' => $amount,
3216 'referer' => 'http://cleanwhisker.420.am/',
3218 $content{authorization} = $auth
3219 if length($auth); #echeck/ACH transactions have an order # but no auth
3220 #(at least with authorize.net)
3222 my $disable_void_after;
3223 if ($conf->exists('disable_void_after')
3224 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3225 $disable_void_after = $1;
3228 #first try void if applicable
3229 if ( $cust_pay && $cust_pay->paid == $amount
3231 ( not defined($disable_void_after) )
3232 || ( time < ($cust_pay->_date + $disable_void_after ) )
3235 warn " attempting void\n" if $DEBUG > 1;
3236 my $void = new Business::OnlinePayment( $processor, @bop_options );
3237 $void->content( 'action' => 'void', %content );
3239 if ( $void->is_success ) {
3240 my $error = $cust_pay->void($options{'reason'});
3242 # gah, even with transactions.
3243 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3244 "error voiding payment: $error";
3248 warn " void successful\n" if $DEBUG > 1;
3253 warn " void unsuccessful, trying refund\n"
3257 my $address = $self->address1;
3258 $address .= ", ". $self->address2 if $self->address2;
3260 my($payname, $payfirst, $paylast);
3261 if ( $self->payname && $method ne 'ECHECK' ) {
3262 $payname = $self->payname;
3263 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3264 or return "Illegal payname $payname";
3265 ($payfirst, $paylast) = ($1, $2);
3267 $payfirst = $self->getfield('first');
3268 $paylast = $self->getfield('last');
3269 $payname = "$payfirst $paylast";
3272 my @invoicing_list = $self->invoicing_list_emailonly;
3273 if ( $conf->exists('emailinvoiceautoalways')
3274 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3275 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3276 push @invoicing_list, $self->all_emails;
3279 my $email = ($conf->exists('business-onlinepayment-email-override'))
3280 ? $conf->config('business-onlinepayment-email-override')
3281 : $invoicing_list[0];
3283 my $payip = exists($options{'payip'})
3286 $content{customer_ip} = $payip
3290 if ( $method eq 'CC' ) {
3293 $content{card_number} = $payinfo = $cust_pay->payinfo;
3294 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3295 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3296 ($content{expiration} = "$2/$1"); # where available
3298 $content{card_number} = $payinfo = $self->payinfo;
3299 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3300 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3301 $content{expiration} = "$2/$1";
3304 } elsif ( $method eq 'ECHECK' ) {
3307 $payinfo = $cust_pay->payinfo;
3309 $payinfo = $self->payinfo;
3311 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3312 $content{bank_name} = $self->payname;
3313 $content{account_type} = 'CHECKING';
3314 $content{account_name} = $payname;
3315 $content{customer_org} = $self->company ? 'B' : 'I';
3316 $content{customer_ssn} = $self->ss;
3317 } elsif ( $method eq 'LEC' ) {
3318 $content{phone} = $payinfo = $self->payinfo;
3322 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3323 my %sub_content = $refund->content(
3324 'action' => 'credit',
3325 'customer_id' => $self->custnum,
3326 'last_name' => $paylast,
3327 'first_name' => $payfirst,
3329 'address' => $address,
3330 'city' => $self->city,
3331 'state' => $self->state,
3332 'zip' => $self->zip,
3333 'country' => $self->country,
3335 'phone' => $self->daytime || $self->night,
3338 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3342 return "$processor error: ". $refund->error_message
3343 unless $refund->is_success();
3345 my %method2payby = (
3351 my $paybatch = "$processor:". $refund->authorization;
3352 $paybatch .= ':'. $refund->order_number
3353 if $refund->can('order_number') && $refund->order_number;
3355 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3356 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3357 last unless @cust_bill_pay;
3358 my $cust_bill_pay = pop @cust_bill_pay;
3359 my $error = $cust_bill_pay->delete;
3363 my $cust_refund = new FS::cust_refund ( {
3364 'custnum' => $self->custnum,
3365 'paynum' => $options{'paynum'},
3366 'refund' => $amount,
3368 'payby' => $method2payby{$method},
3369 'payinfo' => $payinfo,
3370 'paybatch' => $paybatch,
3371 'reason' => $options{'reason'} || 'card or ACH refund',
3373 my $error = $cust_refund->insert;
3375 $cust_refund->paynum(''); #try again with no specific paynum
3376 my $error2 = $cust_refund->insert;
3378 # gah, even with transactions.
3379 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3380 "error inserting refund ($processor): $error2".
3381 " (previously tried insert with paynum #$options{'paynum'}" .
3392 =item batch_card OPTION => VALUE...
3394 Adds a payment for this invoice to the pending credit card batch (see
3395 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3396 runs the payment using a realtime gateway.
3401 my ($self, %options) = @_;
3404 if (exists($options{amount})) {
3405 $amount = $options{amount};
3407 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3409 return '' unless $amount > 0;
3411 my $invnum = delete $options{invnum};
3412 my $payby = $options{invnum} || $self->payby; #dubious
3414 if ($options{'realtime'}) {
3415 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3421 my $oldAutoCommit = $FS::UID::AutoCommit;
3422 local $FS::UID::AutoCommit = 0;
3425 #this needs to handle mysql as well as Pg, like svc_acct.pm
3426 #(make it into a common function if folks need to do batching with mysql)
3427 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3428 or return "Cannot lock pay_batch: " . $dbh->errstr;
3432 'payby' => FS::payby->payby2payment($payby),
3435 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3437 unless ( $pay_batch ) {
3438 $pay_batch = new FS::pay_batch \%pay_batch;
3439 my $error = $pay_batch->insert;
3441 $dbh->rollback if $oldAutoCommit;
3442 die "error creating new batch: $error\n";
3446 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3447 'batchnum' => $pay_batch->batchnum,
3448 'custnum' => $self->custnum,
3451 foreach (qw( address1 address2 city state zip country payby payinfo paydate
3453 $options{$_} = '' unless exists($options{$_});
3456 my $cust_pay_batch = new FS::cust_pay_batch ( {
3457 'batchnum' => $pay_batch->batchnum,
3458 'invnum' => $invnum || 0, # is there a better value?
3459 # this field should be
3461 # cust_bill_pay_batch now
3462 'custnum' => $self->custnum,
3463 'last' => $self->getfield('last'),
3464 'first' => $self->getfield('first'),
3465 'address1' => $options{address1} || $self->address1,
3466 'address2' => $options{address2} || $self->address2,
3467 'city' => $options{city} || $self->city,
3468 'state' => $options{state} || $self->state,
3469 'zip' => $options{zip} || $self->zip,
3470 'country' => $options{country} || $self->country,
3471 'payby' => $options{payby} || $self->payby,
3472 'payinfo' => $options{payinfo} || $self->payinfo,
3473 'exp' => $options{paydate} || $self->paydate,
3474 'payname' => $options{payname} || $self->payname,
3475 'amount' => $amount, # consolidating
3478 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3479 if $old_cust_pay_batch;
3482 if ($old_cust_pay_batch) {
3483 $error = $cust_pay_batch->replace($old_cust_pay_batch)
3485 $error = $cust_pay_batch->insert;
3489 $dbh->rollback if $oldAutoCommit;
3493 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
3494 foreach my $cust_bill ($self->open_cust_bill) {
3495 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3496 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3497 'invnum' => $cust_bill->invnum,
3498 'paybatchnum' => $cust_pay_batch->paybatchnum,
3499 'amount' => $cust_bill->owed,
3502 if ($unapplied >= $cust_bill_pay_batch->amount){
3503 $unapplied -= $cust_bill_pay_batch->amount;
3506 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
3507 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
3509 $error = $cust_bill_pay_batch->insert;
3511 $dbh->rollback if $oldAutoCommit;
3516 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3522 Returns the total owed for this customer on all invoices
3523 (see L<FS::cust_bill/owed>).
3529 $self->total_owed_date(2145859200); #12/31/2037
3532 =item total_owed_date TIME
3534 Returns the total owed for this customer on all invoices with date earlier than
3535 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3536 see L<Time::Local> and L<Date::Parse> for conversion functions.
3540 sub total_owed_date {
3544 foreach my $cust_bill (
3545 grep { $_->_date <= $time }
3546 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3548 $total_bill += $cust_bill->owed;
3550 sprintf( "%.2f", $total_bill );
3553 =item apply_payments_and_credits
3555 Applies unapplied payments and credits.
3557 In most cases, this new method should be used in place of sequential
3558 apply_payments and apply_credits methods.
3560 If there is an error, returns the error, otherwise returns false.
3564 sub apply_payments_and_credits {
3567 local $SIG{HUP} = 'IGNORE';
3568 local $SIG{INT} = 'IGNORE';
3569 local $SIG{QUIT} = 'IGNORE';
3570 local $SIG{TERM} = 'IGNORE';
3571 local $SIG{TSTP} = 'IGNORE';
3572 local $SIG{PIPE} = 'IGNORE';
3574 my $oldAutoCommit = $FS::UID::AutoCommit;
3575 local $FS::UID::AutoCommit = 0;
3578 $self->select_for_update; #mutex
3580 foreach my $cust_bill ( $self->open_cust_bill ) {
3581 my $error = $cust_bill->apply_payments_and_credits;
3583 $dbh->rollback if $oldAutoCommit;
3584 return "Error applying: $error";
3588 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3593 =item apply_credits OPTION => VALUE ...
3595 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3596 to outstanding invoice balances in chronological order (or reverse
3597 chronological order if the I<order> option is set to B<newest>) and returns the
3598 value of any remaining unapplied credits available for refund (see
3599 L<FS::cust_refund>).
3601 Dies if there is an error.
3609 local $SIG{HUP} = 'IGNORE';
3610 local $SIG{INT} = 'IGNORE';
3611 local $SIG{QUIT} = 'IGNORE';
3612 local $SIG{TERM} = 'IGNORE';
3613 local $SIG{TSTP} = 'IGNORE';
3614 local $SIG{PIPE} = 'IGNORE';
3616 my $oldAutoCommit = $FS::UID::AutoCommit;
3617 local $FS::UID::AutoCommit = 0;
3620 $self->select_for_update; #mutex
3622 unless ( $self->total_credited ) {
3623 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3627 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3628 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3630 my @invoices = $self->open_cust_bill;
3631 @invoices = sort { $b->_date <=> $a->_date } @invoices
3632 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3635 foreach my $cust_bill ( @invoices ) {
3638 if ( !defined($credit) || $credit->credited == 0) {
3639 $credit = pop @credits or last;
3642 if ($cust_bill->owed >= $credit->credited) {
3643 $amount=$credit->credited;
3645 $amount=$cust_bill->owed;
3648 my $cust_credit_bill = new FS::cust_credit_bill ( {
3649 'crednum' => $credit->crednum,
3650 'invnum' => $cust_bill->invnum,
3651 'amount' => $amount,
3653 my $error = $cust_credit_bill->insert;
3655 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3659 redo if ($cust_bill->owed > 0);
3663 my $total_credited = $self->total_credited;
3665 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3667 return $total_credited;
3670 =item apply_payments
3672 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3673 to outstanding invoice balances in chronological order.
3675 #and returns the value of any remaining unapplied payments.
3677 Dies if there is an error.
3681 sub apply_payments {
3684 local $SIG{HUP} = 'IGNORE';
3685 local $SIG{INT} = 'IGNORE';
3686 local $SIG{QUIT} = 'IGNORE';
3687 local $SIG{TERM} = 'IGNORE';
3688 local $SIG{TSTP} = 'IGNORE';
3689 local $SIG{PIPE} = 'IGNORE';
3691 my $oldAutoCommit = $FS::UID::AutoCommit;
3692 local $FS::UID::AutoCommit = 0;
3695 $self->select_for_update; #mutex
3699 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3700 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3702 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3703 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3707 foreach my $cust_bill ( @invoices ) {
3710 if ( !defined($payment) || $payment->unapplied == 0 ) {
3711 $payment = pop @payments or last;
3714 if ( $cust_bill->owed >= $payment->unapplied ) {
3715 $amount = $payment->unapplied;
3717 $amount = $cust_bill->owed;
3720 my $cust_bill_pay = new FS::cust_bill_pay ( {
3721 'paynum' => $payment->paynum,
3722 'invnum' => $cust_bill->invnum,
3723 'amount' => $amount,
3725 my $error = $cust_bill_pay->insert;
3727 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3731 redo if ( $cust_bill->owed > 0);
3735 my $total_unapplied_payments = $self->total_unapplied_payments;
3737 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3739 return $total_unapplied_payments;
3742 =item total_credited
3744 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3745 customer. See L<FS::cust_credit/credited>.
3749 sub total_credited {
3751 my $total_credit = 0;
3752 foreach my $cust_credit ( qsearch('cust_credit', {
3753 'custnum' => $self->custnum,
3755 $total_credit += $cust_credit->credited;
3757 sprintf( "%.2f", $total_credit );
3760 =item total_unapplied_payments
3762 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3763 See L<FS::cust_pay/unapplied>.
3767 sub total_unapplied_payments {
3769 my $total_unapplied = 0;
3770 foreach my $cust_pay ( qsearch('cust_pay', {
3771 'custnum' => $self->custnum,
3773 $total_unapplied += $cust_pay->unapplied;
3775 sprintf( "%.2f", $total_unapplied );
3778 =item total_unapplied_refunds
3780 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
3781 customer. See L<FS::cust_refund/unapplied>.
3785 sub total_unapplied_refunds {
3787 my $total_unapplied = 0;
3788 foreach my $cust_refund ( qsearch('cust_refund', {
3789 'custnum' => $self->custnum,
3791 $total_unapplied += $cust_refund->unapplied;
3793 sprintf( "%.2f", $total_unapplied );
3798 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3799 total_credited minus total_unapplied_payments).
3807 + $self->total_unapplied_refunds
3808 - $self->total_credited
3809 - $self->total_unapplied_payments
3813 =item balance_date TIME
3815 Returns the balance for this customer, only considering invoices with date
3816 earlier than TIME (total_owed_date minus total_credited minus
3817 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3818 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3827 $self->total_owed_date($time)
3828 + $self->total_unapplied_refunds
3829 - $self->total_credited
3830 - $self->total_unapplied_payments
3834 =item in_transit_payments
3836 Returns the total of requests for payments for this customer pending in
3837 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3841 sub in_transit_payments {
3843 my $in_transit_payments = 0;
3844 foreach my $pay_batch ( qsearch('pay_batch', {
3847 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3848 'batchnum' => $pay_batch->batchnum,
3849 'custnum' => $self->custnum,
3851 $in_transit_payments += $cust_pay_batch->amount;
3854 sprintf( "%.2f", $in_transit_payments );
3857 =item paydate_monthyear
3859 Returns a two-element list consisting of the month and year of this customer's
3860 paydate (credit card expiration date for CARD customers)
3864 sub paydate_monthyear {
3866 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3868 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3875 =item invoicing_list [ ARRAYREF ]
3877 If an arguement is given, sets these email addresses as invoice recipients
3878 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3879 (except as warnings), so use check_invoicing_list first.
3881 Returns a list of email addresses (with svcnum entries expanded).
3883 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3884 check it without disturbing anything by passing nothing.
3886 This interface may change in the future.
3890 sub invoicing_list {
3891 my( $self, $arrayref ) = @_;
3894 my @cust_main_invoice;
3895 if ( $self->custnum ) {
3896 @cust_main_invoice =
3897 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3899 @cust_main_invoice = ();
3901 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3902 #warn $cust_main_invoice->destnum;
3903 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3904 #warn $cust_main_invoice->destnum;
3905 my $error = $cust_main_invoice->delete;
3906 warn $error if $error;
3909 if ( $self->custnum ) {
3910 @cust_main_invoice =
3911 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3913 @cust_main_invoice = ();
3915 my %seen = map { $_->address => 1 } @cust_main_invoice;
3916 foreach my $address ( @{$arrayref} ) {
3917 next if exists $seen{$address} && $seen{$address};
3918 $seen{$address} = 1;
3919 my $cust_main_invoice = new FS::cust_main_invoice ( {
3920 'custnum' => $self->custnum,
3923 my $error = $cust_main_invoice->insert;
3924 warn $error if $error;
3928 if ( $self->custnum ) {
3930 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3937 =item check_invoicing_list ARRAYREF
3939 Checks these arguements as valid input for the invoicing_list method. If there
3940 is an error, returns the error, otherwise returns false.
3944 sub check_invoicing_list {
3945 my( $self, $arrayref ) = @_;
3947 foreach my $address ( @$arrayref ) {
3949 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3950 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3953 my $cust_main_invoice = new FS::cust_main_invoice ( {
3954 'custnum' => $self->custnum,
3957 my $error = $self->custnum
3958 ? $cust_main_invoice->check
3959 : $cust_main_invoice->checkdest
3961 return $error if $error;
3965 return "Email address required"
3966 if $conf->exists('cust_main-require_invoicing_list_email')
3967 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3972 =item set_default_invoicing_list
3974 Sets the invoicing list to all accounts associated with this customer,
3975 overwriting any previous invoicing list.
3979 sub set_default_invoicing_list {
3981 $self->invoicing_list($self->all_emails);
3986 Returns the email addresses of all accounts provisioned for this customer.
3993 foreach my $cust_pkg ( $self->all_pkgs ) {
3994 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3996 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3997 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3999 $list{$_}=1 foreach map { $_->email } @svc_acct;
4004 =item invoicing_list_addpost
4006 Adds postal invoicing to this customer. If this customer is already configured
4007 to receive postal invoices, does nothing.
4011 sub invoicing_list_addpost {
4013 return if grep { $_ eq 'POST' } $self->invoicing_list;
4014 my @invoicing_list = $self->invoicing_list;
4015 push @invoicing_list, 'POST';
4016 $self->invoicing_list(\@invoicing_list);
4019 =item invoicing_list_emailonly
4021 Returns the list of email invoice recipients (invoicing_list without non-email
4022 destinations such as POST and FAX).
4026 sub invoicing_list_emailonly {
4028 warn "$me invoicing_list_emailonly called"
4030 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4033 =item invoicing_list_emailonly_scalar
4035 Returns the list of email invoice recipients (invoicing_list without non-email
4036 destinations such as POST and FAX) as a comma-separated scalar.
4040 sub invoicing_list_emailonly_scalar {
4042 warn "$me invoicing_list_emailonly_scalar called"
4044 join(', ', $self->invoicing_list_emailonly);
4047 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4049 Returns an array of customers referred by this customer (referral_custnum set
4050 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4051 customers referred by customers referred by this customer and so on, inclusive.
4052 The default behavior is DEPTH 1 (no recursion).
4056 sub referral_cust_main {
4058 my $depth = @_ ? shift : 1;
4059 my $exclude = @_ ? shift : {};
4062 map { $exclude->{$_->custnum}++; $_; }
4063 grep { ! $exclude->{ $_->custnum } }
4064 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4068 map { $_->referral_cust_main($depth-1, $exclude) }
4075 =item referral_cust_main_ncancelled
4077 Same as referral_cust_main, except only returns customers with uncancelled
4082 sub referral_cust_main_ncancelled {
4084 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4087 =item referral_cust_pkg [ DEPTH ]
4089 Like referral_cust_main, except returns a flat list of all unsuspended (and
4090 uncancelled) packages for each customer. The number of items in this list may
4091 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4095 sub referral_cust_pkg {
4097 my $depth = @_ ? shift : 1;
4099 map { $_->unsuspended_pkgs }
4100 grep { $_->unsuspended_pkgs }
4101 $self->referral_cust_main($depth);
4104 =item referring_cust_main
4106 Returns the single cust_main record for the customer who referred this customer
4107 (referral_custnum), or false.
4111 sub referring_cust_main {
4113 return '' unless $self->referral_custnum;
4114 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4117 =item credit AMOUNT, REASON
4119 Applies a credit to this customer. If there is an error, returns the error,
4120 otherwise returns false.
4125 my( $self, $amount, $reason, %options ) = @_;
4126 my $cust_credit = new FS::cust_credit {
4127 'custnum' => $self->custnum,
4128 'amount' => $amount,
4129 'reason' => $reason,
4131 $cust_credit->insert(%options);
4134 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4136 Creates a one-time charge for this customer. If there is an error, returns
4137 the error, otherwise returns false.
4143 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4144 if ( ref( $_[0] ) ) {
4145 $amount = $_[0]->{amount};
4146 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4147 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4148 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4149 : '$'. sprintf("%.2f",$amount);
4150 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4151 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4152 $additional = $_[0]->{additional};
4156 $pkg = @_ ? shift : 'One-time charge';
4157 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4158 $taxclass = @_ ? shift : '';
4162 local $SIG{HUP} = 'IGNORE';
4163 local $SIG{INT} = 'IGNORE';
4164 local $SIG{QUIT} = 'IGNORE';
4165 local $SIG{TERM} = 'IGNORE';
4166 local $SIG{TSTP} = 'IGNORE';
4167 local $SIG{PIPE} = 'IGNORE';
4169 my $oldAutoCommit = $FS::UID::AutoCommit;
4170 local $FS::UID::AutoCommit = 0;
4173 my $part_pkg = new FS::part_pkg ( {
4175 'comment' => $comment,
4179 'classnum' => $classnum ? $classnum : '',
4180 'taxclass' => $taxclass,
4183 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4184 ( 0 .. @$additional - 1 )
4186 'additional_count' => scalar(@$additional),
4187 'setup_fee' => $amount,
4190 my $error = $part_pkg->insert( options => \%options );
4192 $dbh->rollback if $oldAutoCommit;
4196 my $pkgpart = $part_pkg->pkgpart;
4197 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4198 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4199 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4200 $error = $type_pkgs->insert;
4202 $dbh->rollback if $oldAutoCommit;
4207 my $cust_pkg = new FS::cust_pkg ( {
4208 'custnum' => $self->custnum,
4209 'pkgpart' => $pkgpart,
4210 'quantity' => $quantity,
4213 $error = $cust_pkg->insert;
4215 $dbh->rollback if $oldAutoCommit;
4219 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4226 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4232 sort { $a->_date <=> $b->_date }
4233 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4236 =item open_cust_bill
4238 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4243 sub open_cust_bill {
4245 grep { $_->owed > 0 } $self->cust_bill;
4250 Returns all the credits (see L<FS::cust_credit>) for this customer.
4256 sort { $a->_date <=> $b->_date }
4257 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4262 Returns all the payments (see L<FS::cust_pay>) for this customer.
4268 sort { $a->_date <=> $b->_date }
4269 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4274 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4280 sort { $a->_date <=> $b->_date }
4281 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4287 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4293 sort { $a->_date <=> $b->_date }
4294 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4299 Returns a name string for this customer, either "Company (Last, First)" or
4306 my $name = $self->contact;
4307 $name = $self->company. " ($name)" if $self->company;
4313 Returns a name string for this (service/shipping) contact, either
4314 "Company (Last, First)" or "Last, First".
4320 if ( $self->get('ship_last') ) {
4321 my $name = $self->ship_contact;
4322 $name = $self->ship_company. " ($name)" if $self->ship_company;
4331 Returns this customer's full (billing) contact name only, "Last, First"
4337 $self->get('last'). ', '. $self->first;
4342 Returns this customer's full (shipping) contact name only, "Last, First"
4348 $self->get('ship_last')
4349 ? $self->get('ship_last'). ', '. $self->ship_first
4355 Returns this customer's full country name
4361 code2country($self->country);
4368 Returns a status string for this customer, currently:
4372 =item prospect - No packages have ever been ordered
4374 =item active - One or more recurring packages is active
4376 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4378 =item suspended - All non-cancelled recurring packages are suspended
4380 =item cancelled - All recurring packages are cancelled
4386 sub status { shift->cust_status(@_); }
4390 for my $status (qw( prospect active inactive suspended cancelled )) {
4391 my $method = $status.'_sql';
4392 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4393 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4394 $sth->execute( ($self->custnum) x $numnum )
4395 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4396 return $status if $sth->fetchrow_arrayref->[0];
4400 =item ucfirst_cust_status
4402 =item ucfirst_status
4404 Returns the status with the first character capitalized.
4408 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4410 sub ucfirst_cust_status {
4412 ucfirst($self->cust_status);
4417 Returns a hex triplet color string for this customer's status.
4421 use vars qw(%statuscolor);
4422 tie %statuscolor, 'Tie::IxHash',
4423 'prospect' => '7e0079', #'000000', #black? naw, purple
4424 'active' => '00CC00', #green
4425 'inactive' => '0000CC', #blue
4426 'suspended' => 'FF9900', #yellow
4427 'cancelled' => 'FF0000', #red
4430 sub statuscolor { shift->cust_statuscolor(@_); }
4432 sub cust_statuscolor {
4434 $statuscolor{$self->cust_status};
4439 =head1 CLASS METHODS
4445 Class method that returns the list of possible status strings for customers
4446 (see L<the status method|/status>). For example:
4448 @statuses = FS::cust_main->statuses();
4453 #my $self = shift; #could be class...
4459 Returns an SQL expression identifying prospective cust_main records (customers
4460 with no packages ever ordered)
4464 use vars qw($select_count_pkgs);
4465 $select_count_pkgs =
4466 "SELECT COUNT(*) FROM cust_pkg
4467 WHERE cust_pkg.custnum = cust_main.custnum";
4469 sub select_count_pkgs_sql {
4473 sub prospect_sql { "
4474 0 = ( $select_count_pkgs )
4479 Returns an SQL expression identifying active cust_main records (customers with
4480 active recurring packages).
4485 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
4491 Returns an SQL expression identifying inactive cust_main records (customers with
4492 no active recurring packages, but otherwise unsuspended/uncancelled).
4496 sub inactive_sql { "
4497 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4499 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4505 Returns an SQL expression identifying suspended cust_main records.
4510 sub suspended_sql { susp_sql(@_); }
4512 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
4514 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4520 Returns an SQL expression identifying cancelled cust_main records.
4524 sub cancelled_sql { cancel_sql(@_); }
4527 my $recurring_sql = FS::cust_pkg->recurring_sql;
4528 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
4531 0 < ( $select_count_pkgs )
4532 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
4533 AND 0 = ( $select_count_pkgs AND $recurring_sql
4534 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4541 =item uncancelled_sql
4543 Returns an SQL expression identifying un-cancelled cust_main records.
4547 sub uncancelled_sql { uncancel_sql(@_); }
4548 sub uncancel_sql { "
4549 ( 0 < ( $select_count_pkgs
4550 AND ( cust_pkg.cancel IS NULL
4551 OR cust_pkg.cancel = 0
4554 OR 0 = ( $select_count_pkgs )
4560 Returns an SQL fragment to retreive the balance.
4565 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4566 WHERE cust_bill.custnum = cust_main.custnum )
4567 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4568 WHERE cust_pay.custnum = cust_main.custnum )
4569 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4570 WHERE cust_credit.custnum = cust_main.custnum )
4571 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4572 WHERE cust_refund.custnum = cust_main.custnum )
4575 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4577 Returns an SQL fragment to retreive the balance for this customer, only
4578 considering invoices with date earlier than START_TIME, and optionally not
4579 later than END_TIME (total_owed_date minus total_credited minus
4580 total_unapplied_payments).
4582 Times are specified as SQL fragments or numeric
4583 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4584 L<Date::Parse> for conversion functions. The empty string can be passed
4585 to disable that time constraint completely.
4587 Available options are:
4591 =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)
4593 =item total - set to true to remove all customer comparison clauses, for totals
4595 =item where - WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4597 =item join - JOIN clause (typically used with the total option)
4605 sub balance_date_sql {
4606 my( $class, $start, $end, %opt ) = @_;
4608 my $owed = FS::cust_bill->owed_sql;
4609 my $unapp_refund = FS::cust_refund->unapplied_sql;
4610 my $unapp_credit = FS::cust_credit->unapplied_sql;
4611 my $unapp_pay = FS::cust_pay->unapplied_sql;
4613 my $j = $opt{'join'} || '';
4615 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4616 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4617 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4618 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4620 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4621 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4622 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4623 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4628 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4630 Helper method for balance_date_sql; name (and usage) subject to change
4631 (suggestions welcome).
4633 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4634 cust_refund, cust_credit or cust_pay).
4636 If TABLE is "cust_bill" or the unapplied_date option is true, only
4637 considers records with date earlier than START_TIME, and optionally not
4638 later than END_TIME .
4642 sub _money_table_where {
4643 my( $class, $table, $start, $end, %opt ) = @_;
4646 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4647 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4648 push @where, "$table._date <= $start" if defined($start) && length($start);
4649 push @where, "$table._date > $end" if defined($end) && length($end);
4651 push @where, @{$opt{'where'}} if $opt{'where'};
4652 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4658 =item search_sql HASHREF
4662 Returns a qsearch hash expression to search for parameters specified in HREF.
4663 Valid parameters are
4671 =item cancelled_pkgs
4677 listref of start date, end date
4683 =item current_balance
4685 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
4689 =item flattened_pkgs
4698 my ($class, $params) = @_;
4709 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4711 "cust_main.agentnum = $1";
4718 #prospect active inactive suspended cancelled
4719 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
4720 my $method = $params->{'status'}. '_sql';
4721 #push @where, $class->$method();
4722 push @where, FS::cust_main->$method();
4726 # parse cancelled package checkbox
4731 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
4732 unless $params->{'cancelled_pkgs'};
4738 foreach my $field (qw( signupdate )) {
4740 next unless exists($params->{$field});
4742 my($beginning, $ending) = @{$params->{$field}};
4745 "cust_main.$field IS NOT NULL",
4746 "cust_main.$field >= $beginning",
4747 "cust_main.$field <= $ending";
4749 $orderby ||= "ORDER BY cust_main.$field";
4757 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
4759 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
4766 #my $balance_sql = $class->balance_sql();
4767 my $balance_sql = FS::cust_main->balance_sql();
4769 push @where, map { s/current_balance/$balance_sql/; $_ }
4770 @{ $params->{'current_balance'} };
4773 # setup queries, subs, etc. for the search
4776 $orderby ||= 'ORDER BY custnum';
4778 # here is the agent virtualization
4779 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
4781 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4783 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
4785 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
4787 my $select = join(', ',
4788 'cust_main.custnum',
4789 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
4792 my(@extra_headers) = ();
4793 my(@extra_fields) = ();
4795 if ($params->{'flattened_pkgs'}) {
4797 if ($dbh->{Driver}->{Name} eq 'Pg') {
4799 $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";
4801 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
4802 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
4803 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
4805 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
4806 "omitting packing information from report.";
4809 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";
4811 my $sth = dbh->prepare($header_query) or die dbh->errstr;
4812 $sth->execute() or die $sth->errstr;
4813 my $headerrow = $sth->fetchrow_arrayref;
4814 my $headercount = $headerrow ? $headerrow->[0] : 0;
4815 while($headercount) {
4816 unshift @extra_headers, "Package ". $headercount;
4817 unshift @extra_fields, eval q!sub {my $c = shift;
4818 my @a = split '\|', $c->magic;
4819 my $p = $a[!.--$headercount. q!];
4827 'table' => 'cust_main',
4828 'select' => $select,
4830 'extra_sql' => $extra_sql,
4831 'order_by' => $orderby,
4832 'count_query' => $count_query,
4833 'extra_headers' => \@extra_headers,
4834 'extra_fields' => \@extra_fields,
4839 =item email_search_sql HASHREF
4843 Emails a notice to the specified customers.
4845 Valid parameters are those of the L<search_sql> method, plus the following:
4867 Optional job queue job for status updates.
4871 Returns an error message, or false for success.
4873 If an error occurs during any email, stops the enture send and returns that
4874 error. Presumably if you're getting SMTP errors aborting is better than
4875 retrying everything.
4879 sub email_search_sql {
4880 my($class, $params) = @_;
4882 my $from = delete $params->{from};
4883 my $subject = delete $params->{subject};
4884 my $html_body = delete $params->{html_body};
4885 my $text_body = delete $params->{text_body};
4887 my $job = delete $params->{'job'};
4889 my $sql_query = $class->search_sql($params);
4891 my $count_query = delete($sql_query->{'count_query'});
4892 my $count_sth = dbh->prepare($count_query)
4893 or die "Error preparing $count_query: ". dbh->errstr;
4895 or die "Error executing $count_query: ". $count_sth->errstr;
4896 my $count_arrayref = $count_sth->fetchrow_arrayref;
4897 my $num_cust = $count_arrayref->[0];
4899 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
4900 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
4903 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
4905 #eventually order+limit magic to reduce memory use?
4906 foreach my $cust_main ( qsearch($sql_query) ) {
4908 my $to = $cust_main->invoicing_list_emailonly_scalar;
4911 my $error = send_email(
4915 'subject' => $subject,
4916 'html_body' => $html_body,
4917 'text_body' => $text_body,
4920 return $error if $error;
4922 if ( $job ) { #progressbar foo
4924 if ( time - $min_sec > $last ) {
4925 my $error = $job->update_statustext(
4926 int( 100 * $num / $num_cust )
4928 die $error if $error;
4938 use Storable qw(thaw);
4941 sub process_email_search_sql {
4943 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
4945 my $param = thaw(decode_base64(shift));
4946 warn Dumper($param) if $DEBUG;
4948 $param->{'job'} = $job;
4950 my $error = FS::cust_main->email_search_sql( $param );
4951 die $error if $error;
4955 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
4957 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
4958 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
4959 appropriate ship_ field is also searched).
4961 Additional options are the same as FS::Record::qsearch
4966 my( $self, $fuzzy, $hash, @opt) = @_;
4971 check_and_rebuild_fuzzyfiles();
4972 foreach my $field ( keys %$fuzzy ) {
4974 my $all = $self->all_X($field);
4975 next unless scalar(@$all);
4978 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
4981 foreach ( keys %match ) {
4982 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
4983 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
4986 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
4989 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
4991 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
4999 Returns a masked version of the named field
5004 my ($self, $field) = @_;
5008 'x'x(length($self->getfield($field))-4).
5009 substr($self->getfield($field), (length($self->getfield($field))-4));
5019 =item smart_search OPTION => VALUE ...
5021 Accepts the following options: I<search>, the string to search for. The string
5022 will be searched for as a customer number, phone number, name or company name,
5023 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5024 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5025 skip fuzzy matching when an exact match is found.
5027 Any additional options are treated as an additional qualifier on the search
5030 Returns a (possibly empty) array of FS::cust_main objects.
5037 #here is the agent virtualization
5038 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5042 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5043 my $search = delete $options{'search'};
5044 ( my $alphanum_search = $search ) =~ s/\W//g;
5046 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5048 #false laziness w/Record::ut_phone
5049 my $phonen = "$1-$2-$3";
5050 $phonen .= " x$4" if $4;
5052 push @cust_main, qsearch( {
5053 'table' => 'cust_main',
5054 'hashref' => { %options },
5055 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5057 join(' OR ', map "$_ = '$phonen'",
5058 qw( daytime night fax
5059 ship_daytime ship_night ship_fax )
5062 " AND $agentnums_sql", #agent virtualization
5065 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5066 #try looking for matches with extensions unless one was specified
5068 push @cust_main, qsearch( {
5069 'table' => 'cust_main',
5070 'hashref' => { %options },
5071 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5073 join(' OR ', map "$_ LIKE '$phonen\%'",
5075 ship_daytime ship_night )
5078 " AND $agentnums_sql", #agent virtualization
5083 # custnum search (also try agent_custid), with some tweaking options if your
5084 # legacy cust "numbers" have letters
5085 } elsif ( $search =~ /^\s*(\d+)\s*$/
5086 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5087 && $search =~ /^\s*(\w\w?\d+)\s*$/
5092 push @cust_main, qsearch( {
5093 'table' => 'cust_main',
5094 'hashref' => { 'custnum' => $1, %options },
5095 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5098 push @cust_main, qsearch( {
5099 'table' => 'cust_main',
5100 'hashref' => { 'agent_custid' => $1, %options },
5101 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5104 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5106 my($company, $last, $first) = ( $1, $2, $3 );
5108 # "Company (Last, First)"
5109 #this is probably something a browser remembered,
5110 #so just do an exact search
5112 foreach my $prefix ( '', 'ship_' ) {
5113 push @cust_main, qsearch( {
5114 'table' => 'cust_main',
5115 'hashref' => { $prefix.'first' => $first,
5116 $prefix.'last' => $last,
5117 $prefix.'company' => $company,
5120 'extra_sql' => " AND $agentnums_sql",
5124 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5125 # try (ship_){last,company}
5129 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5130 # # full strings the browser remembers won't work
5131 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5133 use Lingua::EN::NameParse;
5134 my $NameParse = new Lingua::EN::NameParse(
5136 allow_reversed => 1,
5139 my($last, $first) = ( '', '' );
5140 #maybe disable this too and just rely on NameParse?
5141 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5143 ($last, $first) = ( $1, $2 );
5145 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5146 } elsif ( ! $NameParse->parse($value) ) {
5148 my %name = $NameParse->components;
5149 $first = $name{'given_name_1'};
5150 $last = $name{'surname_1'};
5154 if ( $first && $last ) {
5156 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5159 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5161 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5162 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5165 push @cust_main, qsearch( {
5166 'table' => 'cust_main',
5167 'hashref' => \%options,
5168 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5171 # or it just be something that was typed in... (try that in a sec)
5175 my $q_value = dbh->quote($value);
5178 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5179 $sql .= " ( LOWER(last) = $q_value
5180 OR LOWER(company) = $q_value
5181 OR LOWER(ship_last) = $q_value
5182 OR LOWER(ship_company) = $q_value
5185 push @cust_main, qsearch( {
5186 'table' => 'cust_main',
5187 'hashref' => \%options,
5188 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5191 #always do substring & fuzzy,
5192 #getting complains searches are not returning enough
5193 unless ( @cust_main && $skip_fuzzy ) { #no exact match, trying substring/fuzzy
5195 #still some false laziness w/search_sql (was search/cust_main.cgi)
5200 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
5201 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5204 if ( $first && $last ) {
5207 { 'first' => { op=>'ILIKE', value=>"%$first%" },
5208 'last' => { op=>'ILIKE', value=>"%$last%" },
5210 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
5211 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
5218 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
5219 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
5223 foreach my $hashref ( @hashrefs ) {
5225 push @cust_main, qsearch( {
5226 'table' => 'cust_main',
5227 'hashref' => { %$hashref,
5230 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
5239 " AND $agentnums_sql", #extra_sql #agent virtualization
5242 if ( $first && $last ) {
5243 push @cust_main, FS::cust_main->fuzzy_search(
5244 { 'last' => $last, #fuzzy hashref
5245 'first' => $first }, #
5249 foreach my $field ( 'last', 'company' ) {
5251 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
5256 #eliminate duplicates
5258 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5268 Accepts the following options: I<email>, the email address to search for. The
5269 email address will be searched for as an email invoice destination and as an
5272 #Any additional options are treated as an additional qualifier on the search
5273 #(i.e. I<agentnum>).
5275 Returns a (possibly empty) array of FS::cust_main objects (but usually just
5285 my $email = delete $options{'email'};
5287 #we're only being used by RT at the moment... no agent virtualization yet
5288 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5292 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
5294 my ( $user, $domain ) = ( $1, $2 );
5296 warn "$me smart_search: searching for $user in domain $domain"
5302 'table' => 'cust_main_invoice',
5303 'hashref' => { 'dest' => $email },
5310 map $_->cust_svc->cust_pkg,
5312 'table' => 'svc_acct',
5313 'hashref' => { 'username' => $user, },
5315 'AND ( SELECT domain FROM svc_domain
5316 WHERE svc_acct.domsvc = svc_domain.svcnum
5317 ) = '. dbh->quote($domain),
5323 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5325 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
5332 =item check_and_rebuild_fuzzyfiles
5336 use vars qw(@fuzzyfields);
5337 @fuzzyfields = ( 'last', 'first', 'company' );
5339 sub check_and_rebuild_fuzzyfiles {
5340 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5341 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
5344 =item rebuild_fuzzyfiles
5348 sub rebuild_fuzzyfiles {
5350 use Fcntl qw(:flock);
5352 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5353 mkdir $dir, 0700 unless -d $dir;
5355 foreach my $fuzzy ( @fuzzyfields ) {
5357 open(LOCK,">>$dir/cust_main.$fuzzy")
5358 or die "can't open $dir/cust_main.$fuzzy: $!";
5360 or die "can't lock $dir/cust_main.$fuzzy: $!";
5362 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
5363 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
5365 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
5366 my $sth = dbh->prepare("SELECT $field FROM cust_main".
5367 " WHERE $field != '' AND $field IS NOT NULL");
5368 $sth->execute or die $sth->errstr;
5370 while ( my $row = $sth->fetchrow_arrayref ) {
5371 print CACHE $row->[0]. "\n";
5376 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
5378 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
5389 my( $self, $field ) = @_;
5390 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5391 open(CACHE,"<$dir/cust_main.$field")
5392 or die "can't open $dir/cust_main.$field: $!";
5393 my @array = map { chomp; $_; } <CACHE>;
5398 =item append_fuzzyfiles LASTNAME COMPANY
5402 sub append_fuzzyfiles {
5403 #my( $first, $last, $company ) = @_;
5405 &check_and_rebuild_fuzzyfiles;
5407 use Fcntl qw(:flock);
5409 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5411 foreach my $field (qw( first last company )) {
5416 open(CACHE,">>$dir/cust_main.$field")
5417 or die "can't open $dir/cust_main.$field: $!";
5418 flock(CACHE,LOCK_EX)
5419 or die "can't lock $dir/cust_main.$field: $!";
5421 print CACHE "$value\n";
5423 flock(CACHE,LOCK_UN)
5424 or die "can't unlock $dir/cust_main.$field: $!";
5439 #warn join('-',keys %$param);
5440 my $fh = $param->{filehandle};
5441 my $agentnum = $param->{agentnum};
5443 my $refnum = $param->{refnum};
5444 my $pkgpart = $param->{pkgpart};
5446 #my @fields = @{$param->{fields}};
5447 my $format = $param->{'format'};
5450 if ( $format eq 'simple' ) {
5451 @fields = qw( cust_pkg.setup dayphone first last
5452 address1 address2 city state zip comments );
5454 } elsif ( $format eq 'extended' ) {
5455 @fields = qw( agent_custid refnum
5456 last first address1 address2 city state zip country
5458 ship_last ship_first ship_address1 ship_address2
5459 ship_city ship_state ship_zip ship_country
5460 payinfo paycvv paydate
5463 svc_acct.username svc_acct._password
5466 } elsif ( $format eq 'extended-plus_company' ) {
5467 @fields = qw( agent_custid refnum
5468 last first company address1 address2 city state zip country
5470 ship_last ship_first ship_company ship_address1 ship_address2
5471 ship_city ship_state ship_zip ship_country
5472 payinfo paycvv paydate
5475 svc_acct.username svc_acct._password
5479 die "unknown format $format";
5482 eval "use Text::CSV_XS;";
5485 my $csv = new Text::CSV_XS;
5492 local $SIG{HUP} = 'IGNORE';
5493 local $SIG{INT} = 'IGNORE';
5494 local $SIG{QUIT} = 'IGNORE';
5495 local $SIG{TERM} = 'IGNORE';
5496 local $SIG{TSTP} = 'IGNORE';
5497 local $SIG{PIPE} = 'IGNORE';
5499 my $oldAutoCommit = $FS::UID::AutoCommit;
5500 local $FS::UID::AutoCommit = 0;
5503 #while ( $columns = $csv->getline($fh) ) {
5505 while ( defined($line=<$fh>) ) {
5507 $csv->parse($line) or do {
5508 $dbh->rollback if $oldAutoCommit;
5509 return "can't parse: ". $csv->error_input();
5512 my @columns = $csv->fields();
5513 #warn join('-',@columns);
5516 agentnum => $agentnum,
5518 country => $conf->config('countrydefault') || 'US',
5519 payby => $payby, #default
5520 paydate => '12/2037', #default
5522 my $billtime = time;
5523 my %cust_pkg = ( pkgpart => $pkgpart );
5525 foreach my $field ( @fields ) {
5527 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
5529 #$cust_pkg{$1} = str2time( shift @$columns );
5530 if ( $1 eq 'pkgpart' ) {
5531 $cust_pkg{$1} = shift @columns;
5532 } elsif ( $1 eq 'setup' ) {
5533 $billtime = str2time(shift @columns);
5535 $cust_pkg{$1} = str2time( shift @columns );
5538 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
5540 $svc_acct{$1} = shift @columns;
5544 #refnum interception
5545 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
5547 my $referral = $columns[0];
5548 my %hash = ( 'referral' => $referral,
5549 'agentnum' => $agentnum,
5553 my $part_referral = qsearchs('part_referral', \%hash )
5554 || new FS::part_referral \%hash;
5556 unless ( $part_referral->refnum ) {
5557 my $error = $part_referral->insert;
5559 $dbh->rollback if $oldAutoCommit;
5560 return "can't auto-insert advertising source: $referral: $error";
5564 $columns[0] = $part_referral->refnum;
5567 #$cust_main{$field} = shift @$columns;
5568 $cust_main{$field} = shift @columns;
5572 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
5574 my $invoicing_list = $cust_main{'invoicing_list'}
5575 ? [ delete $cust_main{'invoicing_list'} ]
5578 my $cust_main = new FS::cust_main ( \%cust_main );
5581 tie my %hash, 'Tie::RefHash'; #this part is important
5583 if ( $cust_pkg{'pkgpart'} ) {
5584 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
5587 if ( $svc_acct{'username'} ) {
5588 my $part_pkg = $cust_pkg->part_pkg;
5589 unless ( $part_pkg ) {
5590 $dbh->rollback if $oldAutoCommit;
5591 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
5593 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
5594 push @svc_acct, new FS::svc_acct ( \%svc_acct )
5597 $hash{$cust_pkg} = \@svc_acct;
5600 my $error = $cust_main->insert( \%hash, $invoicing_list );
5603 $dbh->rollback if $oldAutoCommit;
5604 return "can't insert customer for $line: $error";
5607 if ( $format eq 'simple' ) {
5609 #false laziness w/bill.cgi
5610 $error = $cust_main->bill( 'time' => $billtime );
5612 $dbh->rollback if $oldAutoCommit;
5613 return "can't bill customer for $line: $error";
5616 $error = $cust_main->apply_payments_and_credits;
5618 $dbh->rollback if $oldAutoCommit;
5619 return "can't bill customer for $line: $error";
5622 $error = $cust_main->collect();
5624 $dbh->rollback if $oldAutoCommit;
5625 return "can't collect customer for $line: $error";
5633 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5635 return "Empty file!" unless $imported;
5647 #warn join('-',keys %$param);
5648 my $fh = $param->{filehandle};
5649 my @fields = @{$param->{fields}};
5651 eval "use Text::CSV_XS;";
5654 my $csv = new Text::CSV_XS;
5661 local $SIG{HUP} = 'IGNORE';
5662 local $SIG{INT} = 'IGNORE';
5663 local $SIG{QUIT} = 'IGNORE';
5664 local $SIG{TERM} = 'IGNORE';
5665 local $SIG{TSTP} = 'IGNORE';
5666 local $SIG{PIPE} = 'IGNORE';
5668 my $oldAutoCommit = $FS::UID::AutoCommit;
5669 local $FS::UID::AutoCommit = 0;
5672 #while ( $columns = $csv->getline($fh) ) {
5674 while ( defined($line=<$fh>) ) {
5676 $csv->parse($line) or do {
5677 $dbh->rollback if $oldAutoCommit;
5678 return "can't parse: ". $csv->error_input();
5681 my @columns = $csv->fields();
5682 #warn join('-',@columns);
5685 foreach my $field ( @fields ) {
5686 $row{$field} = shift @columns;
5689 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
5690 unless ( $cust_main ) {
5691 $dbh->rollback if $oldAutoCommit;
5692 return "unknown custnum $row{'custnum'}";
5695 if ( $row{'amount'} > 0 ) {
5696 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5698 $dbh->rollback if $oldAutoCommit;
5702 } elsif ( $row{'amount'} < 0 ) {
5703 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5706 $dbh->rollback if $oldAutoCommit;
5716 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5718 return "Empty file!" unless $imported;
5724 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5726 Sends a templated email notification to the customer (see L<Text::Template>).
5728 OPTIONS is a hash and may include
5730 I<from> - the email sender (default is invoice_from)
5732 I<to> - comma-separated scalar or arrayref of recipients
5733 (default is invoicing_list)
5735 I<subject> - The subject line of the sent email notification
5736 (default is "Notice from company_name")
5738 I<extra_fields> - a hashref of name/value pairs which will be substituted
5741 The following variables are vavailable in the template.
5743 I<$first> - the customer first name
5744 I<$last> - the customer last name
5745 I<$company> - the customer company
5746 I<$payby> - a description of the method of payment for the customer
5747 # would be nice to use FS::payby::shortname
5748 I<$payinfo> - the account information used to collect for this customer
5749 I<$expdate> - the expiration of the customer payment in seconds from epoch
5754 my ($customer, $template, %options) = @_;
5756 return unless $conf->exists($template);
5758 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
5759 $from = $options{from} if exists($options{from});
5761 my $to = join(',', $customer->invoicing_list_emailonly);
5762 $to = $options{to} if exists($options{to});
5764 my $subject = "Notice from " . $conf->config('company_name')
5765 if $conf->exists('company_name');
5766 $subject = $options{subject} if exists($options{subject});
5768 my $notify_template = new Text::Template (TYPE => 'ARRAY',
5769 SOURCE => [ map "$_\n",
5770 $conf->config($template)]
5772 or die "can't create new Text::Template object: Text::Template::ERROR";
5773 $notify_template->compile()
5774 or die "can't compile template: Text::Template::ERROR";
5776 my $paydate = $customer->paydate || '2037-12-31';
5777 $FS::notify_template::_template::first = $customer->first;
5778 $FS::notify_template::_template::last = $customer->last;
5779 $FS::notify_template::_template::company = $customer->company;
5780 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
5781 my $payby = $customer->payby;
5782 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5783 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5785 #credit cards expire at the end of the month/year of their exp date
5786 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5787 $FS::notify_template::_template::payby = 'credit card';
5788 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5789 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5791 }elsif ($payby eq 'COMP') {
5792 $FS::notify_template::_template::payby = 'complimentary account';
5794 $FS::notify_template::_template::payby = 'current method';
5796 $FS::notify_template::_template::expdate = $expire_time;
5798 for (keys %{$options{extra_fields}}){
5800 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5803 send_email(from => $from,
5805 subject => $subject,
5806 body => $notify_template->fill_in( PACKAGE =>
5807 'FS::notify_template::_template' ),
5812 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5814 Generates a templated notification to the customer (see L<Text::Template>).
5816 OPTIONS is a hash and may include
5818 I<extra_fields> - a hashref of name/value pairs which will be substituted
5819 into the template. These values may override values mentioned below
5820 and those from the customer record.
5822 The following variables are available in the template instead of or in addition
5823 to the fields of the customer record.
5825 I<$payby> - a description of the method of payment for the customer
5826 # would be nice to use FS::payby::shortname
5827 I<$payinfo> - the masked account information used to collect for this customer
5828 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5829 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress
5833 sub generate_letter {
5834 my ($self, $template, %options) = @_;
5836 return unless $conf->exists($template);
5838 my $letter_template = new Text::Template
5840 SOURCE => [ map "$_\n", $conf->config($template)],
5841 DELIMITERS => [ '[@--', '--@]' ],
5843 or die "can't create new Text::Template object: Text::Template::ERROR";
5845 $letter_template->compile()
5846 or die "can't compile template: Text::Template::ERROR";
5848 my %letter_data = map { $_ => $self->$_ } $self->fields;
5849 $letter_data{payinfo} = $self->mask_payinfo;
5851 my $paydate = $self->paydate || '2037-12-31';
5852 my $payby = $self->payby;
5853 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5854 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5856 #credit cards expire at the end of the month/year of their exp date
5857 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5858 $letter_data{payby} = 'credit card';
5859 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5860 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5862 }elsif ($payby eq 'COMP') {
5863 $letter_data{payby} = 'complimentary account';
5865 $letter_data{payby} = 'current method';
5867 $letter_data{expdate} = $expire_time;
5869 for (keys %{$options{extra_fields}}){
5870 $letter_data{$_} = $options{extra_fields}->{$_};
5873 unless(exists($letter_data{returnaddress})){
5874 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5875 $self->_agent_template)
5878 $letter_data{returnaddress} = length($retadd) ? $retadd : '~';
5881 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5883 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
5884 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5888 ) or die "can't open temp file: $!\n";
5890 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5892 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5896 =item print_ps TEMPLATE
5898 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5904 my $file = $self->generate_letter(@_);
5905 FS::Misc::generate_ps($file);
5908 =item print TEMPLATE
5910 Prints the filled in template.
5912 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5916 sub queueable_print {
5919 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5920 or die "invalid customer number: " . $opt{custvnum};
5922 my $error = $self->print( $opt{template} );
5923 die $error if $error;
5927 my ($self, $template) = (shift, shift);
5928 do_print [ $self->print_ps($template) ];
5931 sub agent_template {
5933 $self->_agent_plandata('agent_templatename');
5936 sub agent_invoice_from {
5938 $self->_agent_plandata('agent_invoice_from');
5941 sub _agent_plandata {
5942 my( $self, $option ) = @_;
5945 if ( driver_name =~ /^Pg/i ) {
5947 } elsif ( driver_name =~ /^mysql/i ) {
5950 die "don't know how to use regular expressions in ". driver_name. " databases";
5953 my $part_bill_event = qsearchs( 'part_bill_event',
5955 'payby' => $self->payby,
5956 'plan' => 'send_agent',
5957 'plandata' => { 'op' => $regexp,
5958 'value' => "(^|\n)agentnum ".
5966 'ORDER BY seconds LIMIT 1'
5969 return '' unless $part_bill_event;
5971 if ( $part_bill_event->plandata =~ /^$option (.*)$/m ) {
5974 warn "can't parse part_bill_event eventpart#". $part_bill_event->eventpart.
5975 " plandata for $option";
5987 The delete method should possibly take an FS::cust_main object reference
5988 instead of a scalar customer number.
5990 Bill and collect options should probably be passed as references instead of a
5993 There should probably be a configuration file with a list of allowed credit
5996 No multiple currency support (probably a larger project than just this module).
5998 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6000 Birthdates rely on negative epoch values.
6002 The payby for card/check batches is broken. With mixed batching, bad
6007 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6008 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6009 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.