4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5 $import $skip_fuzzyfiles $ignore_expired_card );
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;
24 use FS::UID qw( getotaker dbh );
25 use FS::Record qw( qsearchs qsearch dbdef );
26 use FS::Misc qw( send_email );
27 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
33 use FS::cust_pay_void;
36 use FS::part_referral;
37 use FS::cust_main_county;
39 use FS::cust_main_invoice;
40 use FS::cust_credit_bill;
41 use FS::cust_bill_pay;
42 use FS::prepay_credit;
45 use FS::part_bill_event qw(due_events);
46 use FS::cust_bill_event;
47 use FS::cust_tax_exempt;
48 use FS::cust_tax_exempt_pkg;
50 use FS::payment_gateway;
51 use FS::agent_payment_gateway;
54 @ISA = qw( FS::Record );
56 @EXPORT_OK = qw( smart_search );
58 $realtime_bop_decline_quiet = 0;
60 # 1 is mostly method/subroutine entry and options
61 # 2 traces progress of some operations
62 # 3 is even more information including possibly sensitive data
64 $me = '[FS::cust_main]';
68 $ignore_expired_card = 0;
70 @encrypted_fields = ('payinfo', 'paycvv');
72 #ask FS::UID to run this stuff for us later
73 #$FS::UID::callback{'FS::cust_main'} = sub {
74 install_callback FS::UID sub {
76 #yes, need it for stuff below (prolly should be cached)
81 my ( $hashref, $cache ) = @_;
82 if ( exists $hashref->{'pkgnum'} ) {
83 #@{ $self->{'_pkgnum'} } = ();
84 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
85 $self->{'_pkgnum'} = $subcache;
86 #push @{ $self->{'_pkgnum'} },
87 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
93 FS::cust_main - Object methods for cust_main records
99 $record = new FS::cust_main \%hash;
100 $record = new FS::cust_main { 'column' => 'value' };
102 $error = $record->insert;
104 $error = $new_record->replace($old_record);
106 $error = $record->delete;
108 $error = $record->check;
110 @cust_pkg = $record->all_pkgs;
112 @cust_pkg = $record->ncancelled_pkgs;
114 @cust_pkg = $record->suspended_pkgs;
116 $error = $record->bill;
117 $error = $record->bill %options;
118 $error = $record->bill 'time' => $time;
120 $error = $record->collect;
121 $error = $record->collect %options;
122 $error = $record->collect 'invoice_time' => $time,
127 An FS::cust_main object represents a customer. FS::cust_main inherits from
128 FS::Record. The following fields are currently supported:
132 =item custnum - primary key (assigned automatically for new customers)
134 =item agentnum - agent (see L<FS::agent>)
136 =item refnum - Advertising source (see L<FS::part_referral>)
142 =item ss - social security number (optional)
144 =item company - (optional)
148 =item address2 - (optional)
152 =item county - (optional, see L<FS::cust_main_county>)
154 =item state - (see L<FS::cust_main_county>)
158 =item country - (see L<FS::cust_main_county>)
160 =item daytime - phone (optional)
162 =item night - phone (optional)
164 =item fax - phone (optional)
166 =item ship_first - name
168 =item ship_last - name
170 =item ship_company - (optional)
174 =item ship_address2 - (optional)
178 =item ship_county - (optional, see L<FS::cust_main_county>)
180 =item ship_state - (see L<FS::cust_main_county>)
184 =item ship_country - (see L<FS::cust_main_county>)
186 =item ship_daytime - phone (optional)
188 =item ship_night - phone (optional)
190 =item ship_fax - phone (optional)
194 I<CARD> (credit card - automatic), I<DCRD> (credit card - on-demand), I<CHEK> (electronic check - automatic), I<DCHK> (electronic check - on-demand), I<LECB> (Phone bill billing), I<BILL> (billing), I<COMP> (free), or I<PREPAY> (special billing type: applies a credit - see L<FS::prepay_credit> and sets billing type to I<BILL>)
198 Card Number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
203 my($self,$payinfo) = @_;
204 if ( defined($payinfo) ) {
205 $self->paymask($payinfo);
206 $self->setfield('payinfo', $payinfo); # This is okay since we are the 'setter'
208 $payinfo = $self->getfield('payinfo'); # This is okay since we are the 'getter'
216 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
220 =item paymask - Masked payment type
226 Mask all but the last four characters.
230 Mask all but last 2 of account number and bank routing number.
234 Do nothing, return the unmasked string.
243 # If it doesn't exist then generate it
244 my $paymask=$self->getfield('paymask');
245 if (!defined($value) && (!defined($paymask) || $paymask eq '')) {
246 $value = $self->payinfo;
249 if ( defined($value) && !$self->is_encrypted($value)) {
250 my $payinfo = $value;
251 my $payby = $self->payby;
252 if ($payby eq 'CARD' || $payby eq 'DCRD') { # Credit Cards (Show last four)
253 $paymask = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
254 } elsif ($payby eq 'CHEK' ||
255 $payby eq 'DCHK' ) { # Checks (Show last 2 @ bank)
256 my( $account, $aba ) = split('@', $payinfo );
257 $paymask = 'x'x(length($account)-2). substr($account,(length($account)-2))."@".$aba;
258 } else { # Tie up loose ends
261 $self->setfield('paymask', $paymask); # This is okay since we are the 'setter'
262 } elsif (defined($value) && $self->is_encrypted($value)) {
268 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
270 =item paystart_month - start date month (maestro/solo cards only)
272 =item paystart_year - start date year (maestro/solo cards only)
274 =item payissue - issue number (maestro/solo cards only)
276 =item payname - name on card or billing name
278 =item payip - IP address from which payment information was received
280 =item tax - tax exempt, empty or `Y'
282 =item otaker - order taker (assigned automatically, see L<FS::UID>)
284 =item comments - comments (optional)
286 =item referral_custnum - referring customer number
288 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
298 Creates a new customer. To add the customer to the database, see L<"insert">.
300 Note that this stores the hash reference, not a distinct copy of the hash it
301 points to. You can ask the object for a copy with the I<hash> method.
305 sub table { 'cust_main'; }
307 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
309 Adds this customer to the database. If there is an error, returns the error,
310 otherwise returns false.
312 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
313 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
314 are inserted atomicly, or the transaction is rolled back. Passing an empty
315 hash reference is equivalent to not supplying this parameter. There should be
316 a better explanation of this, but until then, here's an example:
319 tie %hash, 'Tie::RefHash'; #this part is important
321 $cust_pkg => [ $svc_acct ],
324 $cust_main->insert( \%hash );
326 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
327 be set as the invoicing list (see L<"invoicing_list">). Errors return as
328 expected and rollback the entire transaction; it is not necessary to call
329 check_invoicing_list first. The invoicing_list is set after the records in the
330 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
331 invoicing_list destination to the newly-created svc_acct. Here's an example:
333 $cust_main->insert( {}, [ $email, 'POST' ] );
335 Currently available options are: I<depend_jobnum> and I<noexport>.
337 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
338 on the supplied jobnum (they will not run until the specific job completes).
339 This can be used to defer provisioning until some action completes (such
340 as running the customer's credit card successfully).
342 The I<noexport> option is deprecated. If I<noexport> is set true, no
343 provisioning jobs (exports) are scheduled. (You can schedule them later with
344 the B<reexport> method.)
350 my $cust_pkgs = @_ ? shift : {};
351 my $invoicing_list = @_ ? shift : '';
353 warn "$me insert called with options ".
354 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
357 local $SIG{HUP} = 'IGNORE';
358 local $SIG{INT} = 'IGNORE';
359 local $SIG{QUIT} = 'IGNORE';
360 local $SIG{TERM} = 'IGNORE';
361 local $SIG{TSTP} = 'IGNORE';
362 local $SIG{PIPE} = 'IGNORE';
364 my $oldAutoCommit = $FS::UID::AutoCommit;
365 local $FS::UID::AutoCommit = 0;
368 my $prepay_identifier = '';
369 my( $amount, $seconds ) = ( 0, 0 );
371 if ( $self->payby eq 'PREPAY' ) {
373 $self->payby('BILL');
374 $prepay_identifier = $self->payinfo;
377 warn " looking up prepaid card $prepay_identifier\n"
380 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
382 $dbh->rollback if $oldAutoCommit;
383 #return "error applying prepaid card (transaction rolled back): $error";
387 $payby = 'PREP' if $amount;
389 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
392 $self->payby('BILL');
393 $amount = $self->paid;
397 warn " inserting $self\n"
400 $self->signupdate(time) unless $self->signupdate;
402 my $error = $self->SUPER::insert;
404 $dbh->rollback if $oldAutoCommit;
405 #return "inserting cust_main record (transaction rolled back): $error";
409 warn " setting invoicing list\n"
412 if ( $invoicing_list ) {
413 $error = $self->check_invoicing_list( $invoicing_list );
415 $dbh->rollback if $oldAutoCommit;
416 return "checking invoicing_list (transaction rolled back): $error";
418 $self->invoicing_list( $invoicing_list );
421 if ( $conf->config('cust_main-skeleton_tables')
422 && $conf->config('cust_main-skeleton_custnum') ) {
424 warn " inserting skeleton records\n"
427 my $error = $self->start_copy_skel;
429 $dbh->rollback if $oldAutoCommit;
435 warn " ordering packages\n"
438 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
440 $dbh->rollback if $oldAutoCommit;
445 $dbh->rollback if $oldAutoCommit;
446 return "No svc_acct record to apply pre-paid time";
450 warn " inserting initial $payby payment of $amount\n"
452 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
454 $dbh->rollback if $oldAutoCommit;
455 return "inserting payment (transaction rolled back): $error";
459 unless ( $import || $skip_fuzzyfiles ) {
460 warn " queueing fuzzyfiles update\n"
462 $error = $self->queue_fuzzyfiles_update;
464 $dbh->rollback if $oldAutoCommit;
465 return "updating fuzzy search cache: $error";
469 warn " insert complete; committing transaction\n"
472 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
477 sub start_copy_skel {
480 #'mg_user_preference' => {},
481 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
482 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
483 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
484 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
485 my @tables = eval($conf->config_binary('cust_main-skeleton_tables'));
488 _copy_skel( 'cust_main', #tablename
489 $conf->config('cust_main-skeleton_custnum'), #sourceid
490 $self->custnum, #destid
491 @tables, #child tables
495 #recursive subroutine, not a method
497 my( $table, $sourceid, $destid, %child_tables ) = @_;
500 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
501 ( $table, $primary_key ) = ( $1, $2 );
503 my $dbdef_table = dbdef->table($table);
504 $primary_key = $dbdef_table->primary_key
505 or return "$table has no primary key".
506 " (or do you need to run dbdef-create?)";
509 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
510 join (', ', keys %child_tables). "\n"
513 foreach my $child_table_def ( keys %child_tables ) {
517 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
518 ( $child_table, $child_pkey ) = ( $1, $2 );
520 $child_table = $child_table_def;
522 $child_pkey = dbdef->table($child_table)->primary_key;
523 # or return "$table has no primary key".
524 # " (or do you need to run dbdef-create?)\n";
528 if ( keys %{ $child_tables{$child_table_def} } ) {
530 return "$child_table has no primary key".
531 " (run dbdef-create or try specifying it?)\n"
534 #false laziness w/Record::insert and only works on Pg
535 #refactor the proper last-inserted-id stuff out of Record::insert if this
536 # ever gets use for anything besides a quick kludge for one customer
537 my $default = dbdef->table($child_table)->column($child_pkey)->default;
538 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
539 or return "can't parse $child_table.$child_pkey default value ".
540 " for sequence name: $default";
545 my @sel_columns = grep { $_ ne $primary_key }
546 dbdef->table($child_table)->columns;
547 my $sel_columns = join(', ', @sel_columns );
549 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
550 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
551 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
553 my $sel_st = "SELECT $sel_columns FROM $child_table".
554 " WHERE $primary_key = $sourceid";
557 my $sel_sth = dbh->prepare( $sel_st )
558 or return dbh->errstr;
560 $sel_sth->execute or return $sel_sth->errstr;
562 while ( my $row = $sel_sth->fetchrow_hashref ) {
564 warn " selected row: ".
565 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
569 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
570 my $ins_sth =dbh->prepare($statement)
571 or return dbh->errstr;
572 my @param = ( $destid, map $row->{$_}, @ins_columns );
573 warn " $statement: [ ". join(', ', @param). " ]\n"
575 $ins_sth->execute( @param )
576 or return $ins_sth->errstr;
578 #next unless keys %{ $child_tables{$child_table} };
579 next unless $sequence;
581 #another section of that laziness
582 my $seq_sql = "SELECT currval('$sequence')";
583 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
584 $seq_sth->execute or return $seq_sth->errstr;
585 my $insertid = $seq_sth->fetchrow_arrayref->[0];
587 # don't drink soap! recurse! recurse! okay!
589 _copy_skel( $child_table_def,
590 $row->{$child_pkey}, #sourceid
592 %{ $child_tables{$child_table_def} },
594 return $error if $error;
604 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
606 Like the insert method on an existing record, this method orders a package
607 and included services atomicaly. Pass a Tie::RefHash data structure to this
608 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
609 be a better explanation of this, but until then, here's an example:
612 tie %hash, 'Tie::RefHash'; #this part is important
614 $cust_pkg => [ $svc_acct ],
617 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
619 Services can be new, in which case they are inserted, or existing unaudited
620 services, in which case they are linked to the newly-created package.
622 Currently available options are: I<depend_jobnum> and I<noexport>.
624 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
625 on the supplied jobnum (they will not run until the specific job completes).
626 This can be used to defer provisioning until some action completes (such
627 as running the customer's credit card successfully).
629 The I<noexport> option is deprecated. If I<noexport> is set true, no
630 provisioning jobs (exports) are scheduled. (You can schedule them later with
631 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
632 on the cust_main object is not recommended, as existing services will also be
639 my $cust_pkgs = shift;
642 my %svc_options = ();
643 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
644 if exists $options{'depend_jobnum'};
645 warn "$me order_pkgs called with options ".
646 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
649 local $SIG{HUP} = 'IGNORE';
650 local $SIG{INT} = 'IGNORE';
651 local $SIG{QUIT} = 'IGNORE';
652 local $SIG{TERM} = 'IGNORE';
653 local $SIG{TSTP} = 'IGNORE';
654 local $SIG{PIPE} = 'IGNORE';
656 my $oldAutoCommit = $FS::UID::AutoCommit;
657 local $FS::UID::AutoCommit = 0;
660 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
662 foreach my $cust_pkg ( keys %$cust_pkgs ) {
663 $cust_pkg->custnum( $self->custnum );
664 my $error = $cust_pkg->insert;
666 $dbh->rollback if $oldAutoCommit;
667 return "inserting cust_pkg (transaction rolled back): $error";
669 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
670 if ( $svc_something->svcnum ) {
671 my $old_cust_svc = $svc_something->cust_svc;
672 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
673 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
674 $error = $new_cust_svc->replace($old_cust_svc);
676 $svc_something->pkgnum( $cust_pkg->pkgnum );
677 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
678 $svc_something->seconds( $svc_something->seconds + $$seconds );
681 $error = $svc_something->insert(%svc_options);
684 $dbh->rollback if $oldAutoCommit;
685 #return "inserting svc_ (transaction rolled back): $error";
691 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
695 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
697 Recharges this (existing) customer with the specified prepaid card (see
698 L<FS::prepay_credit>), specified either by I<identifier> or as an
699 FS::prepay_credit object. If there is an error, returns the error, otherwise
702 Optionally, four scalar references can be passed as well. They will have their
703 values filled in with the amount, number of seconds, and number of upload and
704 download bytes applied by this prepaid
709 sub recharge_prepay {
710 my( $self, $prepay_credit, $amountref, $secondsref,
711 $upbytesref, $downbytesref, $totalbytesref ) = @_;
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 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
726 my $error = $self->get_prepay($prepay_credit, \$amount,
727 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
728 || $self->increment_seconds($seconds)
729 || $self->increment_upbytes($upbytes)
730 || $self->increment_downbytes($downbytes)
731 || $self->increment_totalbytes($totalbytes)
732 || $self->insert_cust_pay_prepay( $amount,
734 ? $prepay_credit->identifier
739 $dbh->rollback if $oldAutoCommit;
743 if ( defined($amountref) ) { $$amountref = $amount; }
744 if ( defined($secondsref) ) { $$secondsref = $seconds; }
745 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
746 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
747 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
749 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
754 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
756 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
757 specified either by I<identifier> or as an FS::prepay_credit object.
759 References to I<amount> and I<seconds> scalars should be passed as arguments
760 and will be incremented by the values of the prepaid card.
762 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
763 check or set this customer's I<agentnum>.
765 If there is an error, returns the error, otherwise returns false.
771 my( $self, $prepay_credit, $amountref, $secondsref,
772 $upref, $downref, $totalref) = @_;
774 local $SIG{HUP} = 'IGNORE';
775 local $SIG{INT} = 'IGNORE';
776 local $SIG{QUIT} = 'IGNORE';
777 local $SIG{TERM} = 'IGNORE';
778 local $SIG{TSTP} = 'IGNORE';
779 local $SIG{PIPE} = 'IGNORE';
781 my $oldAutoCommit = $FS::UID::AutoCommit;
782 local $FS::UID::AutoCommit = 0;
785 unless ( ref($prepay_credit) ) {
787 my $identifier = $prepay_credit;
789 $prepay_credit = qsearchs(
791 { 'identifier' => $prepay_credit },
796 unless ( $prepay_credit ) {
797 $dbh->rollback if $oldAutoCommit;
798 return "Invalid prepaid card: ". $identifier;
803 if ( $prepay_credit->agentnum ) {
804 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
805 $dbh->rollback if $oldAutoCommit;
806 return "prepaid card not valid for agent ". $self->agentnum;
808 $self->agentnum($prepay_credit->agentnum);
811 my $error = $prepay_credit->delete;
813 $dbh->rollback if $oldAutoCommit;
814 return "removing prepay_credit (transaction rolled back): $error";
817 $$amountref += $prepay_credit->amount;
818 $$secondsref += $prepay_credit->seconds;
819 $$upref += $prepay_credit->upbytes;
820 $$downref += $prepay_credit->downbytes;
821 $$totalref += $prepay_credit->totalbytes;
823 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
828 =item increment_upbytes SECONDS
830 Updates this customer's single or primary account (see L<FS::svc_acct>) by
831 the specified number of upbytes. If there is an error, returns the error,
832 otherwise returns false.
836 sub increment_upbytes {
837 _increment_column( shift, 'upbytes', @_);
840 =item increment_downbytes SECONDS
842 Updates this customer's single or primary account (see L<FS::svc_acct>) by
843 the specified number of downbytes. If there is an error, returns the error,
844 otherwise returns false.
848 sub increment_downbytes {
849 _increment_column( shift, 'downbytes', @_);
852 =item increment_totalbytes SECONDS
854 Updates this customer's single or primary account (see L<FS::svc_acct>) by
855 the specified number of totalbytes. If there is an error, returns the error,
856 otherwise returns false.
860 sub increment_totalbytes {
861 _increment_column( shift, 'totalbytes', @_);
864 =item increment_seconds SECONDS
866 Updates this customer's single or primary account (see L<FS::svc_acct>) by
867 the specified number of seconds. If there is an error, returns the error,
868 otherwise returns false.
872 sub increment_seconds {
873 _increment_column( shift, 'seconds', @_);
876 =item _increment_column AMOUNT
878 Updates this customer's single or primary account (see L<FS::svc_acct>) by
879 the specified number of seconds or bytes. If there is an error, returns
880 the error, otherwise returns false.
884 sub _increment_column {
885 my( $self, $column, $amount ) = @_;
886 warn "$me increment_column called: $column, $amount\n"
889 return '' unless $amount;
891 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
892 $self->ncancelled_pkgs;
895 return 'No packages with primary or single services found'.
896 ' to apply pre-paid time';
897 } elsif ( scalar(@cust_pkg) > 1 ) {
898 #maybe have a way to specify the package/account?
899 return 'Multiple packages found to apply pre-paid time';
902 my $cust_pkg = $cust_pkg[0];
903 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
907 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
910 return 'No account found to apply pre-paid time';
911 } elsif ( scalar(@cust_svc) > 1 ) {
912 return 'Multiple accounts found to apply pre-paid time';
915 my $svc_acct = $cust_svc[0]->svc_x;
916 warn " found service svcnum ". $svc_acct->pkgnum.
917 ' ('. $svc_acct->email. ")\n"
920 $column = "increment_$column";
921 $svc_acct->$column($amount);
925 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
927 Inserts a prepayment in the specified amount for this customer. An optional
928 second argument can specify the prepayment identifier for tracking purposes.
929 If there is an error, returns the error, otherwise returns false.
933 sub insert_cust_pay_prepay {
934 shift->insert_cust_pay('PREP', @_);
937 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
939 Inserts a cash payment in the specified amount for this customer. An optional
940 second argument can specify the payment identifier for tracking purposes.
941 If there is an error, returns the error, otherwise returns false.
945 sub insert_cust_pay_cash {
946 shift->insert_cust_pay('CASH', @_);
949 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
951 Inserts a Western Union payment in the specified amount for this customer. An
952 optional second argument can specify the prepayment identifier for tracking
953 purposes. If there is an error, returns the error, otherwise returns false.
957 sub insert_cust_pay_west {
958 shift->insert_cust_pay('WEST', @_);
961 sub insert_cust_pay {
962 my( $self, $payby, $amount ) = splice(@_, 0, 3);
963 my $payinfo = scalar(@_) ? shift : '';
965 my $cust_pay = new FS::cust_pay {
966 'custnum' => $self->custnum,
967 'paid' => sprintf('%.2f', $amount),
968 #'_date' => #date the prepaid card was purchased???
970 'payinfo' => $payinfo,
978 This method is deprecated. See the I<depend_jobnum> option to the insert and
979 order_pkgs methods for a better way to defer provisioning.
981 Re-schedules all exports by calling the B<reexport> method of all associated
982 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
983 otherwise returns false.
990 carp "WARNING: FS::cust_main::reexport is deprectated; ".
991 "use the depend_jobnum option to insert or order_pkgs to delay export";
993 local $SIG{HUP} = 'IGNORE';
994 local $SIG{INT} = 'IGNORE';
995 local $SIG{QUIT} = 'IGNORE';
996 local $SIG{TERM} = 'IGNORE';
997 local $SIG{TSTP} = 'IGNORE';
998 local $SIG{PIPE} = 'IGNORE';
1000 my $oldAutoCommit = $FS::UID::AutoCommit;
1001 local $FS::UID::AutoCommit = 0;
1004 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1005 my $error = $cust_pkg->reexport;
1007 $dbh->rollback if $oldAutoCommit;
1012 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1017 =item delete NEW_CUSTNUM
1019 This deletes the customer. If there is an error, returns the error, otherwise
1022 This will completely remove all traces of the customer record. This is not
1023 what you want when a customer cancels service; for that, cancel all of the
1024 customer's packages (see L</cancel>).
1026 If the customer has any uncancelled packages, you need to pass a new (valid)
1027 customer number for those packages to be transferred to. Cancelled packages
1028 will be deleted. Did I mention that this is NOT what you want when a customer
1029 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1031 You can't delete a customer with invoices (see L<FS::cust_bill>),
1032 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1033 refunds (see L<FS::cust_refund>).
1040 local $SIG{HUP} = 'IGNORE';
1041 local $SIG{INT} = 'IGNORE';
1042 local $SIG{QUIT} = 'IGNORE';
1043 local $SIG{TERM} = 'IGNORE';
1044 local $SIG{TSTP} = 'IGNORE';
1045 local $SIG{PIPE} = 'IGNORE';
1047 my $oldAutoCommit = $FS::UID::AutoCommit;
1048 local $FS::UID::AutoCommit = 0;
1051 if ( $self->cust_bill ) {
1052 $dbh->rollback if $oldAutoCommit;
1053 return "Can't delete a customer with invoices";
1055 if ( $self->cust_credit ) {
1056 $dbh->rollback if $oldAutoCommit;
1057 return "Can't delete a customer with credits";
1059 if ( $self->cust_pay ) {
1060 $dbh->rollback if $oldAutoCommit;
1061 return "Can't delete a customer with payments";
1063 if ( $self->cust_refund ) {
1064 $dbh->rollback if $oldAutoCommit;
1065 return "Can't delete a customer with refunds";
1068 my @cust_pkg = $self->ncancelled_pkgs;
1070 my $new_custnum = shift;
1071 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1072 $dbh->rollback if $oldAutoCommit;
1073 return "Invalid new customer number: $new_custnum";
1075 foreach my $cust_pkg ( @cust_pkg ) {
1076 my %hash = $cust_pkg->hash;
1077 $hash{'custnum'} = $new_custnum;
1078 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1079 my $error = $new_cust_pkg->replace($cust_pkg);
1081 $dbh->rollback if $oldAutoCommit;
1086 my @cancelled_cust_pkg = $self->all_pkgs;
1087 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1088 my $error = $cust_pkg->delete;
1090 $dbh->rollback if $oldAutoCommit;
1095 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1096 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1098 my $error = $cust_main_invoice->delete;
1100 $dbh->rollback if $oldAutoCommit;
1105 my $error = $self->SUPER::delete;
1107 $dbh->rollback if $oldAutoCommit;
1111 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1116 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1118 Replaces the OLD_RECORD with this one in the database. If there is an error,
1119 returns the error, otherwise returns false.
1121 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1122 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1123 expected and rollback the entire transaction; it is not necessary to call
1124 check_invoicing_list first. Here's an example:
1126 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1134 warn "$me replace called\n"
1137 local $SIG{HUP} = 'IGNORE';
1138 local $SIG{INT} = 'IGNORE';
1139 local $SIG{QUIT} = 'IGNORE';
1140 local $SIG{TERM} = 'IGNORE';
1141 local $SIG{TSTP} = 'IGNORE';
1142 local $SIG{PIPE} = 'IGNORE';
1144 # If the mask is blank then try to set it - if we can...
1145 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
1146 $self->paymask($self->payinfo);
1149 # We absolutely have to have an old vs. new record to make this work.
1150 if (!defined($old)) {
1151 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1154 my $curuser = $FS::CurrentUser::CurrentUser;
1155 if ( $self->payby eq 'COMP'
1156 && $self->payby ne $old->payby
1157 && ! $curuser->access_right('Complimentary customer')
1160 return "You are not permitted to create complimentary accounts.";
1163 local($ignore_expired_card) = 1
1164 if $old->payby =~ /^(CARD|DCRD)$/
1165 && $self->payby =~ /^(CARD|DCRD)$/
1166 && $old->payinfo eq $self->payinfo;
1168 my $oldAutoCommit = $FS::UID::AutoCommit;
1169 local $FS::UID::AutoCommit = 0;
1172 my $error = $self->SUPER::replace($old);
1175 $dbh->rollback if $oldAutoCommit;
1179 if ( @param ) { # INVOICING_LIST_ARYREF
1180 my $invoicing_list = shift @param;
1181 $error = $self->check_invoicing_list( $invoicing_list );
1183 $dbh->rollback if $oldAutoCommit;
1186 $self->invoicing_list( $invoicing_list );
1189 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1190 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1191 # card/check/lec info has changed, want to retry realtime_ invoice events
1192 my $error = $self->retry_realtime;
1194 $dbh->rollback if $oldAutoCommit;
1199 unless ( $import || $skip_fuzzyfiles ) {
1200 $error = $self->queue_fuzzyfiles_update;
1202 $dbh->rollback if $oldAutoCommit;
1203 return "updating fuzzy search cache: $error";
1207 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1212 =item queue_fuzzyfiles_update
1214 Used by insert & replace to update the fuzzy search cache
1218 sub queue_fuzzyfiles_update {
1221 local $SIG{HUP} = 'IGNORE';
1222 local $SIG{INT} = 'IGNORE';
1223 local $SIG{QUIT} = 'IGNORE';
1224 local $SIG{TERM} = 'IGNORE';
1225 local $SIG{TSTP} = 'IGNORE';
1226 local $SIG{PIPE} = 'IGNORE';
1228 my $oldAutoCommit = $FS::UID::AutoCommit;
1229 local $FS::UID::AutoCommit = 0;
1232 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1233 my $error = $queue->insert( map $self->getfield($_),
1234 qw(first last company)
1237 $dbh->rollback if $oldAutoCommit;
1238 return "queueing job (transaction rolled back): $error";
1241 if ( $self->ship_last ) {
1242 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1243 $error = $queue->insert( map $self->getfield("ship_$_"),
1244 qw(first last company)
1247 $dbh->rollback if $oldAutoCommit;
1248 return "queueing job (transaction rolled back): $error";
1252 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1259 Checks all fields to make sure this is a valid customer record. If there is
1260 an error, returns the error, otherwise returns false. Called by the insert
1261 and replace methods.
1268 warn "$me check BEFORE: \n". $self->_dump
1272 $self->ut_numbern('custnum')
1273 || $self->ut_number('agentnum')
1274 || $self->ut_textn('agent_custid')
1275 || $self->ut_number('refnum')
1276 || $self->ut_name('last')
1277 || $self->ut_name('first')
1278 || $self->ut_snumbern('birthdate')
1279 || $self->ut_snumbern('signupdate')
1280 || $self->ut_textn('company')
1281 || $self->ut_text('address1')
1282 || $self->ut_textn('address2')
1283 || $self->ut_text('city')
1284 || $self->ut_textn('county')
1285 || $self->ut_textn('state')
1286 || $self->ut_country('country')
1287 || $self->ut_anything('comments')
1288 || $self->ut_numbern('referral_custnum')
1290 #barf. need message catalogs. i18n. etc.
1291 $error .= "Please select an advertising source."
1292 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1293 return $error if $error;
1295 return "Unknown agent"
1296 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1298 return "Unknown refnum"
1299 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1301 return "Unknown referring custnum: ". $self->referral_custnum
1302 unless ! $self->referral_custnum
1303 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1305 if ( $self->ss eq '' ) {
1310 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1311 or return "Illegal social security number: ". $self->ss;
1312 $self->ss("$1-$2-$3");
1316 # bad idea to disable, causes billing to fail because of no tax rates later
1317 # unless ( $import ) {
1318 unless ( qsearch('cust_main_county', {
1319 'country' => $self->country,
1322 return "Unknown state/county/country: ".
1323 $self->state. "/". $self->county. "/". $self->country
1324 unless qsearch('cust_main_county',{
1325 'state' => $self->state,
1326 'county' => $self->county,
1327 'country' => $self->country,
1333 $self->ut_phonen('daytime', $self->country)
1334 || $self->ut_phonen('night', $self->country)
1335 || $self->ut_phonen('fax', $self->country)
1336 || $self->ut_zip('zip', $self->country)
1338 return $error if $error;
1341 last first company address1 address2 city county state zip
1342 country daytime night fax
1345 if ( defined $self->dbdef_table->column('ship_last') ) {
1346 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1348 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1352 $self->ut_name('ship_last')
1353 || $self->ut_name('ship_first')
1354 || $self->ut_textn('ship_company')
1355 || $self->ut_text('ship_address1')
1356 || $self->ut_textn('ship_address2')
1357 || $self->ut_text('ship_city')
1358 || $self->ut_textn('ship_county')
1359 || $self->ut_textn('ship_state')
1360 || $self->ut_country('ship_country')
1362 return $error if $error;
1364 #false laziness with above
1365 unless ( qsearchs('cust_main_county', {
1366 'country' => $self->ship_country,
1369 return "Unknown ship_state/ship_county/ship_country: ".
1370 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1371 unless qsearch('cust_main_county',{
1372 'state' => $self->ship_state,
1373 'county' => $self->ship_county,
1374 'country' => $self->ship_country,
1380 $self->ut_phonen('ship_daytime', $self->ship_country)
1381 || $self->ut_phonen('ship_night', $self->ship_country)
1382 || $self->ut_phonen('ship_fax', $self->ship_country)
1383 || $self->ut_zip('ship_zip', $self->ship_country)
1385 return $error if $error;
1387 } else { # ship_ info eq billing info, so don't store dup info in database
1388 $self->setfield("ship_$_", '')
1389 foreach qw( last first company address1 address2 city county state zip
1390 country daytime night fax );
1394 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1395 or return "Illegal payby: ". $self->payby;
1397 $error = $self->ut_numbern('paystart_month')
1398 || $self->ut_numbern('paystart_year')
1399 || $self->ut_numbern('payissue')
1401 return $error if $error;
1403 if ( $self->payip eq '' ) {
1406 $error = $self->ut_ip('payip');
1407 return $error if $error;
1410 # If it is encrypted and the private key is not availaible then we can't
1411 # check the credit card.
1413 my $check_payinfo = 1;
1415 if ($self->is_encrypted($self->payinfo)) {
1421 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1423 my $payinfo = $self->payinfo;
1424 $payinfo =~ s/\D//g;
1425 $payinfo =~ /^(\d{13,16})$/
1426 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1428 $self->payinfo($payinfo);
1430 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1432 return gettext('unknown_card_type')
1433 if cardtype($self->payinfo) eq "Unknown";
1435 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1437 return 'Banned credit card: banned on '.
1438 time2str('%a %h %o at %r', $ban->_date).
1439 ' by '. $ban->otaker.
1440 ' (ban# '. $ban->bannum. ')';
1443 if ( defined $self->dbdef_table->column('paycvv') ) {
1444 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1445 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1446 $self->paycvv =~ /^(\d{4})$/
1447 or return "CVV2 (CID) for American Express cards is four digits.";
1450 $self->paycvv =~ /^(\d{3})$/
1451 or return "CVV2 (CVC2/CID) is three digits.";
1459 my $cardtype = cardtype($payinfo);
1460 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1462 return "Start date or issue number is required for $cardtype cards"
1463 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1465 return "Start month must be between 1 and 12"
1466 if $self->paystart_month
1467 and $self->paystart_month < 1 || $self->paystart_month > 12;
1469 return "Start year must be 1990 or later"
1470 if $self->paystart_year
1471 and $self->paystart_year < 1990;
1473 return "Issue number must be beween 1 and 99"
1475 and $self->payissue < 1 || $self->payissue > 99;
1478 $self->paystart_month('');
1479 $self->paystart_year('');
1480 $self->payissue('');
1483 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1485 my $payinfo = $self->payinfo;
1486 $payinfo =~ s/[^\d\@]//g;
1487 if ( $conf->exists('echeck-nonus') ) {
1488 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1489 $payinfo = "$1\@$2";
1491 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1492 $payinfo = "$1\@$2";
1494 $self->payinfo($payinfo);
1495 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1497 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1499 return 'Banned ACH account: banned on '.
1500 time2str('%a %h %o at %r', $ban->_date).
1501 ' by '. $ban->otaker.
1502 ' (ban# '. $ban->bannum. ')';
1505 } elsif ( $self->payby eq 'LECB' ) {
1507 my $payinfo = $self->payinfo;
1508 $payinfo =~ s/\D//g;
1509 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1511 $self->payinfo($payinfo);
1512 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1514 } elsif ( $self->payby eq 'BILL' ) {
1516 $error = $self->ut_textn('payinfo');
1517 return "Illegal P.O. number: ". $self->payinfo if $error;
1518 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1520 } elsif ( $self->payby eq 'COMP' ) {
1522 my $curuser = $FS::CurrentUser::CurrentUser;
1523 if ( ! $self->custnum
1524 && ! $curuser->access_right('Complimentary customer')
1527 return "You are not permitted to create complimentary accounts."
1530 $error = $self->ut_textn('payinfo');
1531 return "Illegal comp account issuer: ". $self->payinfo if $error;
1532 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1534 } elsif ( $self->payby eq 'PREPAY' ) {
1536 my $payinfo = $self->payinfo;
1537 $payinfo =~ s/\W//g; #anything else would just confuse things
1538 $self->payinfo($payinfo);
1539 $error = $self->ut_alpha('payinfo');
1540 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1541 return "Unknown prepayment identifier"
1542 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1543 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1547 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1548 return "Expiration date required"
1549 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1553 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1554 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1555 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1556 ( $m, $y ) = ( $3, "20$2" );
1558 return "Illegal expiration date: ". $self->paydate;
1560 $self->paydate("$y-$m-01");
1561 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1562 return gettext('expired_card')
1564 && !$ignore_expired_card
1565 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1568 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1569 ( ! $conf->exists('require_cardname')
1570 || $self->payby !~ /^(CARD|DCRD)$/ )
1572 $self->payname( $self->first. " ". $self->getfield('last') );
1574 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1575 or return gettext('illegal_name'). " payname: ". $self->payname;
1579 foreach my $flag (qw( tax spool_cdr )) {
1580 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1584 $self->otaker(getotaker) unless $self->otaker;
1586 warn "$me check AFTER: \n". $self->_dump
1589 $self->SUPER::check;
1594 Returns all packages (see L<FS::cust_pkg>) for this customer.
1600 if ( $self->{'_pkgnum'} ) {
1601 values %{ $self->{'_pkgnum'}->cache };
1603 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1607 =item ncancelled_pkgs
1609 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1613 sub ncancelled_pkgs {
1615 if ( $self->{'_pkgnum'} ) {
1616 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1618 @{ [ # force list context
1619 qsearch( 'cust_pkg', {
1620 'custnum' => $self->custnum,
1623 qsearch( 'cust_pkg', {
1624 'custnum' => $self->custnum,
1631 =item suspended_pkgs
1633 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1637 sub suspended_pkgs {
1639 grep { $_->susp } $self->ncancelled_pkgs;
1642 =item unflagged_suspended_pkgs
1644 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1645 customer (thouse packages without the `manual_flag' set).
1649 sub unflagged_suspended_pkgs {
1651 return $self->suspended_pkgs
1652 unless dbdef->table('cust_pkg')->column('manual_flag');
1653 grep { ! $_->manual_flag } $self->suspended_pkgs;
1656 =item unsuspended_pkgs
1658 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1663 sub unsuspended_pkgs {
1665 grep { ! $_->susp } $self->ncancelled_pkgs;
1668 =item num_cancelled_pkgs
1670 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1675 sub num_cancelled_pkgs {
1677 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1681 my( $self, $sql ) = @_;
1682 my $sth = dbh->prepare(
1683 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1684 ) or die dbh->errstr;
1685 $sth->execute($self->custnum) or die $sth->errstr;
1686 $sth->fetchrow_arrayref->[0];
1691 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1692 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1693 on success or a list of errors.
1699 grep { $_->unsuspend } $self->suspended_pkgs;
1704 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1706 Returns a list: an empty list on success or a list of errors.
1712 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1715 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1717 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1718 PKGPARTs (see L<FS::part_pkg>).
1720 Returns a list: an empty list on success or a list of errors.
1724 sub suspend_if_pkgpart {
1726 my (@pkgparts, %opt);
1727 if (ref($_[0]) eq 'HASH'){
1728 @pkgparts = @{$_[0]{pkgparts}};
1733 grep { $_->suspend(%opt) }
1734 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1735 $self->unsuspended_pkgs;
1738 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1740 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1741 listed PKGPARTs (see L<FS::part_pkg>).
1743 Returns a list: an empty list on success or a list of errors.
1747 sub suspend_unless_pkgpart {
1749 my (@pkgparts, %opt);
1750 if (ref($_[0]) eq 'HASH'){
1751 @pkgparts = @{$_[0]{pkgparts}};
1756 grep { $_->suspend(%opt) }
1757 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1758 $self->unsuspended_pkgs;
1761 =item cancel [ OPTION => VALUE ... ]
1763 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1765 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1767 I<quiet> can be set true to supress email cancellation notices.
1769 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1771 I<ban> can be set true to ban this customer's credit card or ACH information,
1774 Always returns a list: an empty list on success or a list of errors.
1782 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1784 #should try decryption (we might have the private key)
1785 # and if not maybe queue a job for the server that does?
1786 return ( "Can't (yet) ban encrypted credit cards" )
1787 if $self->is_encrypted($self->payinfo);
1789 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1790 my $error = $ban->insert;
1791 return ( $error ) if $error;
1795 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1798 sub _banned_pay_hashref {
1809 'payby' => $payby2ban{$self->payby},
1810 'payinfo' => md5_base64($self->payinfo),
1817 Returns all notes (see L<FS::cust_main_note>) for this customer.
1824 qsearch( 'cust_main_note',
1825 { 'custnum' => $self->custnum },
1827 'ORDER BY _DATE DESC'
1833 Returns the agent (see L<FS::agent>) for this customer.
1839 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1844 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1845 conjunction with the collect method.
1847 Options are passed as name-value pairs.
1849 Currently available options are:
1851 resetup - if set true, re-charges setup fees.
1853 time - bills the customer as if it were that time. Specified as a UNIX
1854 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1855 L<Date::Parse> for conversion functions. For example:
1859 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1862 If there is an error, returns the error, otherwise returns false.
1867 my( $self, %options ) = @_;
1868 return '' if $self->payby eq 'COMP';
1869 warn "$me bill customer ". $self->custnum. "\n"
1872 my $time = $options{'time'} || time;
1877 local $SIG{HUP} = 'IGNORE';
1878 local $SIG{INT} = 'IGNORE';
1879 local $SIG{QUIT} = 'IGNORE';
1880 local $SIG{TERM} = 'IGNORE';
1881 local $SIG{TSTP} = 'IGNORE';
1882 local $SIG{PIPE} = 'IGNORE';
1884 my $oldAutoCommit = $FS::UID::AutoCommit;
1885 local $FS::UID::AutoCommit = 0;
1888 $self->select_for_update; #mutex
1890 #create a new invoice
1891 #(we'll remove it later if it doesn't actually need to be generated [contains
1892 # no line items] and we're inside a transaciton so nothing else will see it)
1893 my $cust_bill = new FS::cust_bill ( {
1894 'custnum' => $self->custnum,
1896 #'charged' => $charged,
1899 $error = $cust_bill->insert;
1901 $dbh->rollback if $oldAutoCommit;
1902 return "can't create invoice for customer #". $self->custnum. ": $error";
1904 my $invnum = $cust_bill->invnum;
1907 # find the packages which are due for billing, find out how much they are
1908 # & generate invoice database.
1911 my( $total_setup, $total_recur ) = ( 0, 0 );
1913 my @precommit_hooks = ();
1915 foreach my $cust_pkg (
1916 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1919 #NO!! next if $cust_pkg->cancel;
1920 next if $cust_pkg->getfield('cancel');
1922 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1924 #? to avoid use of uninitialized value errors... ?
1925 $cust_pkg->setfield('bill', '')
1926 unless defined($cust_pkg->bill);
1928 my $part_pkg = $cust_pkg->part_pkg;
1930 my %hash = $cust_pkg->hash;
1931 my $old_cust_pkg = new FS::cust_pkg \%hash;
1940 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1942 warn " bill setup\n" if $DEBUG > 1;
1944 $setup = eval { $cust_pkg->calc_setup( $time ) };
1946 $dbh->rollback if $oldAutoCommit;
1947 return "$@ running calc_setup for $cust_pkg\n";
1950 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1954 # bill recurring fee
1959 if ( $part_pkg->getfield('freq') ne '0' &&
1960 ! $cust_pkg->getfield('susp') &&
1961 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1964 warn " bill recur\n" if $DEBUG > 1;
1966 # XXX shared with $recur_prog
1967 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1969 #over two params! lets at least switch to a hashref for the rest...
1970 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
1972 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
1974 $dbh->rollback if $oldAutoCommit;
1975 return "$@ running calc_recur for $cust_pkg\n";
1978 #change this bit to use Date::Manip? CAREFUL with timezones (see
1979 # mailing list archive)
1980 my ($sec,$min,$hour,$mday,$mon,$year) =
1981 (localtime($sdate) )[0,1,2,3,4,5];
1983 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1984 # only for figuring next bill date, nothing else, so, reset $sdate again
1986 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1987 $cust_pkg->last_bill($sdate)
1988 if $cust_pkg->dbdef_table->column('last_bill');
1990 if ( $part_pkg->freq =~ /^\d+$/ ) {
1991 $mon += $part_pkg->freq;
1992 until ( $mon < 12 ) { $mon -= 12; $year++; }
1993 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1995 $mday += $weeks * 7;
1996 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1999 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2003 $dbh->rollback if $oldAutoCommit;
2004 return "unparsable frequency: ". $part_pkg->freq;
2006 $cust_pkg->setfield('bill',
2007 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2010 warn "\$setup is undefined" unless defined($setup);
2011 warn "\$recur is undefined" unless defined($recur);
2012 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2015 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2018 if ( $cust_pkg->modified ) {
2020 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2023 $error=$cust_pkg->replace($old_cust_pkg);
2024 if ( $error ) { #just in case
2025 $dbh->rollback if $oldAutoCommit;
2026 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2029 $setup = sprintf( "%.2f", $setup );
2030 $recur = sprintf( "%.2f", $recur );
2031 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2032 $dbh->rollback if $oldAutoCommit;
2033 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2035 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2036 $dbh->rollback if $oldAutoCommit;
2037 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2040 if ( $setup != 0 || $recur != 0 ) {
2042 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2044 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2045 'invnum' => $invnum,
2046 'pkgnum' => $cust_pkg->pkgnum,
2050 'edate' => $cust_pkg->bill,
2051 'details' => \@details,
2053 $error = $cust_bill_pkg->insert;
2055 $dbh->rollback if $oldAutoCommit;
2056 return "can't create invoice line item for invoice #$invnum: $error";
2058 $total_setup += $setup;
2059 $total_recur += $recur;
2065 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2068 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2071 my %taxhash = map { $_ => $self->get("$prefix$_") }
2072 qw( state county country );
2074 $taxhash{'taxclass'} = $part_pkg->taxclass;
2076 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2079 $taxhash{'taxclass'} = '';
2080 @taxes = qsearch( 'cust_main_county', \%taxhash );
2083 #one more try at a whole-country tax rate
2085 $taxhash{$_} = '' foreach qw( state county );
2086 @taxes = qsearch( 'cust_main_county', \%taxhash );
2089 # maybe eliminate this entirely, along with all the 0% records
2091 $dbh->rollback if $oldAutoCommit;
2093 "fatal: can't find tax rate for state/county/country/taxclass ".
2094 join('/', ( map $self->get("$prefix$_"),
2095 qw(state county country)
2097 $part_pkg->taxclass ). "\n";
2100 foreach my $tax ( @taxes ) {
2102 my $taxable_charged = 0;
2103 $taxable_charged += $setup
2104 unless $part_pkg->setuptax =~ /^Y$/i
2105 || $tax->setuptax =~ /^Y$/i;
2106 $taxable_charged += $recur
2107 unless $part_pkg->recurtax =~ /^Y$/i
2108 || $tax->recurtax =~ /^Y$/i;
2109 next unless $taxable_charged;
2111 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2112 #my ($mon,$year) = (localtime($sdate) )[4,5];
2113 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2115 my $freq = $part_pkg->freq || 1;
2116 if ( $freq !~ /(\d+)$/ ) {
2117 $dbh->rollback if $oldAutoCommit;
2118 return "daily/weekly package definitions not (yet?)".
2119 " compatible with monthly tax exemptions";
2121 my $taxable_per_month =
2122 sprintf("%.2f", $taxable_charged / $freq );
2124 #call the whole thing off if this customer has any old
2125 #exemption records...
2126 my @cust_tax_exempt =
2127 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2128 if ( @cust_tax_exempt ) {
2129 $dbh->rollback if $oldAutoCommit;
2131 'this customer still has old-style tax exemption records; '.
2132 'run bin/fs-migrate-cust_tax_exempt?';
2135 foreach my $which_month ( 1 .. $freq ) {
2137 #maintain the new exemption table now
2140 FROM cust_tax_exempt_pkg
2141 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2142 LEFT JOIN cust_bill USING ( invnum )
2148 my $sth = dbh->prepare($sql) or do {
2149 $dbh->rollback if $oldAutoCommit;
2150 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2158 $dbh->rollback if $oldAutoCommit;
2159 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2161 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2163 my $remaining_exemption =
2164 $tax->exempt_amount - $existing_exemption;
2165 if ( $remaining_exemption > 0 ) {
2166 my $addl = $remaining_exemption > $taxable_per_month
2167 ? $taxable_per_month
2168 : $remaining_exemption;
2169 $taxable_charged -= $addl;
2171 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2172 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2173 'taxnum' => $tax->taxnum,
2174 'year' => 1900+$year,
2176 'amount' => sprintf("%.2f", $addl ),
2178 $error = $cust_tax_exempt_pkg->insert;
2180 $dbh->rollback if $oldAutoCommit;
2181 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2183 } # if $remaining_exemption > 0
2187 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2188 until ( $mon < 13 ) { $mon -= 12; $year++; }
2190 } #foreach $which_month
2192 } #if $tax->exempt_amount
2194 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2196 #$tax += $taxable_charged * $cust_main_county->tax / 100
2197 $tax{ $tax->taxname || 'Tax' } +=
2198 $taxable_charged * $tax->tax / 100
2200 } #foreach my $tax ( @taxes )
2202 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2204 } #if $setup != 0 || $recur != 0
2206 } #if $cust_pkg->modified
2208 } #foreach my $cust_pkg
2210 unless ( $cust_bill->cust_bill_pkg ) {
2211 $cust_bill->delete; #don't create an invoice w/o line items
2212 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2216 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2218 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2219 my $tax = sprintf("%.2f", $tax{$taxname} );
2220 $charged = sprintf( "%.2f", $charged+$tax );
2222 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2223 'invnum' => $invnum,
2229 'itemdesc' => $taxname,
2231 $error = $cust_bill_pkg->insert;
2233 $dbh->rollback if $oldAutoCommit;
2234 return "can't create invoice line item for invoice #$invnum: $error";
2236 $total_setup += $tax;
2240 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2241 $error = $cust_bill->replace;
2243 $dbh->rollback if $oldAutoCommit;
2244 return "can't update charged for invoice #$invnum: $error";
2247 foreach my $hook ( @precommit_hooks ) {
2249 &{$hook}; #($self) ?
2252 $dbh->rollback if $oldAutoCommit;
2253 return "$@ running precommit hook $hook\n";
2257 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2261 =item collect OPTIONS
2263 (Attempt to) collect money for this customer's outstanding invoices (see
2264 L<FS::cust_bill>). Usually used after the bill method.
2266 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2267 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2268 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2270 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2271 and the invoice events web interface.
2273 If there is an error, returns the error, otherwise returns false.
2275 Options are passed as name-value pairs.
2277 Currently available options are:
2279 invoice_time - Use this time when deciding when to print invoices and
2280 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>
2281 for conversion functions.
2283 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2286 quiet - set true to surpress email card/ACH decline notices.
2288 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2291 payby - allows for one time override of normal customer billing method
2296 my( $self, %options ) = @_;
2297 my $invoice_time = $options{'invoice_time'} || time;
2300 local $SIG{HUP} = 'IGNORE';
2301 local $SIG{INT} = 'IGNORE';
2302 local $SIG{QUIT} = 'IGNORE';
2303 local $SIG{TERM} = 'IGNORE';
2304 local $SIG{TSTP} = 'IGNORE';
2305 local $SIG{PIPE} = 'IGNORE';
2307 my $oldAutoCommit = $FS::UID::AutoCommit;
2308 local $FS::UID::AutoCommit = 0;
2311 $self->select_for_update; #mutex
2313 my $balance = $self->balance;
2314 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2316 unless ( $balance > 0 ) { #redundant?????
2317 $dbh->rollback if $oldAutoCommit; #hmm
2321 if ( exists($options{'retry_card'}) ) {
2322 carp 'retry_card option passed to collect is deprecated; use retry';
2323 $options{'retry'} ||= $options{'retry_card'};
2325 if ( exists($options{'retry'}) && $options{'retry'} ) {
2326 my $error = $self->retry_realtime;
2328 $dbh->rollback if $oldAutoCommit;
2334 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2335 $extra_sql = " AND freq = '1m' ";
2337 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2340 foreach my $cust_bill ( $self->open_cust_bill ) {
2342 # don't try to charge for the same invoice if it's already in a batch
2343 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2345 last if $self->balance <= 0;
2347 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2350 foreach my $part_bill_event ( due_events ( $cust_bill,
2351 exists($options{'payby'})
2357 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2358 || $self->balance <= 0; # or if balance<=0
2361 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2362 warn " do_event " . $cust_bill . " ". (%options) . "\n"
2365 if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2366 # gah, even with transactions.
2367 $dbh->commit if $oldAutoCommit; #well.
2376 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2381 =item retry_realtime
2383 Schedules realtime / batch credit card / electronic check / LEC billing
2384 events for for retry. Useful if card information has changed or manual
2385 retry is desired. The 'collect' method must be called to actually retry
2388 Implementation details: For each of this customer's open invoices, changes
2389 the status of the first "done" (with statustext error) realtime processing
2394 sub retry_realtime {
2397 local $SIG{HUP} = 'IGNORE';
2398 local $SIG{INT} = 'IGNORE';
2399 local $SIG{QUIT} = 'IGNORE';
2400 local $SIG{TERM} = 'IGNORE';
2401 local $SIG{TSTP} = 'IGNORE';
2402 local $SIG{PIPE} = 'IGNORE';
2404 my $oldAutoCommit = $FS::UID::AutoCommit;
2405 local $FS::UID::AutoCommit = 0;
2408 foreach my $cust_bill (
2409 grep { $_->cust_bill_event }
2410 $self->open_cust_bill
2412 my @cust_bill_event =
2413 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2415 #$_->part_bill_event->plan eq 'realtime-card'
2416 $_->part_bill_event->eventcode =~
2417 /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2418 && $_->status eq 'done'
2421 $cust_bill->cust_bill_event;
2422 next unless @cust_bill_event;
2423 my $error = $cust_bill_event[0]->retry;
2425 $dbh->rollback if $oldAutoCommit;
2426 return "error scheduling invoice event for retry: $error";
2431 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2436 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2438 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2439 via a Business::OnlinePayment realtime gateway. See
2440 L<http://420.am/business-onlinepayment> for supported gateways.
2442 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2444 Available options are: I<description>, I<invnum>, I<quiet>
2446 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2447 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2448 if set, will override the value from the customer record.
2450 I<description> is a free-text field passed to the gateway. It defaults to
2451 "Internet services".
2453 If an I<invnum> is specified, this payment (if successful) is applied to the
2454 specified invoice. If you don't specify an I<invnum> you might want to
2455 call the B<apply_payments> method.
2457 I<quiet> can be set true to surpress email decline notices.
2459 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2464 my( $self, $method, $amount, %options ) = @_;
2466 warn "$me realtime_bop: $method $amount\n";
2467 warn " $_ => $options{$_}\n" foreach keys %options;
2470 $options{'description'} ||= 'Internet services';
2472 eval "use Business::OnlinePayment";
2475 my $payinfo = exists($options{'payinfo'})
2476 ? $options{'payinfo'}
2484 if ( $options{'invnum'} ) {
2485 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2486 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2488 map { $_->part_pkg->taxclass }
2490 map { $_->cust_pkg }
2491 $cust_bill->cust_bill_pkg;
2492 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2493 #different taxclasses
2494 $taxclass = $taxclasses[0];
2498 #look for an agent gateway override first
2500 if ( $method eq 'CC' ) {
2501 $cardtype = cardtype($payinfo);
2502 } elsif ( $method eq 'ECHECK' ) {
2505 $cardtype = $method;
2509 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2510 cardtype => $cardtype,
2511 taxclass => $taxclass, } )
2512 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2514 taxclass => $taxclass, } )
2515 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2516 cardtype => $cardtype,
2518 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2520 taxclass => '', } );
2522 my $payment_gateway = '';
2523 my( $processor, $login, $password, $action, @bop_options );
2524 if ( $override ) { #use a payment gateway override
2526 $payment_gateway = $override->payment_gateway;
2528 $processor = $payment_gateway->gateway_module;
2529 $login = $payment_gateway->gateway_username;
2530 $password = $payment_gateway->gateway_password;
2531 $action = $payment_gateway->gateway_action;
2532 @bop_options = $payment_gateway->options;
2534 } else { #use the standard settings from the config
2536 ( $processor, $login, $password, $action, @bop_options ) =
2537 $self->default_payment_gateway($method);
2545 my $address = exists($options{'address1'})
2546 ? $options{'address1'}
2548 my $address2 = exists($options{'address2'})
2549 ? $options{'address2'}
2551 $address .= ", ". $address2 if length($address2);
2553 my $o_payname = exists($options{'payname'})
2554 ? $options{'payname'}
2556 my($payname, $payfirst, $paylast);
2557 if ( $o_payname && $method ne 'ECHECK' ) {
2558 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2559 or return "Illegal payname $payname";
2560 ($payfirst, $paylast) = ($1, $2);
2562 $payfirst = $self->getfield('first');
2563 $paylast = $self->getfield('last');
2564 $payname = "$payfirst $paylast";
2567 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2568 if ( $conf->exists('emailinvoiceauto')
2569 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2570 push @invoicing_list, $self->all_emails;
2573 my $email = ($conf->exists('business-onlinepayment-email-override'))
2574 ? $conf->config('business-onlinepayment-email-override')
2575 : $invoicing_list[0];
2579 my $payip = exists($options{'payip'})
2582 $content{customer_ip} = $payip
2585 $content{invoice_number} = $options{'invnum'}
2586 if exists($options{'invnum'}) && length($options{'invnum'});
2588 if ( $method eq 'CC' ) {
2590 $content{card_number} = $payinfo;
2591 my $paydate = exists($options{'paydate'})
2592 ? $options{'paydate'}
2594 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2595 $content{expiration} = "$2/$1";
2597 my $paycvv = exists($options{'paycvv'})
2598 ? $options{'paycvv'}
2600 $content{cvv2} = $self->paycvv
2603 my $paystart_month = exists($options{'paystart_month'})
2604 ? $options{'paystart_month'}
2605 : $self->paystart_month;
2607 my $paystart_year = exists($options{'paystart_year'})
2608 ? $options{'paystart_year'}
2609 : $self->paystart_year;
2611 $content{card_start} = "$paystart_month/$paystart_year"
2612 if $paystart_month && $paystart_year;
2614 my $payissue = exists($options{'payissue'})
2615 ? $options{'payissue'}
2617 $content{issue_number} = $payissue if $payissue;
2619 $content{recurring_billing} = 'YES'
2620 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2622 'payinfo' => $payinfo,
2625 } elsif ( $method eq 'ECHECK' ) {
2626 ( $content{account_number}, $content{routing_code} ) =
2627 split('@', $payinfo);
2628 $content{bank_name} = $o_payname;
2629 $content{account_type} = 'CHECKING';
2630 $content{account_name} = $payname;
2631 $content{customer_org} = $self->company ? 'B' : 'I';
2632 $content{customer_ssn} = exists($options{'ss'})
2635 } elsif ( $method eq 'LEC' ) {
2636 $content{phone} = $payinfo;
2640 # run transaction(s)
2643 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2645 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2646 $transaction->content(
2649 'password' => $password,
2650 'action' => $action1,
2651 'description' => $options{'description'},
2652 'amount' => $amount,
2653 #'invoice_number' => $options{'invnum'},
2654 'customer_id' => $self->custnum,
2655 'last_name' => $paylast,
2656 'first_name' => $payfirst,
2658 'address' => $address,
2659 'city' => ( exists($options{'city'})
2662 'state' => ( exists($options{'state'})
2665 'zip' => ( exists($options{'zip'})
2668 'country' => ( exists($options{'country'})
2669 ? $options{'country'}
2671 'referer' => 'http://cleanwhisker.420.am/',
2673 'phone' => $self->daytime || $self->night,
2676 $transaction->submit();
2678 if ( $transaction->is_success() && $action2 ) {
2679 my $auth = $transaction->authorization;
2680 my $ordernum = $transaction->can('order_number')
2681 ? $transaction->order_number
2685 new Business::OnlinePayment( $processor, @bop_options );
2692 password => $password,
2693 order_number => $ordernum,
2695 authorization => $auth,
2696 description => $options{'description'},
2699 foreach my $field (qw( authorization_source_code returned_ACI
2700 transaction_identifier validation_code
2701 transaction_sequence_num local_transaction_date
2702 local_transaction_time AVS_result_code )) {
2703 $capture{$field} = $transaction->$field() if $transaction->can($field);
2706 $capture->content( %capture );
2710 unless ( $capture->is_success ) {
2711 my $e = "Authorization successful but capture failed, custnum #".
2712 $self->custnum. ': '. $capture->result_code.
2713 ": ". $capture->error_message;
2721 # remove paycvv after initial transaction
2724 #false laziness w/misc/process/payment.cgi - check both to make sure working
2726 if ( defined $self->dbdef_table->column('paycvv')
2727 && length($self->paycvv)
2728 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2730 my $error = $self->remove_cvv;
2732 warn "WARNING: error removing cvv: $error\n";
2740 if ( $transaction->is_success() ) {
2742 my %method2payby = (
2749 if ( $payment_gateway ) { # agent override
2750 $paybatch = $payment_gateway->gatewaynum. '-';
2753 $paybatch .= "$processor:". $transaction->authorization;
2755 $paybatch .= ':'. $transaction->order_number
2756 if $transaction->can('order_number')
2757 && length($transaction->order_number);
2759 my $cust_pay = new FS::cust_pay ( {
2760 'custnum' => $self->custnum,
2761 'invnum' => $options{'invnum'},
2764 'payby' => $method2payby{$method},
2765 'payinfo' => $payinfo,
2766 'paybatch' => $paybatch,
2768 my $error = $cust_pay->insert;
2770 $cust_pay->invnum(''); #try again with no specific invnum
2771 my $error2 = $cust_pay->insert;
2773 # gah, even with transactions.
2774 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2775 "error inserting payment ($processor): $error2".
2776 " (previously tried insert with invnum #$options{'invnum'}" .
2782 return ''; #no error
2786 my $perror = "$processor error: ". $transaction->error_message;
2788 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2789 && $conf->exists('emaildecline')
2790 && grep { $_ ne 'POST' } $self->invoicing_list
2791 && ! grep { $transaction->error_message =~ /$_/ }
2792 $conf->config('emaildecline-exclude')
2794 my @templ = $conf->config('declinetemplate');
2795 my $template = new Text::Template (
2797 SOURCE => [ map "$_\n", @templ ],
2798 ) or return "($perror) can't create template: $Text::Template::ERROR";
2799 $template->compile()
2800 or return "($perror) can't compile template: $Text::Template::ERROR";
2802 my $templ_hash = { error => $transaction->error_message };
2804 my $error = send_email(
2805 'from' => $conf->config('invoice_from'),
2806 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2807 'subject' => 'Your payment could not be processed',
2808 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2811 $perror .= " (also received error sending decline notification: $error)"
2821 =item default_payment_gateway
2825 sub default_payment_gateway {
2826 my( $self, $method ) = @_;
2828 die "Real-time processing not enabled\n"
2829 unless $conf->exists('business-onlinepayment');
2832 my $bop_config = 'business-onlinepayment';
2833 $bop_config .= '-ach'
2834 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2835 my ( $processor, $login, $password, $action, @bop_options ) =
2836 $conf->config($bop_config);
2837 $action ||= 'normal authorization';
2838 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2839 die "No real-time processor is enabled - ".
2840 "did you set the business-onlinepayment configuration value?\n"
2843 ( $processor, $login, $password, $action, @bop_options )
2848 Removes the I<paycvv> field from the database directly.
2850 If there is an error, returns the error, otherwise returns false.
2856 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2857 or return dbh->errstr;
2858 $sth->execute($self->custnum)
2859 or return $sth->errstr;
2864 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2866 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2867 via a Business::OnlinePayment realtime gateway. See
2868 L<http://420.am/business-onlinepayment> for supported gateways.
2870 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2872 Available options are: I<amount>, I<reason>, I<paynum>
2874 Most gateways require a reference to an original payment transaction to refund,
2875 so you probably need to specify a I<paynum>.
2877 I<amount> defaults to the original amount of the payment if not specified.
2879 I<reason> specifies a reason for the refund.
2881 Implementation note: If I<amount> is unspecified or equal to the amount of the
2882 orignal payment, first an attempt is made to "void" the transaction via
2883 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2884 the normal attempt is made to "refund" ("credit") the transaction via the
2885 gateway is attempted.
2887 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2888 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2889 #if set, will override the value from the customer record.
2891 #If an I<invnum> is specified, this payment (if successful) is applied to the
2892 #specified invoice. If you don't specify an I<invnum> you might want to
2893 #call the B<apply_payments> method.
2897 #some false laziness w/realtime_bop, not enough to make it worth merging
2898 #but some useful small subs should be pulled out
2899 sub realtime_refund_bop {
2900 my( $self, $method, %options ) = @_;
2902 warn "$me realtime_refund_bop: $method refund\n";
2903 warn " $_ => $options{$_}\n" foreach keys %options;
2906 eval "use Business::OnlinePayment";
2910 # look up the original payment and optionally a gateway for that payment
2914 my $amount = $options{'amount'};
2916 my( $processor, $login, $password, @bop_options ) ;
2917 my( $auth, $order_number ) = ( '', '', '' );
2919 if ( $options{'paynum'} ) {
2921 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
2922 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2923 or return "Unknown paynum $options{'paynum'}";
2924 $amount ||= $cust_pay->paid;
2926 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2927 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2928 $cust_pay->paybatch;
2929 my $gatewaynum = '';
2930 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2932 if ( $gatewaynum ) { #gateway for the payment to be refunded
2934 my $payment_gateway =
2935 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2936 die "payment gateway $gatewaynum not found"
2937 unless $payment_gateway;
2939 $processor = $payment_gateway->gateway_module;
2940 $login = $payment_gateway->gateway_username;
2941 $password = $payment_gateway->gateway_password;
2942 @bop_options = $payment_gateway->options;
2944 } else { #try the default gateway
2946 my( $conf_processor, $unused_action );
2947 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2948 $self->default_payment_gateway($method);
2950 return "processor of payment $options{'paynum'} $processor does not".
2951 " match default processor $conf_processor"
2952 unless $processor eq $conf_processor;
2957 } else { # didn't specify a paynum, so look for agent gateway overrides
2958 # like a normal transaction
2961 if ( $method eq 'CC' ) {
2962 $cardtype = cardtype($self->payinfo);
2963 } elsif ( $method eq 'ECHECK' ) {
2966 $cardtype = $method;
2969 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2970 cardtype => $cardtype,
2972 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2974 taxclass => '', } );
2976 if ( $override ) { #use a payment gateway override
2978 my $payment_gateway = $override->payment_gateway;
2980 $processor = $payment_gateway->gateway_module;
2981 $login = $payment_gateway->gateway_username;
2982 $password = $payment_gateway->gateway_password;
2983 #$action = $payment_gateway->gateway_action;
2984 @bop_options = $payment_gateway->options;
2986 } else { #use the standard settings from the config
2989 ( $processor, $login, $password, $unused_action, @bop_options ) =
2990 $self->default_payment_gateway($method);
2995 return "neither amount nor paynum specified" unless $amount;
3000 'password' => $password,
3001 'order_number' => $order_number,
3002 'amount' => $amount,
3003 'referer' => 'http://cleanwhisker.420.am/',
3005 $content{authorization} = $auth
3006 if length($auth); #echeck/ACH transactions have an order # but no auth
3007 #(at least with authorize.net)
3009 #first try void if applicable
3010 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
3011 warn " attempting void\n" if $DEBUG > 1;
3012 my $void = new Business::OnlinePayment( $processor, @bop_options );
3013 $void->content( 'action' => 'void', %content );
3015 if ( $void->is_success ) {
3016 my $error = $cust_pay->void($options{'reason'});
3018 # gah, even with transactions.
3019 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3020 "error voiding payment: $error";
3024 warn " void successful\n" if $DEBUG > 1;
3029 warn " void unsuccessful, trying refund\n"
3033 my $address = $self->address1;
3034 $address .= ", ". $self->address2 if $self->address2;
3036 my($payname, $payfirst, $paylast);
3037 if ( $self->payname && $method ne 'ECHECK' ) {
3038 $payname = $self->payname;
3039 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3040 or return "Illegal payname $payname";
3041 ($payfirst, $paylast) = ($1, $2);
3043 $payfirst = $self->getfield('first');
3044 $paylast = $self->getfield('last');
3045 $payname = "$payfirst $paylast";
3048 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
3049 if ( $conf->exists('emailinvoiceauto')
3050 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3051 push @invoicing_list, $self->all_emails;
3054 my $email = ($conf->exists('business-onlinepayment-email-override'))
3055 ? $conf->config('business-onlinepayment-email-override')
3056 : $invoicing_list[0];
3058 my $payip = exists($options{'payip'})
3061 $content{customer_ip} = $payip
3065 if ( $method eq 'CC' ) {
3068 $content{card_number} = $payinfo = $cust_pay->payinfo;
3069 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3070 #$content{expiration} = "$2/$1";
3072 $content{card_number} = $payinfo = $self->payinfo;
3073 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3074 $content{expiration} = "$2/$1";
3077 } elsif ( $method eq 'ECHECK' ) {
3078 ( $content{account_number}, $content{routing_code} ) =
3079 split('@', $payinfo = $self->payinfo);
3080 $content{bank_name} = $self->payname;
3081 $content{account_type} = 'CHECKING';
3082 $content{account_name} = $payname;
3083 $content{customer_org} = $self->company ? 'B' : 'I';
3084 $content{customer_ssn} = $self->ss;
3085 } elsif ( $method eq 'LEC' ) {
3086 $content{phone} = $payinfo = $self->payinfo;
3090 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3091 my %sub_content = $refund->content(
3092 'action' => 'credit',
3093 'customer_id' => $self->custnum,
3094 'last_name' => $paylast,
3095 'first_name' => $payfirst,
3097 'address' => $address,
3098 'city' => $self->city,
3099 'state' => $self->state,
3100 'zip' => $self->zip,
3101 'country' => $self->country,
3103 'phone' => $self->daytime || $self->night,
3106 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3110 return "$processor error: ". $refund->error_message
3111 unless $refund->is_success();
3113 my %method2payby = (
3119 my $paybatch = "$processor:". $refund->authorization;
3120 $paybatch .= ':'. $refund->order_number
3121 if $refund->can('order_number') && $refund->order_number;
3123 while ( $cust_pay && $cust_pay->unappled < $amount ) {
3124 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3125 last unless @cust_bill_pay;
3126 my $cust_bill_pay = pop @cust_bill_pay;
3127 my $error = $cust_bill_pay->delete;
3131 my $cust_refund = new FS::cust_refund ( {
3132 'custnum' => $self->custnum,
3133 'paynum' => $options{'paynum'},
3134 'refund' => $amount,
3136 'payby' => $method2payby{$method},
3137 'payinfo' => $payinfo,
3138 'paybatch' => $paybatch,
3139 'reason' => $options{'reason'} || 'card or ACH refund',
3141 my $error = $cust_refund->insert;
3143 $cust_refund->paynum(''); #try again with no specific paynum
3144 my $error2 = $cust_refund->insert;
3146 # gah, even with transactions.
3147 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3148 "error inserting refund ($processor): $error2".
3149 " (previously tried insert with paynum #$options{'paynum'}" .
3162 Returns the total owed for this customer on all invoices
3163 (see L<FS::cust_bill/owed>).
3169 $self->total_owed_date(2145859200); #12/31/2037
3172 =item total_owed_date TIME
3174 Returns the total owed for this customer on all invoices with date earlier than
3175 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3176 see L<Time::Local> and L<Date::Parse> for conversion functions.
3180 sub total_owed_date {
3184 foreach my $cust_bill (
3185 grep { $_->_date <= $time }
3186 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3188 $total_bill += $cust_bill->owed;
3190 sprintf( "%.2f", $total_bill );
3193 =item apply_credits OPTION => VALUE ...
3195 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3196 to outstanding invoice balances in chronological order (or reverse
3197 chronological order if the I<order> option is set to B<newest>) and returns the
3198 value of any remaining unapplied credits available for refund (see
3199 L<FS::cust_refund>).
3207 return 0 unless $self->total_credited;
3209 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3210 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3212 my @invoices = $self->open_cust_bill;
3213 @invoices = sort { $b->_date <=> $a->_date } @invoices
3214 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3217 foreach my $cust_bill ( @invoices ) {
3220 if ( !defined($credit) || $credit->credited == 0) {
3221 $credit = pop @credits or last;
3224 if ($cust_bill->owed >= $credit->credited) {
3225 $amount=$credit->credited;
3227 $amount=$cust_bill->owed;
3230 my $cust_credit_bill = new FS::cust_credit_bill ( {
3231 'crednum' => $credit->crednum,
3232 'invnum' => $cust_bill->invnum,
3233 'amount' => $amount,
3235 my $error = $cust_credit_bill->insert;
3236 die $error if $error;
3238 redo if ($cust_bill->owed > 0);
3242 return $self->total_credited;
3245 =item apply_payments
3247 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3248 to outstanding invoice balances in chronological order.
3250 #and returns the value of any remaining unapplied payments.
3254 sub apply_payments {
3259 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3260 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3262 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3263 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3267 foreach my $cust_bill ( @invoices ) {
3270 if ( !defined($payment) || $payment->unapplied == 0 ) {
3271 $payment = pop @payments or last;
3274 if ( $cust_bill->owed >= $payment->unapplied ) {
3275 $amount = $payment->unapplied;
3277 $amount = $cust_bill->owed;
3280 my $cust_bill_pay = new FS::cust_bill_pay ( {
3281 'paynum' => $payment->paynum,
3282 'invnum' => $cust_bill->invnum,
3283 'amount' => $amount,
3285 my $error = $cust_bill_pay->insert;
3286 die $error if $error;
3288 redo if ( $cust_bill->owed > 0);
3292 return $self->total_unapplied_payments;
3295 =item total_credited
3297 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3298 customer. See L<FS::cust_credit/credited>.
3302 sub total_credited {
3304 my $total_credit = 0;
3305 foreach my $cust_credit ( qsearch('cust_credit', {
3306 'custnum' => $self->custnum,
3308 $total_credit += $cust_credit->credited;
3310 sprintf( "%.2f", $total_credit );
3313 =item total_unapplied_payments
3315 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3316 See L<FS::cust_pay/unapplied>.
3320 sub total_unapplied_payments {
3322 my $total_unapplied = 0;
3323 foreach my $cust_pay ( qsearch('cust_pay', {
3324 'custnum' => $self->custnum,
3326 $total_unapplied += $cust_pay->unapplied;
3328 sprintf( "%.2f", $total_unapplied );
3333 Returns the balance for this customer (total_owed minus total_credited
3334 minus total_unapplied_payments).
3341 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
3345 =item balance_date TIME
3347 Returns the balance for this customer, only considering invoices with date
3348 earlier than TIME (total_owed_date minus total_credited minus
3349 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3350 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3359 $self->total_owed_date($time)
3360 - $self->total_credited
3361 - $self->total_unapplied_payments
3365 =item in_transit_payments
3367 Returns the total of requests for payments for this customer pending in
3368 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3372 sub in_transit_payments {
3374 my $in_transit_payments = 0;
3375 foreach my $pay_batch ( qsearch('pay_batch', {
3378 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3379 'batchnum' => $pay_batch->batchnum,
3380 'custnum' => $self->custnum,
3382 $in_transit_payments += $cust_pay_batch->amount;
3385 sprintf( "%.2f", $in_transit_payments );
3388 =item paydate_monthyear
3390 Returns a two-element list consisting of the month and year of this customer's
3391 paydate (credit card expiration date for CARD customers)
3395 sub paydate_monthyear {
3397 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3399 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3406 =item payinfo_masked
3408 Returns a "masked" payinfo field appropriate to the payment type. Masked characters are replaced by 'x'es. Use this to display publicly accessable account Information.
3410 Credit Cards - Mask all but the last four characters.
3411 Checks - Mask all but last 2 of account number and bank routing number.
3412 Others - Do nothing, return the unmasked string.
3416 sub payinfo_masked {
3418 return $self->paymask;
3421 =item invoicing_list [ ARRAYREF ]
3423 If an arguement is given, sets these email addresses as invoice recipients
3424 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3425 (except as warnings), so use check_invoicing_list first.
3427 Returns a list of email addresses (with svcnum entries expanded).
3429 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3430 check it without disturbing anything by passing nothing.
3432 This interface may change in the future.
3436 sub invoicing_list {
3437 my( $self, $arrayref ) = @_;
3440 my @cust_main_invoice;
3441 if ( $self->custnum ) {
3442 @cust_main_invoice =
3443 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3445 @cust_main_invoice = ();
3447 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3448 #warn $cust_main_invoice->destnum;
3449 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3450 #warn $cust_main_invoice->destnum;
3451 my $error = $cust_main_invoice->delete;
3452 warn $error if $error;
3455 if ( $self->custnum ) {
3456 @cust_main_invoice =
3457 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3459 @cust_main_invoice = ();
3461 my %seen = map { $_->address => 1 } @cust_main_invoice;
3462 foreach my $address ( @{$arrayref} ) {
3463 next if exists $seen{$address} && $seen{$address};
3464 $seen{$address} = 1;
3465 my $cust_main_invoice = new FS::cust_main_invoice ( {
3466 'custnum' => $self->custnum,
3469 my $error = $cust_main_invoice->insert;
3470 warn $error if $error;
3474 if ( $self->custnum ) {
3476 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3483 =item check_invoicing_list ARRAYREF
3485 Checks these arguements as valid input for the invoicing_list method. If there
3486 is an error, returns the error, otherwise returns false.
3490 sub check_invoicing_list {
3491 my( $self, $arrayref ) = @_;
3492 foreach my $address ( @{$arrayref} ) {
3494 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3495 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3498 my $cust_main_invoice = new FS::cust_main_invoice ( {
3499 'custnum' => $self->custnum,
3502 my $error = $self->custnum
3503 ? $cust_main_invoice->check
3504 : $cust_main_invoice->checkdest
3506 return $error if $error;
3511 =item set_default_invoicing_list
3513 Sets the invoicing list to all accounts associated with this customer,
3514 overwriting any previous invoicing list.
3518 sub set_default_invoicing_list {
3520 $self->invoicing_list($self->all_emails);
3525 Returns the email addresses of all accounts provisioned for this customer.
3532 foreach my $cust_pkg ( $self->all_pkgs ) {
3533 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3535 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3536 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3538 $list{$_}=1 foreach map { $_->email } @svc_acct;
3543 =item invoicing_list_addpost
3545 Adds postal invoicing to this customer. If this customer is already configured
3546 to receive postal invoices, does nothing.
3550 sub invoicing_list_addpost {
3552 return if grep { $_ eq 'POST' } $self->invoicing_list;
3553 my @invoicing_list = $self->invoicing_list;
3554 push @invoicing_list, 'POST';
3555 $self->invoicing_list(\@invoicing_list);
3558 =item invoicing_list_emailonly
3560 Returns the list of email invoice recipients (invoicing_list without non-email
3561 destinations such as POST and FAX).
3565 sub invoicing_list_emailonly {
3567 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3570 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3572 Returns an array of customers referred by this customer (referral_custnum set
3573 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3574 customers referred by customers referred by this customer and so on, inclusive.
3575 The default behavior is DEPTH 1 (no recursion).
3579 sub referral_cust_main {
3581 my $depth = @_ ? shift : 1;
3582 my $exclude = @_ ? shift : {};
3585 map { $exclude->{$_->custnum}++; $_; }
3586 grep { ! $exclude->{ $_->custnum } }
3587 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3591 map { $_->referral_cust_main($depth-1, $exclude) }
3598 =item referral_cust_main_ncancelled
3600 Same as referral_cust_main, except only returns customers with uncancelled
3605 sub referral_cust_main_ncancelled {
3607 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3610 =item referral_cust_pkg [ DEPTH ]
3612 Like referral_cust_main, except returns a flat list of all unsuspended (and
3613 uncancelled) packages for each customer. The number of items in this list may
3614 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3618 sub referral_cust_pkg {
3620 my $depth = @_ ? shift : 1;
3622 map { $_->unsuspended_pkgs }
3623 grep { $_->unsuspended_pkgs }
3624 $self->referral_cust_main($depth);
3627 =item referring_cust_main
3629 Returns the single cust_main record for the customer who referred this customer
3630 (referral_custnum), or false.
3634 sub referring_cust_main {
3636 return '' unless $self->referral_custnum;
3637 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3640 =item credit AMOUNT, REASON
3642 Applies a credit to this customer. If there is an error, returns the error,
3643 otherwise returns false.
3648 my( $self, $amount, $reason ) = @_;
3649 my $cust_credit = new FS::cust_credit {
3650 'custnum' => $self->custnum,
3651 'amount' => $amount,
3652 'reason' => $reason,
3654 $cust_credit->insert;
3657 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3659 Creates a one-time charge for this customer. If there is an error, returns
3660 the error, otherwise returns false.
3665 my ( $self, $amount ) = ( shift, shift );
3666 my $pkg = @_ ? shift : 'One-time charge';
3667 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3668 my $taxclass = @_ ? shift : '';
3670 local $SIG{HUP} = 'IGNORE';
3671 local $SIG{INT} = 'IGNORE';
3672 local $SIG{QUIT} = 'IGNORE';
3673 local $SIG{TERM} = 'IGNORE';
3674 local $SIG{TSTP} = 'IGNORE';
3675 local $SIG{PIPE} = 'IGNORE';
3677 my $oldAutoCommit = $FS::UID::AutoCommit;
3678 local $FS::UID::AutoCommit = 0;
3681 my $part_pkg = new FS::part_pkg ( {
3683 'comment' => $comment,
3684 #'setup' => $amount,
3687 'plandata' => "setup_fee=$amount",
3690 'taxclass' => $taxclass,
3693 my $error = $part_pkg->insert;
3695 $dbh->rollback if $oldAutoCommit;
3699 my $pkgpart = $part_pkg->pkgpart;
3700 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3701 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3702 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3703 $error = $type_pkgs->insert;
3705 $dbh->rollback if $oldAutoCommit;
3710 my $cust_pkg = new FS::cust_pkg ( {
3711 'custnum' => $self->custnum,
3712 'pkgpart' => $pkgpart,
3715 $error = $cust_pkg->insert;
3717 $dbh->rollback if $oldAutoCommit;
3721 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3728 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3734 sort { $a->_date <=> $b->_date }
3735 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3738 =item open_cust_bill
3740 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3745 sub open_cust_bill {
3747 grep { $_->owed > 0 } $self->cust_bill;
3752 Returns all the credits (see L<FS::cust_credit>) for this customer.
3758 sort { $a->_date <=> $b->_date }
3759 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3764 Returns all the payments (see L<FS::cust_pay>) for this customer.
3770 sort { $a->_date <=> $b->_date }
3771 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3776 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3782 sort { $a->_date <=> $b->_date }
3783 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3789 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3795 sort { $a->_date <=> $b->_date }
3796 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3799 =item select_for_update
3801 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3806 sub select_for_update {
3808 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3813 Returns a name string for this customer, either "Company (Last, First)" or
3820 my $name = $self->contact;
3821 $name = $self->company. " ($name)" if $self->company;
3827 Returns a name string for this (service/shipping) contact, either
3828 "Company (Last, First)" or "Last, First".
3834 if ( $self->get('ship_last') ) {
3835 my $name = $self->ship_contact;
3836 $name = $self->ship_company. " ($name)" if $self->ship_company;
3845 Returns this customer's full (billing) contact name only, "Last, First"
3851 $self->get('last'). ', '. $self->first;
3856 Returns this customer's full (shipping) contact name only, "Last, First"
3862 $self->get('ship_last')
3863 ? $self->get('ship_last'). ', '. $self->ship_first
3869 Returns this customer's full country name
3875 code2country($self->country);
3880 Returns a status string for this customer, currently:
3884 =item prospect - No packages have ever been ordered
3886 =item active - One or more recurring packages is active
3888 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3890 =item suspended - All non-cancelled recurring packages are suspended
3892 =item cancelled - All recurring packages are cancelled
3900 for my $status (qw( prospect active inactive suspended cancelled )) {
3901 my $method = $status.'_sql';
3902 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3903 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3904 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3905 return $status if $sth->fetchrow_arrayref->[0];
3911 Returns a hex triplet color string for this customer's status.
3915 use vars qw(%statuscolor);
3917 'prospect' => '7e0079', #'000000', #black? naw, purple
3918 'active' => '00CC00', #green
3919 'inactive' => '0000CC', #blue
3920 'suspended' => 'FF9900', #yellow
3921 'cancelled' => 'FF0000', #red
3926 $statuscolor{$self->status};
3931 =head1 CLASS METHODS
3937 Returns an SQL expression identifying prospective cust_main records (customers
3938 with no packages ever ordered)
3942 use vars qw($select_count_pkgs);
3943 $select_count_pkgs =
3944 "SELECT COUNT(*) FROM cust_pkg
3945 WHERE cust_pkg.custnum = cust_main.custnum";
3947 sub select_count_pkgs_sql {
3951 sub prospect_sql { "
3952 0 = ( $select_count_pkgs )
3957 Returns an SQL expression identifying active cust_main records (customers with
3958 no active recurring packages, but otherwise unsuspended/uncancelled).
3963 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
3969 Returns an SQL expression identifying inactive cust_main records (customers with
3970 active recurring packages).
3974 sub inactive_sql { "
3975 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3977 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
3983 Returns an SQL expression identifying suspended cust_main records.
3988 sub suspended_sql { susp_sql(@_); }
3990 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
3992 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3998 Returns an SQL expression identifying cancelled cust_main records.
4002 sub cancelled_sql { cancel_sql(@_); }
4005 my $recurring_sql = FS::cust_pkg->recurring_sql;
4006 #my $recurring_sql = "
4007 # '0' != ( select freq from part_pkg
4008 # where cust_pkg.pkgpart = part_pkg.pkgpart )
4012 0 < ( $select_count_pkgs )
4013 AND 0 = ( $select_count_pkgs AND $recurring_sql
4014 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4020 =item uncancelled_sql
4022 Returns an SQL expression identifying un-cancelled cust_main records.
4026 sub uncancelled_sql { uncancel_sql(@_); }
4027 sub uncancel_sql { "
4028 ( 0 < ( $select_count_pkgs
4029 AND ( cust_pkg.cancel IS NULL
4030 OR cust_pkg.cancel = 0
4033 OR 0 = ( $select_count_pkgs )
4037 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
4039 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
4040 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
4041 appropriate ship_ field is also searched).
4043 Additional options are the same as FS::Record::qsearch
4048 my( $self, $fuzzy, $hash, @opt) = @_;
4053 check_and_rebuild_fuzzyfiles();
4054 foreach my $field ( keys %$fuzzy ) {
4056 my $all = $self->all_X($field);
4057 next unless scalar(@$all);
4060 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
4063 foreach ( keys %match ) {
4064 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
4065 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
4068 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
4071 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
4073 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
4085 =item smart_search OPTION => VALUE ...
4087 Accepts the following options: I<search>, the string to search for. The string
4088 will be searched for as a customer number, phone number, name or company name,
4089 as an exact, or, in some cases, a substring or fuzzy match (see the source code
4090 for the exact heuristics used).
4092 Any additional options are treated as an additional qualifier on the search
4095 Returns a (possibly empty) array of FS::cust_main objects.
4102 #here is the agent virtualization
4103 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
4107 my $search = delete $options{'search'};
4108 ( my $alphanum_search = $search ) =~ s/\W//g;
4110 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
4112 #false laziness w/Record::ut_phone
4113 my $phonen = "$1-$2-$3";
4114 $phonen .= " x$4" if $4;
4116 push @cust_main, qsearch( {
4117 'table' => 'cust_main',
4118 'hashref' => { %options },
4119 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4121 join(' OR ', map "$_ = '$phonen'",
4122 qw( daytime night fax
4123 ship_daytime ship_night ship_fax )
4126 " AND $agentnums_sql", #agent virtualization
4129 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
4130 #try looking for matches with extensions unless one was specified
4132 push @cust_main, qsearch( {
4133 'table' => 'cust_main',
4134 'hashref' => { %options },
4135 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4137 join(' OR ', map "$_ LIKE '$phonen\%'",
4139 ship_daytime ship_night )
4142 " AND $agentnums_sql", #agent virtualization
4147 } elsif ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
4149 push @cust_main, qsearch( {
4150 'table' => 'cust_main',
4151 'hashref' => { 'custnum' => $1, %options },
4152 'extra_sql' => " AND $agentnums_sql", #agent virtualization
4155 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
4157 my($company, $last, $first) = ( $1, $2, $3 );
4159 # "Company (Last, First)"
4160 #this is probably something a browser remembered,
4161 #so just do an exact search
4163 foreach my $prefix ( '', 'ship_' ) {
4164 push @cust_main, qsearch( {
4165 'table' => 'cust_main',
4166 'hashref' => { $prefix.'first' => $first,
4167 $prefix.'last' => $last,
4168 $prefix.'company' => $company,
4171 'extra_sql' => " AND $agentnums_sql",
4175 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
4176 # try (ship_){last,company}
4180 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
4181 # # full strings the browser remembers won't work
4182 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
4184 use Lingua::EN::NameParse;
4185 my $NameParse = new Lingua::EN::NameParse(
4187 allow_reversed => 1,
4190 my($last, $first) = ( '', '' );
4191 #maybe disable this too and just rely on NameParse?
4192 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
4194 ($last, $first) = ( $1, $2 );
4196 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
4197 } elsif ( ! $NameParse->parse($value) ) {
4199 my %name = $NameParse->components;
4200 $first = $name{'given_name_1'};
4201 $last = $name{'surname_1'};
4205 if ( $first && $last ) {
4207 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
4210 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4212 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
4213 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
4216 push @cust_main, qsearch( {
4217 'table' => 'cust_main',
4218 'hashref' => \%options,
4219 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4222 # or it just be something that was typed in... (try that in a sec)
4226 my $q_value = dbh->quote($value);
4229 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4230 $sql .= " ( LOWER(last) = $q_value
4231 OR LOWER(company) = $q_value
4232 OR LOWER(ship_last) = $q_value
4233 OR LOWER(ship_company) = $q_value
4236 push @cust_main, qsearch( {
4237 'table' => 'cust_main',
4238 'hashref' => \%options,
4239 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4242 #always do substring & fuzzy,
4243 #getting complains searches are not returning enough
4244 #unless ( @cust_main ) { #no exact match, trying substring/fuzzy
4246 #still some false laziness w/ search/cust_main.cgi
4251 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
4252 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
4255 if ( $first && $last ) {
4258 { 'first' => { op=>'ILIKE', value=>"%$first%" },
4259 'last' => { op=>'ILIKE', value=>"%$last%" },
4261 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
4262 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
4269 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
4270 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
4274 foreach my $hashref ( @hashrefs ) {
4276 push @cust_main, qsearch( {
4277 'table' => 'cust_main',
4278 'hashref' => { %$hashref,
4281 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
4290 " AND $agentnums_sql", #extra_sql #agent virtualization
4293 if ( $first && $last ) {
4294 push @cust_main, FS::cust_main->fuzzy_search(
4295 { 'last' => $last, #fuzzy hashref
4296 'first' => $first }, #
4300 foreach my $field ( 'last', 'company' ) {
4302 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
4307 #eliminate duplicates
4309 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
4317 =item check_and_rebuild_fuzzyfiles
4321 use vars qw(@fuzzyfields);
4322 @fuzzyfields = ( 'last', 'first', 'company' );
4324 sub check_and_rebuild_fuzzyfiles {
4325 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4326 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
4329 =item rebuild_fuzzyfiles
4333 sub rebuild_fuzzyfiles {
4335 use Fcntl qw(:flock);
4337 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4338 mkdir $dir, 0700 unless -d $dir;
4340 foreach my $fuzzy ( @fuzzyfields ) {
4342 open(LOCK,">>$dir/cust_main.$fuzzy")
4343 or die "can't open $dir/cust_main.$fuzzy: $!";
4345 or die "can't lock $dir/cust_main.$fuzzy: $!";
4347 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
4348 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
4350 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
4351 my $sth = dbh->prepare("SELECT $field FROM cust_main".
4352 " WHERE $field != '' AND $field IS NOT NULL");
4353 $sth->execute or die $sth->errstr;
4355 while ( my $row = $sth->fetchrow_arrayref ) {
4356 print CACHE $row->[0]. "\n";
4361 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
4363 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
4374 my( $self, $field ) = @_;
4375 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4376 open(CACHE,"<$dir/cust_main.$field")
4377 or die "can't open $dir/cust_main.$field: $!";
4378 my @array = map { chomp; $_; } <CACHE>;
4383 =item append_fuzzyfiles LASTNAME COMPANY
4387 sub append_fuzzyfiles {
4388 #my( $first, $last, $company ) = @_;
4390 &check_and_rebuild_fuzzyfiles;
4392 use Fcntl qw(:flock);
4394 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4396 foreach my $field (qw( first last company )) {
4401 open(CACHE,">>$dir/cust_main.$field")
4402 or die "can't open $dir/cust_main.$field: $!";
4403 flock(CACHE,LOCK_EX)
4404 or die "can't lock $dir/cust_main.$field: $!";
4406 print CACHE "$value\n";
4408 flock(CACHE,LOCK_UN)
4409 or die "can't unlock $dir/cust_main.$field: $!";
4424 #warn join('-',keys %$param);
4425 my $fh = $param->{filehandle};
4426 my $agentnum = $param->{agentnum};
4428 my $refnum = $param->{refnum};
4429 my $pkgpart = $param->{pkgpart};
4431 #my @fields = @{$param->{fields}};
4432 my $format = $param->{'format'};
4435 if ( $format eq 'simple' ) {
4436 @fields = qw( cust_pkg.setup dayphone first last
4437 address1 address2 city state zip comments );
4439 } elsif ( $format eq 'extended' ) {
4440 @fields = qw( agent_custid refnum
4441 last first address1 address2 city state zip country
4443 ship_last ship_first ship_address1 ship_address2
4444 ship_city ship_state ship_zip ship_country
4445 payinfo paycvv paydate
4448 svc_acct.username svc_acct._password
4452 die "unknown format $format";
4455 eval "use Text::CSV_XS;";
4458 my $csv = new Text::CSV_XS;
4465 local $SIG{HUP} = 'IGNORE';
4466 local $SIG{INT} = 'IGNORE';
4467 local $SIG{QUIT} = 'IGNORE';
4468 local $SIG{TERM} = 'IGNORE';
4469 local $SIG{TSTP} = 'IGNORE';
4470 local $SIG{PIPE} = 'IGNORE';
4472 my $oldAutoCommit = $FS::UID::AutoCommit;
4473 local $FS::UID::AutoCommit = 0;
4476 #while ( $columns = $csv->getline($fh) ) {
4478 while ( defined($line=<$fh>) ) {
4480 $csv->parse($line) or do {
4481 $dbh->rollback if $oldAutoCommit;
4482 return "can't parse: ". $csv->error_input();
4485 my @columns = $csv->fields();
4486 #warn join('-',@columns);
4489 agentnum => $agentnum,
4491 country => $conf->config('countrydefault') || 'US',
4492 payby => $payby, #default
4493 paydate => '12/2037', #default
4495 my $billtime = time;
4496 my %cust_pkg = ( pkgpart => $pkgpart );
4498 foreach my $field ( @fields ) {
4500 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|expire|cancel)$/ ) {
4502 #$cust_pkg{$1} = str2time( shift @$columns );
4503 if ( $1 eq 'pkgpart' ) {
4504 $cust_pkg{$1} = shift @columns;
4505 } elsif ( $1 eq 'setup' ) {
4506 $billtime = str2time(shift @columns);
4508 $cust_pkg{$1} = str2time( shift @columns );
4511 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
4513 $svc_acct{$1} = shift @columns;
4517 #refnum interception
4518 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
4520 my $referral = $columns[0];
4521 my %hash = ( 'referral' => $referral,
4522 'agentnum' => $agentnum,
4526 my $part_referral = qsearchs('part_referral', \%hash )
4527 || new FS::part_referral \%hash;
4529 unless ( $part_referral->refnum ) {
4530 my $error = $part_referral->insert;
4532 $dbh->rollback if $oldAutoCommit;
4533 return "can't auto-insert advertising source: $referral: $error";
4537 $columns[0] = $part_referral->refnum;
4540 #$cust_main{$field} = shift @$columns;
4541 $cust_main{$field} = shift @columns;
4545 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
4547 my $invoicing_list = $cust_main{'invoicing_list'}
4548 ? [ delete $cust_main{'invoicing_list'} ]
4551 my $cust_main = new FS::cust_main ( \%cust_main );
4554 tie my %hash, 'Tie::RefHash'; #this part is important
4556 if ( $cust_pkg{'pkgpart'} ) {
4557 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
4560 if ( $svc_acct{'username'} ) {
4561 my $part_pkg = $cust_pkg->part_pkg;
4562 unless ( $part_pkg ) {
4563 $dbh->rollback if $oldAutoCommit;
4564 return "unknown pkgnum ". $cust_pkg{'pkgpart'};
4566 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
4567 push @svc_acct, new FS::svc_acct ( \%svc_acct )
4570 $hash{$cust_pkg} = \@svc_acct;
4573 my $error = $cust_main->insert( \%hash, $invoicing_list );
4576 $dbh->rollback if $oldAutoCommit;
4577 return "can't insert customer for $line: $error";
4580 if ( $format eq 'simple' ) {
4582 #false laziness w/bill.cgi
4583 $error = $cust_main->bill( 'time' => $billtime );
4585 $dbh->rollback if $oldAutoCommit;
4586 return "can't bill customer for $line: $error";
4589 $cust_main->apply_payments;
4590 $cust_main->apply_credits;
4592 $error = $cust_main->collect();
4594 $dbh->rollback if $oldAutoCommit;
4595 return "can't collect customer for $line: $error";
4603 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4605 return "Empty file!" unless $imported;
4617 #warn join('-',keys %$param);
4618 my $fh = $param->{filehandle};
4619 my @fields = @{$param->{fields}};
4621 eval "use Text::CSV_XS;";
4624 my $csv = new Text::CSV_XS;
4631 local $SIG{HUP} = 'IGNORE';
4632 local $SIG{INT} = 'IGNORE';
4633 local $SIG{QUIT} = 'IGNORE';
4634 local $SIG{TERM} = 'IGNORE';
4635 local $SIG{TSTP} = 'IGNORE';
4636 local $SIG{PIPE} = 'IGNORE';
4638 my $oldAutoCommit = $FS::UID::AutoCommit;
4639 local $FS::UID::AutoCommit = 0;
4642 #while ( $columns = $csv->getline($fh) ) {
4644 while ( defined($line=<$fh>) ) {
4646 $csv->parse($line) or do {
4647 $dbh->rollback if $oldAutoCommit;
4648 return "can't parse: ". $csv->error_input();
4651 my @columns = $csv->fields();
4652 #warn join('-',@columns);
4655 foreach my $field ( @fields ) {
4656 $row{$field} = shift @columns;
4659 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4660 unless ( $cust_main ) {
4661 $dbh->rollback if $oldAutoCommit;
4662 return "unknown custnum $row{'custnum'}";
4665 if ( $row{'amount'} > 0 ) {
4666 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4668 $dbh->rollback if $oldAutoCommit;
4672 } elsif ( $row{'amount'} < 0 ) {
4673 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4676 $dbh->rollback if $oldAutoCommit;
4686 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4688 return "Empty file!" unless $imported;
4700 The delete method should possibly take an FS::cust_main object reference
4701 instead of a scalar customer number.
4703 Bill and collect options should probably be passed as references instead of a
4706 There should probably be a configuration file with a list of allowed credit
4709 No multiple currency support (probably a larger project than just this module).
4711 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4713 Birthdates rely on negative epoch values.
4717 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4718 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4719 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.