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 my $error = $self->SUPER::insert;
402 $dbh->rollback if $oldAutoCommit;
403 #return "inserting cust_main record (transaction rolled back): $error";
407 warn " setting invoicing list\n"
410 if ( $invoicing_list ) {
411 $error = $self->check_invoicing_list( $invoicing_list );
413 $dbh->rollback if $oldAutoCommit;
414 return "checking invoicing_list (transaction rolled back): $error";
416 $self->invoicing_list( $invoicing_list );
419 if ( $conf->config('cust_main-skeleton_tables')
420 && $conf->config('cust_main-skeleton_custnum') ) {
422 warn " inserting skeleton records\n"
425 my $error = $self->start_copy_skel;
427 $dbh->rollback if $oldAutoCommit;
433 warn " ordering packages\n"
436 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
438 $dbh->rollback if $oldAutoCommit;
443 $dbh->rollback if $oldAutoCommit;
444 return "No svc_acct record to apply pre-paid time";
448 warn " inserting initial $payby payment of $amount\n"
450 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
452 $dbh->rollback if $oldAutoCommit;
453 return "inserting payment (transaction rolled back): $error";
457 unless ( $import || $skip_fuzzyfiles ) {
458 warn " queueing fuzzyfiles update\n"
460 $error = $self->queue_fuzzyfiles_update;
462 $dbh->rollback if $oldAutoCommit;
463 return "updating fuzzy search cache: $error";
467 warn " insert complete; committing transaction\n"
470 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
475 sub start_copy_skel {
478 #'mg_user_preference' => {},
479 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
480 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
481 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
482 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
483 my @tables = eval($conf->config_binary('cust_main-skeleton_tables'));
486 _copy_skel( 'cust_main', #tablename
487 $conf->config('cust_main-skeleton_custnum'), #sourceid
488 $self->custnum, #destid
489 @tables, #child tables
493 #recursive subroutine, not a method
495 my( $table, $sourceid, $destid, %child_tables ) = @_;
498 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
499 ( $table, $primary_key ) = ( $1, $2 );
501 my $dbdef_table = dbdef->table($table);
502 $primary_key = $dbdef_table->primary_key
503 or return "$table has no primary key".
504 " (or do you need to run dbdef-create?)";
507 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
508 join (', ', keys %child_tables). "\n"
511 foreach my $child_table_def ( keys %child_tables ) {
515 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
516 ( $child_table, $child_pkey ) = ( $1, $2 );
518 $child_table = $child_table_def;
520 $child_pkey = dbdef->table($child_table)->primary_key;
521 # or return "$table has no primary key".
522 # " (or do you need to run dbdef-create?)\n";
526 if ( keys %{ $child_tables{$child_table_def} } ) {
528 return "$child_table has no primary key".
529 " (run dbdef-create or try specifying it?)\n"
532 #false laziness w/Record::insert and only works on Pg
533 #refactor the proper last-inserted-id stuff out of Record::insert if this
534 # ever gets use for anything besides a quick kludge for one customer
535 my $default = dbdef->table($child_table)->column($child_pkey)->default;
536 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
537 or return "can't parse $child_table.$child_pkey default value ".
538 " for sequence name: $default";
543 my @sel_columns = grep { $_ ne $primary_key }
544 dbdef->table($child_table)->columns;
545 my $sel_columns = join(', ', @sel_columns );
547 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
548 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
549 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
551 my $sel_st = "SELECT $sel_columns FROM $child_table".
552 " WHERE $primary_key = $sourceid";
555 my $sel_sth = dbh->prepare( $sel_st )
556 or return dbh->errstr;
558 $sel_sth->execute or return $sel_sth->errstr;
560 while ( my $row = $sel_sth->fetchrow_hashref ) {
562 warn " selected row: ".
563 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
567 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
568 my $ins_sth =dbh->prepare($statement)
569 or return dbh->errstr;
570 my @param = ( $destid, map $row->{$_}, @ins_columns );
571 warn " $statement: [ ". join(', ', @param). " ]\n"
573 $ins_sth->execute( @param )
574 or return $ins_sth->errstr;
576 #next unless keys %{ $child_tables{$child_table} };
577 next unless $sequence;
579 #another section of that laziness
580 my $seq_sql = "SELECT currval('$sequence')";
581 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
582 $seq_sth->execute or return $seq_sth->errstr;
583 my $insertid = $seq_sth->fetchrow_arrayref->[0];
585 # don't drink soap! recurse! recurse! okay!
587 _copy_skel( $child_table_def,
588 $row->{$child_pkey}, #sourceid
590 %{ $child_tables{$child_table_def} },
592 return $error if $error;
602 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
604 Like the insert method on an existing record, this method orders a package
605 and included services atomicaly. Pass a Tie::RefHash data structure to this
606 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
607 be a better explanation of this, but until then, here's an example:
610 tie %hash, 'Tie::RefHash'; #this part is important
612 $cust_pkg => [ $svc_acct ],
615 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
617 Services can be new, in which case they are inserted, or existing unaudited
618 services, in which case they are linked to the newly-created package.
620 Currently available options are: I<depend_jobnum> and I<noexport>.
622 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
623 on the supplied jobnum (they will not run until the specific job completes).
624 This can be used to defer provisioning until some action completes (such
625 as running the customer's credit card successfully).
627 The I<noexport> option is deprecated. If I<noexport> is set true, no
628 provisioning jobs (exports) are scheduled. (You can schedule them later with
629 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
630 on the cust_main object is not recommended, as existing services will also be
637 my $cust_pkgs = shift;
640 my %svc_options = ();
641 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
642 if exists $options{'depend_jobnum'};
643 warn "$me order_pkgs called with options ".
644 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
647 local $SIG{HUP} = 'IGNORE';
648 local $SIG{INT} = 'IGNORE';
649 local $SIG{QUIT} = 'IGNORE';
650 local $SIG{TERM} = 'IGNORE';
651 local $SIG{TSTP} = 'IGNORE';
652 local $SIG{PIPE} = 'IGNORE';
654 my $oldAutoCommit = $FS::UID::AutoCommit;
655 local $FS::UID::AutoCommit = 0;
658 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
660 foreach my $cust_pkg ( keys %$cust_pkgs ) {
661 $cust_pkg->custnum( $self->custnum );
662 my $error = $cust_pkg->insert;
664 $dbh->rollback if $oldAutoCommit;
665 return "inserting cust_pkg (transaction rolled back): $error";
667 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
668 if ( $svc_something->svcnum ) {
669 my $old_cust_svc = $svc_something->cust_svc;
670 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
671 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
672 $error = $new_cust_svc->replace($old_cust_svc);
674 $svc_something->pkgnum( $cust_pkg->pkgnum );
675 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
676 $svc_something->seconds( $svc_something->seconds + $$seconds );
679 $error = $svc_something->insert(%svc_options);
682 $dbh->rollback if $oldAutoCommit;
683 #return "inserting svc_ (transaction rolled back): $error";
689 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
693 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF ]
695 Recharges this (existing) customer with the specified prepaid card (see
696 L<FS::prepay_credit>), specified either by I<identifier> or as an
697 FS::prepay_credit object. If there is an error, returns the error, otherwise
700 Optionally, two scalar references can be passed as well. They will have their
701 values filled in with the amount and number of seconds applied by this prepaid
706 sub recharge_prepay {
707 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
709 local $SIG{HUP} = 'IGNORE';
710 local $SIG{INT} = 'IGNORE';
711 local $SIG{QUIT} = 'IGNORE';
712 local $SIG{TERM} = 'IGNORE';
713 local $SIG{TSTP} = 'IGNORE';
714 local $SIG{PIPE} = 'IGNORE';
716 my $oldAutoCommit = $FS::UID::AutoCommit;
717 local $FS::UID::AutoCommit = 0;
720 my( $amount, $seconds ) = ( 0, 0 );
722 my $error = $self->get_prepay($prepay_credit, \$amount, \$seconds)
723 || $self->increment_seconds($seconds)
724 || $self->insert_cust_pay_prepay( $amount,
726 ? $prepay_credit->identifier
731 $dbh->rollback if $oldAutoCommit;
735 if ( defined($amountref) ) { $$amountref = $amount; }
736 if ( defined($secondsref) ) { $$secondsref = $seconds; }
738 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
743 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
745 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
746 specified either by I<identifier> or as an FS::prepay_credit object.
748 References to I<amount> and I<seconds> scalars should be passed as arguments
749 and will be incremented by the values of the prepaid card.
751 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
752 check or set this customer's I<agentnum>.
754 If there is an error, returns the error, otherwise returns false.
760 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
762 local $SIG{HUP} = 'IGNORE';
763 local $SIG{INT} = 'IGNORE';
764 local $SIG{QUIT} = 'IGNORE';
765 local $SIG{TERM} = 'IGNORE';
766 local $SIG{TSTP} = 'IGNORE';
767 local $SIG{PIPE} = 'IGNORE';
769 my $oldAutoCommit = $FS::UID::AutoCommit;
770 local $FS::UID::AutoCommit = 0;
773 unless ( ref($prepay_credit) ) {
775 my $identifier = $prepay_credit;
777 $prepay_credit = qsearchs(
779 { 'identifier' => $prepay_credit },
784 unless ( $prepay_credit ) {
785 $dbh->rollback if $oldAutoCommit;
786 return "Invalid prepaid card: ". $identifier;
791 if ( $prepay_credit->agentnum ) {
792 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
793 $dbh->rollback if $oldAutoCommit;
794 return "prepaid card not valid for agent ". $self->agentnum;
796 $self->agentnum($prepay_credit->agentnum);
799 my $error = $prepay_credit->delete;
801 $dbh->rollback if $oldAutoCommit;
802 return "removing prepay_credit (transaction rolled back): $error";
805 $$amountref += $prepay_credit->amount;
806 $$secondsref += $prepay_credit->seconds;
808 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
813 =item increment_seconds SECONDS
815 Updates this customer's single or primary account (see L<FS::svc_acct>) by
816 the specified number of seconds. If there is an error, returns the error,
817 otherwise returns false.
821 sub increment_seconds {
822 my( $self, $seconds ) = @_;
823 warn "$me increment_seconds called: $seconds seconds\n"
826 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
827 $self->ncancelled_pkgs;
830 return 'No packages with primary or single services found'.
831 ' to apply pre-paid time';
832 } elsif ( scalar(@cust_pkg) > 1 ) {
833 #maybe have a way to specify the package/account?
834 return 'Multiple packages found to apply pre-paid time';
837 my $cust_pkg = $cust_pkg[0];
838 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
842 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
845 return 'No account found to apply pre-paid time';
846 } elsif ( scalar(@cust_svc) > 1 ) {
847 return 'Multiple accounts found to apply pre-paid time';
850 my $svc_acct = $cust_svc[0]->svc_x;
851 warn " found service svcnum ". $svc_acct->pkgnum.
852 ' ('. $svc_acct->email. ")\n"
855 $svc_acct->increment_seconds($seconds);
859 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
861 Inserts a prepayment in the specified amount for this customer. An optional
862 second argument can specify the prepayment identifier for tracking purposes.
863 If there is an error, returns the error, otherwise returns false.
867 sub insert_cust_pay_prepay {
868 shift->insert_cust_pay('PREP', @_);
871 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
873 Inserts a cash payment in the specified amount for this customer. An optional
874 second argument can specify the payment identifier for tracking purposes.
875 If there is an error, returns the error, otherwise returns false.
879 sub insert_cust_pay_cash {
880 shift->insert_cust_pay('CASH', @_);
883 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
885 Inserts a Western Union payment in the specified amount for this customer. An
886 optional second argument can specify the prepayment identifier for tracking
887 purposes. If there is an error, returns the error, otherwise returns false.
891 sub insert_cust_pay_west {
892 shift->insert_cust_pay('WEST', @_);
895 sub insert_cust_pay {
896 my( $self, $payby, $amount ) = splice(@_, 0, 3);
897 my $payinfo = scalar(@_) ? shift : '';
899 my $cust_pay = new FS::cust_pay {
900 'custnum' => $self->custnum,
901 'paid' => sprintf('%.2f', $amount),
902 #'_date' => #date the prepaid card was purchased???
904 'payinfo' => $payinfo,
912 This method is deprecated. See the I<depend_jobnum> option to the insert and
913 order_pkgs methods for a better way to defer provisioning.
915 Re-schedules all exports by calling the B<reexport> method of all associated
916 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
917 otherwise returns false.
924 carp "WARNING: FS::cust_main::reexport is deprectated; ".
925 "use the depend_jobnum option to insert or order_pkgs to delay export";
927 local $SIG{HUP} = 'IGNORE';
928 local $SIG{INT} = 'IGNORE';
929 local $SIG{QUIT} = 'IGNORE';
930 local $SIG{TERM} = 'IGNORE';
931 local $SIG{TSTP} = 'IGNORE';
932 local $SIG{PIPE} = 'IGNORE';
934 my $oldAutoCommit = $FS::UID::AutoCommit;
935 local $FS::UID::AutoCommit = 0;
938 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
939 my $error = $cust_pkg->reexport;
941 $dbh->rollback if $oldAutoCommit;
946 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
951 =item delete NEW_CUSTNUM
953 This deletes the customer. If there is an error, returns the error, otherwise
956 This will completely remove all traces of the customer record. This is not
957 what you want when a customer cancels service; for that, cancel all of the
958 customer's packages (see L</cancel>).
960 If the customer has any uncancelled packages, you need to pass a new (valid)
961 customer number for those packages to be transferred to. Cancelled packages
962 will be deleted. Did I mention that this is NOT what you want when a customer
963 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
965 You can't delete a customer with invoices (see L<FS::cust_bill>),
966 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
967 refunds (see L<FS::cust_refund>).
974 local $SIG{HUP} = 'IGNORE';
975 local $SIG{INT} = 'IGNORE';
976 local $SIG{QUIT} = 'IGNORE';
977 local $SIG{TERM} = 'IGNORE';
978 local $SIG{TSTP} = 'IGNORE';
979 local $SIG{PIPE} = 'IGNORE';
981 my $oldAutoCommit = $FS::UID::AutoCommit;
982 local $FS::UID::AutoCommit = 0;
985 if ( $self->cust_bill ) {
986 $dbh->rollback if $oldAutoCommit;
987 return "Can't delete a customer with invoices";
989 if ( $self->cust_credit ) {
990 $dbh->rollback if $oldAutoCommit;
991 return "Can't delete a customer with credits";
993 if ( $self->cust_pay ) {
994 $dbh->rollback if $oldAutoCommit;
995 return "Can't delete a customer with payments";
997 if ( $self->cust_refund ) {
998 $dbh->rollback if $oldAutoCommit;
999 return "Can't delete a customer with refunds";
1002 my @cust_pkg = $self->ncancelled_pkgs;
1004 my $new_custnum = shift;
1005 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1006 $dbh->rollback if $oldAutoCommit;
1007 return "Invalid new customer number: $new_custnum";
1009 foreach my $cust_pkg ( @cust_pkg ) {
1010 my %hash = $cust_pkg->hash;
1011 $hash{'custnum'} = $new_custnum;
1012 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1013 my $error = $new_cust_pkg->replace($cust_pkg);
1015 $dbh->rollback if $oldAutoCommit;
1020 my @cancelled_cust_pkg = $self->all_pkgs;
1021 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1022 my $error = $cust_pkg->delete;
1024 $dbh->rollback if $oldAutoCommit;
1029 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1030 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1032 my $error = $cust_main_invoice->delete;
1034 $dbh->rollback if $oldAutoCommit;
1039 my $error = $self->SUPER::delete;
1041 $dbh->rollback if $oldAutoCommit;
1045 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1050 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1052 Replaces the OLD_RECORD with this one in the database. If there is an error,
1053 returns the error, otherwise returns false.
1055 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1056 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1057 expected and rollback the entire transaction; it is not necessary to call
1058 check_invoicing_list first. Here's an example:
1060 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1068 warn "$me replace called\n"
1071 local $SIG{HUP} = 'IGNORE';
1072 local $SIG{INT} = 'IGNORE';
1073 local $SIG{QUIT} = 'IGNORE';
1074 local $SIG{TERM} = 'IGNORE';
1075 local $SIG{TSTP} = 'IGNORE';
1076 local $SIG{PIPE} = 'IGNORE';
1078 # If the mask is blank then try to set it - if we can...
1079 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
1080 $self->paymask($self->payinfo);
1083 # We absolutely have to have an old vs. new record to make this work.
1084 if (!defined($old)) {
1085 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1088 my $curuser = $FS::CurrentUser::CurrentUser;
1089 if ( $self->payby eq 'COMP'
1090 && $self->payby ne $old->payby
1091 && ! $curuser->access_right('Complimentary customer')
1094 return "You are not permitted to create complimentary accounts.";
1097 local($ignore_expired_card) = 1
1098 if $old->payby =~ /^(CARD|DCRD)$/
1099 && $self->payby =~ /^(CARD|DCRD)$/
1100 && $old->payinfo eq $self->payinfo;
1102 my $oldAutoCommit = $FS::UID::AutoCommit;
1103 local $FS::UID::AutoCommit = 0;
1106 my $error = $self->SUPER::replace($old);
1109 $dbh->rollback if $oldAutoCommit;
1113 if ( @param ) { # INVOICING_LIST_ARYREF
1114 my $invoicing_list = shift @param;
1115 $error = $self->check_invoicing_list( $invoicing_list );
1117 $dbh->rollback if $oldAutoCommit;
1120 $self->invoicing_list( $invoicing_list );
1123 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1124 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1125 # card/check/lec info has changed, want to retry realtime_ invoice events
1126 my $error = $self->retry_realtime;
1128 $dbh->rollback if $oldAutoCommit;
1133 unless ( $import || $skip_fuzzyfiles ) {
1134 $error = $self->queue_fuzzyfiles_update;
1136 $dbh->rollback if $oldAutoCommit;
1137 return "updating fuzzy search cache: $error";
1141 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1146 =item queue_fuzzyfiles_update
1148 Used by insert & replace to update the fuzzy search cache
1152 sub queue_fuzzyfiles_update {
1155 local $SIG{HUP} = 'IGNORE';
1156 local $SIG{INT} = 'IGNORE';
1157 local $SIG{QUIT} = 'IGNORE';
1158 local $SIG{TERM} = 'IGNORE';
1159 local $SIG{TSTP} = 'IGNORE';
1160 local $SIG{PIPE} = 'IGNORE';
1162 my $oldAutoCommit = $FS::UID::AutoCommit;
1163 local $FS::UID::AutoCommit = 0;
1166 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1167 my $error = $queue->insert( map $self->getfield($_),
1168 qw(first last company)
1171 $dbh->rollback if $oldAutoCommit;
1172 return "queueing job (transaction rolled back): $error";
1175 if ( $self->ship_last ) {
1176 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1177 $error = $queue->insert( map $self->getfield("ship_$_"),
1178 qw(first last company)
1181 $dbh->rollback if $oldAutoCommit;
1182 return "queueing job (transaction rolled back): $error";
1186 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1193 Checks all fields to make sure this is a valid customer record. If there is
1194 an error, returns the error, otherwise returns false. Called by the insert
1195 and replace methods.
1202 warn "$me check BEFORE: \n". $self->_dump
1206 $self->ut_numbern('custnum')
1207 || $self->ut_number('agentnum')
1208 || $self->ut_textn('agent_custid')
1209 || $self->ut_number('refnum')
1210 || $self->ut_name('last')
1211 || $self->ut_name('first')
1212 || $self->ut_snumbern('birthdate')
1213 || $self->ut_textn('company')
1214 || $self->ut_text('address1')
1215 || $self->ut_textn('address2')
1216 || $self->ut_text('city')
1217 || $self->ut_textn('county')
1218 || $self->ut_textn('state')
1219 || $self->ut_country('country')
1220 || $self->ut_anything('comments')
1221 || $self->ut_numbern('referral_custnum')
1223 #barf. need message catalogs. i18n. etc.
1224 $error .= "Please select an advertising source."
1225 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1226 return $error if $error;
1228 return "Unknown agent"
1229 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1231 return "Unknown refnum"
1232 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1234 return "Unknown referring custnum: ". $self->referral_custnum
1235 unless ! $self->referral_custnum
1236 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1238 if ( $self->ss eq '' ) {
1243 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1244 or return "Illegal social security number: ". $self->ss;
1245 $self->ss("$1-$2-$3");
1249 # bad idea to disable, causes billing to fail because of no tax rates later
1250 # unless ( $import ) {
1251 unless ( qsearch('cust_main_county', {
1252 'country' => $self->country,
1255 return "Unknown state/county/country: ".
1256 $self->state. "/". $self->county. "/". $self->country
1257 unless qsearch('cust_main_county',{
1258 'state' => $self->state,
1259 'county' => $self->county,
1260 'country' => $self->country,
1266 $self->ut_phonen('daytime', $self->country)
1267 || $self->ut_phonen('night', $self->country)
1268 || $self->ut_phonen('fax', $self->country)
1269 || $self->ut_zip('zip', $self->country)
1271 return $error if $error;
1274 last first company address1 address2 city county state zip
1275 country daytime night fax
1278 if ( defined $self->dbdef_table->column('ship_last') ) {
1279 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1281 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1285 $self->ut_name('ship_last')
1286 || $self->ut_name('ship_first')
1287 || $self->ut_textn('ship_company')
1288 || $self->ut_text('ship_address1')
1289 || $self->ut_textn('ship_address2')
1290 || $self->ut_text('ship_city')
1291 || $self->ut_textn('ship_county')
1292 || $self->ut_textn('ship_state')
1293 || $self->ut_country('ship_country')
1295 return $error if $error;
1297 #false laziness with above
1298 unless ( qsearchs('cust_main_county', {
1299 'country' => $self->ship_country,
1302 return "Unknown ship_state/ship_county/ship_country: ".
1303 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1304 unless qsearch('cust_main_county',{
1305 'state' => $self->ship_state,
1306 'county' => $self->ship_county,
1307 'country' => $self->ship_country,
1313 $self->ut_phonen('ship_daytime', $self->ship_country)
1314 || $self->ut_phonen('ship_night', $self->ship_country)
1315 || $self->ut_phonen('ship_fax', $self->ship_country)
1316 || $self->ut_zip('ship_zip', $self->ship_country)
1318 return $error if $error;
1320 } else { # ship_ info eq billing info, so don't store dup info in database
1321 $self->setfield("ship_$_", '')
1322 foreach qw( last first company address1 address2 city county state zip
1323 country daytime night fax );
1327 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1328 or return "Illegal payby: ". $self->payby;
1330 $error = $self->ut_numbern('paystart_month')
1331 || $self->ut_numbern('paystart_year')
1332 || $self->ut_numbern('payissue')
1334 return $error if $error;
1336 if ( $self->payip eq '' ) {
1339 $error = $self->ut_ip('payip');
1340 return $error if $error;
1343 # If it is encrypted and the private key is not availaible then we can't
1344 # check the credit card.
1346 my $check_payinfo = 1;
1348 if ($self->is_encrypted($self->payinfo)) {
1354 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1356 my $payinfo = $self->payinfo;
1357 $payinfo =~ s/\D//g;
1358 $payinfo =~ /^(\d{13,16})$/
1359 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1361 $self->payinfo($payinfo);
1363 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1365 return gettext('unknown_card_type')
1366 if cardtype($self->payinfo) eq "Unknown";
1368 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1370 return 'Banned credit card: banned on '.
1371 time2str('%a %h %o at %r', $ban->_date).
1372 ' by '. $ban->otaker.
1373 ' (ban# '. $ban->bannum. ')';
1376 if ( defined $self->dbdef_table->column('paycvv') ) {
1377 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1378 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1379 $self->paycvv =~ /^(\d{4})$/
1380 or return "CVV2 (CID) for American Express cards is four digits.";
1383 $self->paycvv =~ /^(\d{3})$/
1384 or return "CVV2 (CVC2/CID) is three digits.";
1392 my $cardtype = cardtype($payinfo);
1393 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1395 return "Start date or issue number is required for $cardtype cards"
1396 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1398 return "Start month must be between 1 and 12"
1399 if $self->paystart_month
1400 and $self->paystart_month < 1 || $self->paystart_month > 12;
1402 return "Start year must be 1990 or later"
1403 if $self->paystart_year
1404 and $self->paystart_year < 1990;
1406 return "Issue number must be beween 1 and 99"
1408 and $self->payissue < 1 || $self->payissue > 99;
1411 $self->paystart_month('');
1412 $self->paystart_year('');
1413 $self->payissue('');
1416 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1418 my $payinfo = $self->payinfo;
1419 $payinfo =~ s/[^\d\@]//g;
1420 if ( $conf->exists('echeck-nonus') ) {
1421 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1422 $payinfo = "$1\@$2";
1424 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1425 $payinfo = "$1\@$2";
1427 $self->payinfo($payinfo);
1428 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1430 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1432 return 'Banned ACH account: banned on '.
1433 time2str('%a %h %o at %r', $ban->_date).
1434 ' by '. $ban->otaker.
1435 ' (ban# '. $ban->bannum. ')';
1438 } elsif ( $self->payby eq 'LECB' ) {
1440 my $payinfo = $self->payinfo;
1441 $payinfo =~ s/\D//g;
1442 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1444 $self->payinfo($payinfo);
1445 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1447 } elsif ( $self->payby eq 'BILL' ) {
1449 $error = $self->ut_textn('payinfo');
1450 return "Illegal P.O. number: ". $self->payinfo if $error;
1451 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1453 } elsif ( $self->payby eq 'COMP' ) {
1455 my $curuser = $FS::CurrentUser::CurrentUser;
1456 if ( ! $self->custnum
1457 && ! $curuser->access_right('Complimentary customer')
1460 return "You are not permitted to create complimentary accounts."
1463 $error = $self->ut_textn('payinfo');
1464 return "Illegal comp account issuer: ". $self->payinfo if $error;
1465 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1467 } elsif ( $self->payby eq 'PREPAY' ) {
1469 my $payinfo = $self->payinfo;
1470 $payinfo =~ s/\W//g; #anything else would just confuse things
1471 $self->payinfo($payinfo);
1472 $error = $self->ut_alpha('payinfo');
1473 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1474 return "Unknown prepayment identifier"
1475 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1476 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1480 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1481 return "Expiration date required"
1482 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1486 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1487 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1488 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1489 ( $m, $y ) = ( $3, "20$2" );
1491 return "Illegal expiration date: ". $self->paydate;
1493 $self->paydate("$y-$m-01");
1494 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1495 return gettext('expired_card')
1497 && !$ignore_expired_card
1498 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1501 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1502 ( ! $conf->exists('require_cardname')
1503 || $self->payby !~ /^(CARD|DCRD)$/ )
1505 $self->payname( $self->first. " ". $self->getfield('last') );
1507 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1508 or return gettext('illegal_name'). " payname: ". $self->payname;
1512 foreach my $flag (qw( tax spool_cdr )) {
1513 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1517 $self->otaker(getotaker) unless $self->otaker;
1519 warn "$me check AFTER: \n". $self->_dump
1522 $self->SUPER::check;
1527 Returns all packages (see L<FS::cust_pkg>) for this customer.
1533 if ( $self->{'_pkgnum'} ) {
1534 values %{ $self->{'_pkgnum'}->cache };
1536 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1540 =item ncancelled_pkgs
1542 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1546 sub ncancelled_pkgs {
1548 if ( $self->{'_pkgnum'} ) {
1549 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1551 @{ [ # force list context
1552 qsearch( 'cust_pkg', {
1553 'custnum' => $self->custnum,
1556 qsearch( 'cust_pkg', {
1557 'custnum' => $self->custnum,
1564 =item suspended_pkgs
1566 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1570 sub suspended_pkgs {
1572 grep { $_->susp } $self->ncancelled_pkgs;
1575 =item unflagged_suspended_pkgs
1577 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1578 customer (thouse packages without the `manual_flag' set).
1582 sub unflagged_suspended_pkgs {
1584 return $self->suspended_pkgs
1585 unless dbdef->table('cust_pkg')->column('manual_flag');
1586 grep { ! $_->manual_flag } $self->suspended_pkgs;
1589 =item unsuspended_pkgs
1591 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1596 sub unsuspended_pkgs {
1598 grep { ! $_->susp } $self->ncancelled_pkgs;
1601 =item num_cancelled_pkgs
1603 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1608 sub num_cancelled_pkgs {
1610 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1614 my( $self, $sql ) = @_;
1615 my $sth = dbh->prepare(
1616 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1617 ) or die dbh->errstr;
1618 $sth->execute($self->custnum) or die $sth->errstr;
1619 $sth->fetchrow_arrayref->[0];
1624 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1625 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1626 on success or a list of errors.
1632 grep { $_->unsuspend } $self->suspended_pkgs;
1637 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1639 Returns a list: an empty list on success or a list of errors.
1645 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1648 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1650 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1651 PKGPARTs (see L<FS::part_pkg>).
1653 Returns a list: an empty list on success or a list of errors.
1657 sub suspend_if_pkgpart {
1659 my (@pkgparts, %opt);
1660 if (ref($_[0]) eq 'HASH'){
1661 @pkgparts = @{$_[0]{pkgparts}};
1666 grep { $_->suspend(%opt) }
1667 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1668 $self->unsuspended_pkgs;
1671 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1673 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1674 listed PKGPARTs (see L<FS::part_pkg>).
1676 Returns a list: an empty list on success or a list of errors.
1680 sub suspend_unless_pkgpart {
1682 my (@pkgparts, %opt);
1683 if (ref($_[0]) eq 'HASH'){
1684 @pkgparts = @{$_[0]{pkgparts}};
1689 grep { $_->suspend(%opt) }
1690 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1691 $self->unsuspended_pkgs;
1694 =item cancel [ OPTION => VALUE ... ]
1696 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1698 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1700 I<quiet> can be set true to supress email cancellation notices.
1702 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1704 I<ban> can be set true to ban this customer's credit card or ACH information,
1707 Always returns a list: an empty list on success or a list of errors.
1715 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1717 #should try decryption (we might have the private key)
1718 # and if not maybe queue a job for the server that does?
1719 return ( "Can't (yet) ban encrypted credit cards" )
1720 if $self->is_encrypted($self->payinfo);
1722 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1723 my $error = $ban->insert;
1724 return ( $error ) if $error;
1728 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1731 sub _banned_pay_hashref {
1742 'payby' => $payby2ban{$self->payby},
1743 'payinfo' => md5_base64($self->payinfo),
1750 Returns all notes (see L<FS::cust_main_note>) for this customer.
1757 qsearch( 'cust_main_note',
1758 { 'custnum' => $self->custnum },
1760 'ORDER BY _DATE DESC'
1766 Returns the agent (see L<FS::agent>) for this customer.
1772 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1777 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1778 conjunction with the collect method.
1780 Options are passed as name-value pairs.
1782 Currently available options are:
1784 resetup - if set true, re-charges setup fees.
1786 time - bills the customer as if it were that time. Specified as a UNIX
1787 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1788 L<Date::Parse> for conversion functions. For example:
1792 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1795 If there is an error, returns the error, otherwise returns false.
1800 my( $self, %options ) = @_;
1801 return '' if $self->payby eq 'COMP';
1802 warn "$me bill customer ". $self->custnum. "\n"
1805 my $time = $options{'time'} || time;
1810 local $SIG{HUP} = 'IGNORE';
1811 local $SIG{INT} = 'IGNORE';
1812 local $SIG{QUIT} = 'IGNORE';
1813 local $SIG{TERM} = 'IGNORE';
1814 local $SIG{TSTP} = 'IGNORE';
1815 local $SIG{PIPE} = 'IGNORE';
1817 my $oldAutoCommit = $FS::UID::AutoCommit;
1818 local $FS::UID::AutoCommit = 0;
1821 $self->select_for_update; #mutex
1823 #create a new invoice
1824 #(we'll remove it later if it doesn't actually need to be generated [contains
1825 # no line items] and we're inside a transaciton so nothing else will see it)
1826 my $cust_bill = new FS::cust_bill ( {
1827 'custnum' => $self->custnum,
1829 #'charged' => $charged,
1832 $error = $cust_bill->insert;
1834 $dbh->rollback if $oldAutoCommit;
1835 return "can't create invoice for customer #". $self->custnum. ": $error";
1837 my $invnum = $cust_bill->invnum;
1840 # find the packages which are due for billing, find out how much they are
1841 # & generate invoice database.
1844 my( $total_setup, $total_recur ) = ( 0, 0 );
1846 my @precommit_hooks = ();
1848 foreach my $cust_pkg (
1849 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1852 #NO!! next if $cust_pkg->cancel;
1853 next if $cust_pkg->getfield('cancel');
1855 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1857 #? to avoid use of uninitialized value errors... ?
1858 $cust_pkg->setfield('bill', '')
1859 unless defined($cust_pkg->bill);
1861 my $part_pkg = $cust_pkg->part_pkg;
1863 my %hash = $cust_pkg->hash;
1864 my $old_cust_pkg = new FS::cust_pkg \%hash;
1873 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1875 warn " bill setup\n" if $DEBUG > 1;
1877 $setup = eval { $cust_pkg->calc_setup( $time ) };
1879 $dbh->rollback if $oldAutoCommit;
1880 return "$@ running calc_setup for $cust_pkg\n";
1883 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1887 # bill recurring fee
1892 if ( $part_pkg->getfield('freq') ne '0' &&
1893 ! $cust_pkg->getfield('susp') &&
1894 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1897 warn " bill recur\n" if $DEBUG > 1;
1899 # XXX shared with $recur_prog
1900 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1902 #over two params! lets at least switch to a hashref for the rest...
1903 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
1905 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
1907 $dbh->rollback if $oldAutoCommit;
1908 return "$@ running calc_recur for $cust_pkg\n";
1911 #change this bit to use Date::Manip? CAREFUL with timezones (see
1912 # mailing list archive)
1913 my ($sec,$min,$hour,$mday,$mon,$year) =
1914 (localtime($sdate) )[0,1,2,3,4,5];
1916 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1917 # only for figuring next bill date, nothing else, so, reset $sdate again
1919 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1920 $cust_pkg->last_bill($sdate)
1921 if $cust_pkg->dbdef_table->column('last_bill');
1923 if ( $part_pkg->freq =~ /^\d+$/ ) {
1924 $mon += $part_pkg->freq;
1925 until ( $mon < 12 ) { $mon -= 12; $year++; }
1926 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1928 $mday += $weeks * 7;
1929 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1932 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
1936 $dbh->rollback if $oldAutoCommit;
1937 return "unparsable frequency: ". $part_pkg->freq;
1939 $cust_pkg->setfield('bill',
1940 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1943 warn "\$setup is undefined" unless defined($setup);
1944 warn "\$recur is undefined" unless defined($recur);
1945 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1948 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
1951 if ( $cust_pkg->modified ) {
1953 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
1956 $error=$cust_pkg->replace($old_cust_pkg);
1957 if ( $error ) { #just in case
1958 $dbh->rollback if $oldAutoCommit;
1959 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1962 $setup = sprintf( "%.2f", $setup );
1963 $recur = sprintf( "%.2f", $recur );
1964 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1965 $dbh->rollback if $oldAutoCommit;
1966 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1968 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1969 $dbh->rollback if $oldAutoCommit;
1970 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1973 if ( $setup != 0 || $recur != 0 ) {
1975 warn " charges (setup=$setup, recur=$recur); adding line items\n"
1977 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1978 'invnum' => $invnum,
1979 'pkgnum' => $cust_pkg->pkgnum,
1983 'edate' => $cust_pkg->bill,
1984 'details' => \@details,
1986 $error = $cust_bill_pkg->insert;
1988 $dbh->rollback if $oldAutoCommit;
1989 return "can't create invoice line item for invoice #$invnum: $error";
1991 $total_setup += $setup;
1992 $total_recur += $recur;
1998 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2001 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2004 my %taxhash = map { $_ => $self->get("$prefix$_") }
2005 qw( state county country );
2007 $taxhash{'taxclass'} = $part_pkg->taxclass;
2009 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2012 $taxhash{'taxclass'} = '';
2013 @taxes = qsearch( 'cust_main_county', \%taxhash );
2016 #one more try at a whole-country tax rate
2018 $taxhash{$_} = '' foreach qw( state county );
2019 @taxes = qsearch( 'cust_main_county', \%taxhash );
2022 # maybe eliminate this entirely, along with all the 0% records
2024 $dbh->rollback if $oldAutoCommit;
2026 "fatal: can't find tax rate for state/county/country/taxclass ".
2027 join('/', ( map $self->get("$prefix$_"),
2028 qw(state county country)
2030 $part_pkg->taxclass ). "\n";
2033 foreach my $tax ( @taxes ) {
2035 my $taxable_charged = 0;
2036 $taxable_charged += $setup
2037 unless $part_pkg->setuptax =~ /^Y$/i
2038 || $tax->setuptax =~ /^Y$/i;
2039 $taxable_charged += $recur
2040 unless $part_pkg->recurtax =~ /^Y$/i
2041 || $tax->recurtax =~ /^Y$/i;
2042 next unless $taxable_charged;
2044 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2045 #my ($mon,$year) = (localtime($sdate) )[4,5];
2046 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2048 my $freq = $part_pkg->freq || 1;
2049 if ( $freq !~ /(\d+)$/ ) {
2050 $dbh->rollback if $oldAutoCommit;
2051 return "daily/weekly package definitions not (yet?)".
2052 " compatible with monthly tax exemptions";
2054 my $taxable_per_month =
2055 sprintf("%.2f", $taxable_charged / $freq );
2057 #call the whole thing off if this customer has any old
2058 #exemption records...
2059 my @cust_tax_exempt =
2060 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2061 if ( @cust_tax_exempt ) {
2062 $dbh->rollback if $oldAutoCommit;
2064 'this customer still has old-style tax exemption records; '.
2065 'run bin/fs-migrate-cust_tax_exempt?';
2068 foreach my $which_month ( 1 .. $freq ) {
2070 #maintain the new exemption table now
2073 FROM cust_tax_exempt_pkg
2074 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2075 LEFT JOIN cust_bill USING ( invnum )
2081 my $sth = dbh->prepare($sql) or do {
2082 $dbh->rollback if $oldAutoCommit;
2083 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2091 $dbh->rollback if $oldAutoCommit;
2092 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2094 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2096 my $remaining_exemption =
2097 $tax->exempt_amount - $existing_exemption;
2098 if ( $remaining_exemption > 0 ) {
2099 my $addl = $remaining_exemption > $taxable_per_month
2100 ? $taxable_per_month
2101 : $remaining_exemption;
2102 $taxable_charged -= $addl;
2104 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2105 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2106 'taxnum' => $tax->taxnum,
2107 'year' => 1900+$year,
2109 'amount' => sprintf("%.2f", $addl ),
2111 $error = $cust_tax_exempt_pkg->insert;
2113 $dbh->rollback if $oldAutoCommit;
2114 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2116 } # if $remaining_exemption > 0
2120 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2121 until ( $mon < 13 ) { $mon -= 12; $year++; }
2123 } #foreach $which_month
2125 } #if $tax->exempt_amount
2127 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2129 #$tax += $taxable_charged * $cust_main_county->tax / 100
2130 $tax{ $tax->taxname || 'Tax' } +=
2131 $taxable_charged * $tax->tax / 100
2133 } #foreach my $tax ( @taxes )
2135 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2137 } #if $setup != 0 || $recur != 0
2139 } #if $cust_pkg->modified
2141 } #foreach my $cust_pkg
2143 unless ( $cust_bill->cust_bill_pkg ) {
2144 $cust_bill->delete; #don't create an invoice w/o line items
2145 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2149 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2151 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2152 my $tax = sprintf("%.2f", $tax{$taxname} );
2153 $charged = sprintf( "%.2f", $charged+$tax );
2155 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2156 'invnum' => $invnum,
2162 'itemdesc' => $taxname,
2164 $error = $cust_bill_pkg->insert;
2166 $dbh->rollback if $oldAutoCommit;
2167 return "can't create invoice line item for invoice #$invnum: $error";
2169 $total_setup += $tax;
2173 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2174 $error = $cust_bill->replace;
2176 $dbh->rollback if $oldAutoCommit;
2177 return "can't update charged for invoice #$invnum: $error";
2180 foreach my $hook ( @precommit_hooks ) {
2182 &{$hook}; #($self) ?
2185 $dbh->rollback if $oldAutoCommit;
2186 return "$@ running precommit hook $hook\n";
2190 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2194 =item collect OPTIONS
2196 (Attempt to) collect money for this customer's outstanding invoices (see
2197 L<FS::cust_bill>). Usually used after the bill method.
2199 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2200 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2201 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2203 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2204 and the invoice events web interface.
2206 If there is an error, returns the error, otherwise returns false.
2208 Options are passed as name-value pairs.
2210 Currently available options are:
2212 invoice_time - Use this time when deciding when to print invoices and
2213 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>
2214 for conversion functions.
2216 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2219 quiet - set true to surpress email card/ACH decline notices.
2221 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2224 payby - allows for one time override of normal customer billing method
2229 my( $self, %options ) = @_;
2230 my $invoice_time = $options{'invoice_time'} || time;
2233 local $SIG{HUP} = 'IGNORE';
2234 local $SIG{INT} = 'IGNORE';
2235 local $SIG{QUIT} = 'IGNORE';
2236 local $SIG{TERM} = 'IGNORE';
2237 local $SIG{TSTP} = 'IGNORE';
2238 local $SIG{PIPE} = 'IGNORE';
2240 my $oldAutoCommit = $FS::UID::AutoCommit;
2241 local $FS::UID::AutoCommit = 0;
2244 $self->select_for_update; #mutex
2246 my $balance = $self->balance;
2247 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2249 unless ( $balance > 0 ) { #redundant?????
2250 $dbh->rollback if $oldAutoCommit; #hmm
2254 if ( exists($options{'retry_card'}) ) {
2255 carp 'retry_card option passed to collect is deprecated; use retry';
2256 $options{'retry'} ||= $options{'retry_card'};
2258 if ( exists($options{'retry'}) && $options{'retry'} ) {
2259 my $error = $self->retry_realtime;
2261 $dbh->rollback if $oldAutoCommit;
2267 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2268 $extra_sql = " AND freq = '1m' ";
2270 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2273 foreach my $cust_bill ( $self->open_cust_bill ) {
2275 # don't try to charge for the same invoice if it's already in a batch
2276 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2278 last if $self->balance <= 0;
2280 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2283 foreach my $part_bill_event ( due_events ( $cust_bill,
2284 exists($options{'payby'})
2290 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2291 || $self->balance <= 0; # or if balance<=0
2294 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2295 warn " do_event " . $cust_bill . " ". (%options) . "\n"
2298 if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2299 # gah, even with transactions.
2300 $dbh->commit if $oldAutoCommit; #well.
2309 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2314 =item retry_realtime
2316 Schedules realtime / batch credit card / electronic check / LEC billing
2317 events for for retry. Useful if card information has changed or manual
2318 retry is desired. The 'collect' method must be called to actually retry
2321 Implementation details: For each of this customer's open invoices, changes
2322 the status of the first "done" (with statustext error) realtime processing
2327 sub retry_realtime {
2330 local $SIG{HUP} = 'IGNORE';
2331 local $SIG{INT} = 'IGNORE';
2332 local $SIG{QUIT} = 'IGNORE';
2333 local $SIG{TERM} = 'IGNORE';
2334 local $SIG{TSTP} = 'IGNORE';
2335 local $SIG{PIPE} = 'IGNORE';
2337 my $oldAutoCommit = $FS::UID::AutoCommit;
2338 local $FS::UID::AutoCommit = 0;
2341 foreach my $cust_bill (
2342 grep { $_->cust_bill_event }
2343 $self->open_cust_bill
2345 my @cust_bill_event =
2346 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2348 #$_->part_bill_event->plan eq 'realtime-card'
2349 $_->part_bill_event->eventcode =~
2350 /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2351 && $_->status eq 'done'
2354 $cust_bill->cust_bill_event;
2355 next unless @cust_bill_event;
2356 my $error = $cust_bill_event[0]->retry;
2358 $dbh->rollback if $oldAutoCommit;
2359 return "error scheduling invoice event for retry: $error";
2364 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2369 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2371 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2372 via a Business::OnlinePayment realtime gateway. See
2373 L<http://420.am/business-onlinepayment> for supported gateways.
2375 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2377 Available options are: I<description>, I<invnum>, I<quiet>
2379 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2380 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2381 if set, will override the value from the customer record.
2383 I<description> is a free-text field passed to the gateway. It defaults to
2384 "Internet services".
2386 If an I<invnum> is specified, this payment (if successful) is applied to the
2387 specified invoice. If you don't specify an I<invnum> you might want to
2388 call the B<apply_payments> method.
2390 I<quiet> can be set true to surpress email decline notices.
2392 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2397 my( $self, $method, $amount, %options ) = @_;
2399 warn "$me realtime_bop: $method $amount\n";
2400 warn " $_ => $options{$_}\n" foreach keys %options;
2403 $options{'description'} ||= 'Internet services';
2405 eval "use Business::OnlinePayment";
2408 my $payinfo = exists($options{'payinfo'})
2409 ? $options{'payinfo'}
2417 if ( $options{'invnum'} ) {
2418 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2419 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2421 map { $_->part_pkg->taxclass }
2423 map { $_->cust_pkg }
2424 $cust_bill->cust_bill_pkg;
2425 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2426 #different taxclasses
2427 $taxclass = $taxclasses[0];
2431 #look for an agent gateway override first
2433 if ( $method eq 'CC' ) {
2434 $cardtype = cardtype($payinfo);
2435 } elsif ( $method eq 'ECHECK' ) {
2438 $cardtype = $method;
2442 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2443 cardtype => $cardtype,
2444 taxclass => $taxclass, } )
2445 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2447 taxclass => $taxclass, } )
2448 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2449 cardtype => $cardtype,
2451 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2453 taxclass => '', } );
2455 my $payment_gateway = '';
2456 my( $processor, $login, $password, $action, @bop_options );
2457 if ( $override ) { #use a payment gateway override
2459 $payment_gateway = $override->payment_gateway;
2461 $processor = $payment_gateway->gateway_module;
2462 $login = $payment_gateway->gateway_username;
2463 $password = $payment_gateway->gateway_password;
2464 $action = $payment_gateway->gateway_action;
2465 @bop_options = $payment_gateway->options;
2467 } else { #use the standard settings from the config
2469 ( $processor, $login, $password, $action, @bop_options ) =
2470 $self->default_payment_gateway($method);
2478 my $address = exists($options{'address1'})
2479 ? $options{'address1'}
2481 my $address2 = exists($options{'address2'})
2482 ? $options{'address2'}
2484 $address .= ", ". $address2 if length($address2);
2486 my $o_payname = exists($options{'payname'})
2487 ? $options{'payname'}
2489 my($payname, $payfirst, $paylast);
2490 if ( $o_payname && $method ne 'ECHECK' ) {
2491 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2492 or return "Illegal payname $payname";
2493 ($payfirst, $paylast) = ($1, $2);
2495 $payfirst = $self->getfield('first');
2496 $paylast = $self->getfield('last');
2497 $payname = "$payfirst $paylast";
2500 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2501 if ( $conf->exists('emailinvoiceauto')
2502 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2503 push @invoicing_list, $self->all_emails;
2506 my $email = ($conf->exists('business-onlinepayment-email-override'))
2507 ? $conf->config('business-onlinepayment-email-override')
2508 : $invoicing_list[0];
2512 my $payip = exists($options{'payip'})
2515 $content{customer_ip} = $payip
2518 if ( $method eq 'CC' ) {
2520 $content{card_number} = $payinfo;
2521 my $paydate = exists($options{'paydate'})
2522 ? $options{'paydate'}
2524 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2525 $content{expiration} = "$2/$1";
2527 my $paycvv = exists($options{'paycvv'})
2528 ? $options{'paycvv'}
2530 $content{cvv2} = $self->paycvv
2533 my $paystart_month = exists($options{'paystart_month'})
2534 ? $options{'paystart_month'}
2535 : $self->paystart_month;
2537 my $paystart_year = exists($options{'paystart_year'})
2538 ? $options{'paystart_year'}
2539 : $self->paystart_year;
2541 $content{card_start} = "$paystart_month/$paystart_year"
2542 if $paystart_month && $paystart_year;
2544 my $payissue = exists($options{'payissue'})
2545 ? $options{'payissue'}
2547 $content{issue_number} = $payissue if $payissue;
2549 $content{recurring_billing} = 'YES'
2550 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2552 'payinfo' => $payinfo,
2555 } elsif ( $method eq 'ECHECK' ) {
2556 ( $content{account_number}, $content{routing_code} ) =
2557 split('@', $payinfo);
2558 $content{bank_name} = $o_payname;
2559 $content{account_type} = 'CHECKING';
2560 $content{account_name} = $payname;
2561 $content{customer_org} = $self->company ? 'B' : 'I';
2562 $content{customer_ssn} = exists($options{'ss'})
2565 } elsif ( $method eq 'LEC' ) {
2566 $content{phone} = $payinfo;
2570 # run transaction(s)
2573 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2575 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2576 $transaction->content(
2579 'password' => $password,
2580 'action' => $action1,
2581 'description' => $options{'description'},
2582 'amount' => $amount,
2583 'invoice_number' => $options{'invnum'},
2584 'customer_id' => $self->custnum,
2585 'last_name' => $paylast,
2586 'first_name' => $payfirst,
2588 'address' => $address,
2589 'city' => ( exists($options{'city'})
2592 'state' => ( exists($options{'state'})
2595 'zip' => ( exists($options{'zip'})
2598 'country' => ( exists($options{'country'})
2599 ? $options{'country'}
2601 'referer' => 'http://cleanwhisker.420.am/',
2603 'phone' => $self->daytime || $self->night,
2606 $transaction->submit();
2608 if ( $transaction->is_success() && $action2 ) {
2609 my $auth = $transaction->authorization;
2610 my $ordernum = $transaction->can('order_number')
2611 ? $transaction->order_number
2615 new Business::OnlinePayment( $processor, @bop_options );
2622 password => $password,
2623 order_number => $ordernum,
2625 authorization => $auth,
2626 description => $options{'description'},
2629 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2630 transaction_sequence_num local_transaction_date
2631 local_transaction_time AVS_result_code )) {
2632 $capture{$field} = $transaction->$field() if $transaction->can($field);
2635 $capture->content( %capture );
2639 unless ( $capture->is_success ) {
2640 my $e = "Authorization successful but capture failed, custnum #".
2641 $self->custnum. ': '. $capture->result_code.
2642 ": ". $capture->error_message;
2650 # remove paycvv after initial transaction
2653 #false laziness w/misc/process/payment.cgi - check both to make sure working
2655 if ( defined $self->dbdef_table->column('paycvv')
2656 && length($self->paycvv)
2657 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2659 my $error = $self->remove_cvv;
2661 warn "WARNING: error removing cvv: $error\n";
2669 if ( $transaction->is_success() ) {
2671 my %method2payby = (
2678 if ( $payment_gateway ) { # agent override
2679 $paybatch = $payment_gateway->gatewaynum. '-';
2682 $paybatch .= "$processor:". $transaction->authorization;
2684 $paybatch .= ':'. $transaction->order_number
2685 if $transaction->can('order_number')
2686 && length($transaction->order_number);
2688 my $cust_pay = new FS::cust_pay ( {
2689 'custnum' => $self->custnum,
2690 'invnum' => $options{'invnum'},
2693 'payby' => $method2payby{$method},
2694 'payinfo' => $payinfo,
2695 'paybatch' => $paybatch,
2697 my $error = $cust_pay->insert;
2699 $cust_pay->invnum(''); #try again with no specific invnum
2700 my $error2 = $cust_pay->insert;
2702 # gah, even with transactions.
2703 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2704 "error inserting payment ($processor): $error2".
2705 " (previously tried insert with invnum #$options{'invnum'}" .
2711 return ''; #no error
2715 my $perror = "$processor error: ". $transaction->error_message;
2717 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2718 && $conf->exists('emaildecline')
2719 && grep { $_ ne 'POST' } $self->invoicing_list
2720 && ! grep { $transaction->error_message =~ /$_/ }
2721 $conf->config('emaildecline-exclude')
2723 my @templ = $conf->config('declinetemplate');
2724 my $template = new Text::Template (
2726 SOURCE => [ map "$_\n", @templ ],
2727 ) or return "($perror) can't create template: $Text::Template::ERROR";
2728 $template->compile()
2729 or return "($perror) can't compile template: $Text::Template::ERROR";
2731 my $templ_hash = { error => $transaction->error_message };
2733 my $error = send_email(
2734 'from' => $conf->config('invoice_from'),
2735 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2736 'subject' => 'Your payment could not be processed',
2737 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2740 $perror .= " (also received error sending decline notification: $error)"
2750 =item default_payment_gateway
2754 sub default_payment_gateway {
2755 my( $self, $method ) = @_;
2757 die "Real-time processing not enabled\n"
2758 unless $conf->exists('business-onlinepayment');
2761 my $bop_config = 'business-onlinepayment';
2762 $bop_config .= '-ach'
2763 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2764 my ( $processor, $login, $password, $action, @bop_options ) =
2765 $conf->config($bop_config);
2766 $action ||= 'normal authorization';
2767 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2768 die "No real-time processor is enabled - ".
2769 "did you set the business-onlinepayment configuration value?\n"
2772 ( $processor, $login, $password, $action, @bop_options )
2777 Removes the I<paycvv> field from the database directly.
2779 If there is an error, returns the error, otherwise returns false.
2785 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2786 or return dbh->errstr;
2787 $sth->execute($self->custnum)
2788 or return $sth->errstr;
2793 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2795 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2796 via a Business::OnlinePayment realtime gateway. See
2797 L<http://420.am/business-onlinepayment> for supported gateways.
2799 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2801 Available options are: I<amount>, I<reason>, I<paynum>
2803 Most gateways require a reference to an original payment transaction to refund,
2804 so you probably need to specify a I<paynum>.
2806 I<amount> defaults to the original amount of the payment if not specified.
2808 I<reason> specifies a reason for the refund.
2810 Implementation note: If I<amount> is unspecified or equal to the amount of the
2811 orignal payment, first an attempt is made to "void" the transaction via
2812 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2813 the normal attempt is made to "refund" ("credit") the transaction via the
2814 gateway is attempted.
2816 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2817 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2818 #if set, will override the value from the customer record.
2820 #If an I<invnum> is specified, this payment (if successful) is applied to the
2821 #specified invoice. If you don't specify an I<invnum> you might want to
2822 #call the B<apply_payments> method.
2826 #some false laziness w/realtime_bop, not enough to make it worth merging
2827 #but some useful small subs should be pulled out
2828 sub realtime_refund_bop {
2829 my( $self, $method, %options ) = @_;
2831 warn "$me realtime_refund_bop: $method refund\n";
2832 warn " $_ => $options{$_}\n" foreach keys %options;
2835 eval "use Business::OnlinePayment";
2839 # look up the original payment and optionally a gateway for that payment
2843 my $amount = $options{'amount'};
2845 my( $processor, $login, $password, @bop_options ) ;
2846 my( $auth, $order_number ) = ( '', '', '' );
2848 if ( $options{'paynum'} ) {
2850 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
2851 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2852 or return "Unknown paynum $options{'paynum'}";
2853 $amount ||= $cust_pay->paid;
2855 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2856 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2857 $cust_pay->paybatch;
2858 my $gatewaynum = '';
2859 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2861 if ( $gatewaynum ) { #gateway for the payment to be refunded
2863 my $payment_gateway =
2864 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2865 die "payment gateway $gatewaynum not found"
2866 unless $payment_gateway;
2868 $processor = $payment_gateway->gateway_module;
2869 $login = $payment_gateway->gateway_username;
2870 $password = $payment_gateway->gateway_password;
2871 @bop_options = $payment_gateway->options;
2873 } else { #try the default gateway
2875 my( $conf_processor, $unused_action );
2876 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2877 $self->default_payment_gateway($method);
2879 return "processor of payment $options{'paynum'} $processor does not".
2880 " match default processor $conf_processor"
2881 unless $processor eq $conf_processor;
2886 } else { # didn't specify a paynum, so look for agent gateway overrides
2887 # like a normal transaction
2890 if ( $method eq 'CC' ) {
2891 $cardtype = cardtype($self->payinfo);
2892 } elsif ( $method eq 'ECHECK' ) {
2895 $cardtype = $method;
2898 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2899 cardtype => $cardtype,
2901 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2903 taxclass => '', } );
2905 if ( $override ) { #use a payment gateway override
2907 my $payment_gateway = $override->payment_gateway;
2909 $processor = $payment_gateway->gateway_module;
2910 $login = $payment_gateway->gateway_username;
2911 $password = $payment_gateway->gateway_password;
2912 #$action = $payment_gateway->gateway_action;
2913 @bop_options = $payment_gateway->options;
2915 } else { #use the standard settings from the config
2918 ( $processor, $login, $password, $unused_action, @bop_options ) =
2919 $self->default_payment_gateway($method);
2924 return "neither amount nor paynum specified" unless $amount;
2929 'password' => $password,
2930 'order_number' => $order_number,
2931 'amount' => $amount,
2932 'referer' => 'http://cleanwhisker.420.am/',
2934 $content{authorization} = $auth
2935 if length($auth); #echeck/ACH transactions have an order # but no auth
2936 #(at least with authorize.net)
2938 #first try void if applicable
2939 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2940 warn " attempting void\n" if $DEBUG > 1;
2941 my $void = new Business::OnlinePayment( $processor, @bop_options );
2942 $void->content( 'action' => 'void', %content );
2944 if ( $void->is_success ) {
2945 my $error = $cust_pay->void($options{'reason'});
2947 # gah, even with transactions.
2948 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2949 "error voiding payment: $error";
2953 warn " void successful\n" if $DEBUG > 1;
2958 warn " void unsuccessful, trying refund\n"
2962 my $address = $self->address1;
2963 $address .= ", ". $self->address2 if $self->address2;
2965 my($payname, $payfirst, $paylast);
2966 if ( $self->payname && $method ne 'ECHECK' ) {
2967 $payname = $self->payname;
2968 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2969 or return "Illegal payname $payname";
2970 ($payfirst, $paylast) = ($1, $2);
2972 $payfirst = $self->getfield('first');
2973 $paylast = $self->getfield('last');
2974 $payname = "$payfirst $paylast";
2977 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2978 if ( $conf->exists('emailinvoiceauto')
2979 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2980 push @invoicing_list, $self->all_emails;
2983 my $email = ($conf->exists('business-onlinepayment-email-override'))
2984 ? $conf->config('business-onlinepayment-email-override')
2985 : $invoicing_list[0];
2987 my $payip = exists($options{'payip'})
2990 $content{customer_ip} = $payip
2994 if ( $method eq 'CC' ) {
2997 $content{card_number} = $payinfo = $cust_pay->payinfo;
2998 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2999 #$content{expiration} = "$2/$1";
3001 $content{card_number} = $payinfo = $self->payinfo;
3002 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3003 $content{expiration} = "$2/$1";
3006 } elsif ( $method eq 'ECHECK' ) {
3007 ( $content{account_number}, $content{routing_code} ) =
3008 split('@', $payinfo = $self->payinfo);
3009 $content{bank_name} = $self->payname;
3010 $content{account_type} = 'CHECKING';
3011 $content{account_name} = $payname;
3012 $content{customer_org} = $self->company ? 'B' : 'I';
3013 $content{customer_ssn} = $self->ss;
3014 } elsif ( $method eq 'LEC' ) {
3015 $content{phone} = $payinfo = $self->payinfo;
3019 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3020 my %sub_content = $refund->content(
3021 'action' => 'credit',
3022 'customer_id' => $self->custnum,
3023 'last_name' => $paylast,
3024 'first_name' => $payfirst,
3026 'address' => $address,
3027 'city' => $self->city,
3028 'state' => $self->state,
3029 'zip' => $self->zip,
3030 'country' => $self->country,
3032 'phone' => $self->daytime || $self->night,
3035 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3039 return "$processor error: ". $refund->error_message
3040 unless $refund->is_success();
3042 my %method2payby = (
3048 my $paybatch = "$processor:". $refund->authorization;
3049 $paybatch .= ':'. $refund->order_number
3050 if $refund->can('order_number') && $refund->order_number;
3052 while ( $cust_pay && $cust_pay->unappled < $amount ) {
3053 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3054 last unless @cust_bill_pay;
3055 my $cust_bill_pay = pop @cust_bill_pay;
3056 my $error = $cust_bill_pay->delete;
3060 my $cust_refund = new FS::cust_refund ( {
3061 'custnum' => $self->custnum,
3062 'paynum' => $options{'paynum'},
3063 'refund' => $amount,
3065 'payby' => $method2payby{$method},
3066 'payinfo' => $payinfo,
3067 'paybatch' => $paybatch,
3068 'reason' => $options{'reason'} || 'card or ACH refund',
3070 my $error = $cust_refund->insert;
3072 $cust_refund->paynum(''); #try again with no specific paynum
3073 my $error2 = $cust_refund->insert;
3075 # gah, even with transactions.
3076 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3077 "error inserting refund ($processor): $error2".
3078 " (previously tried insert with paynum #$options{'paynum'}" .
3091 Returns the total owed for this customer on all invoices
3092 (see L<FS::cust_bill/owed>).
3098 $self->total_owed_date(2145859200); #12/31/2037
3101 =item total_owed_date TIME
3103 Returns the total owed for this customer on all invoices with date earlier than
3104 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3105 see L<Time::Local> and L<Date::Parse> for conversion functions.
3109 sub total_owed_date {
3113 foreach my $cust_bill (
3114 grep { $_->_date <= $time }
3115 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3117 $total_bill += $cust_bill->owed;
3119 sprintf( "%.2f", $total_bill );
3122 =item apply_credits OPTION => VALUE ...
3124 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3125 to outstanding invoice balances in chronological order (or reverse
3126 chronological order if the I<order> option is set to B<newest>) and returns the
3127 value of any remaining unapplied credits available for refund (see
3128 L<FS::cust_refund>).
3136 return 0 unless $self->total_credited;
3138 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3139 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3141 my @invoices = $self->open_cust_bill;
3142 @invoices = sort { $b->_date <=> $a->_date } @invoices
3143 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3146 foreach my $cust_bill ( @invoices ) {
3149 if ( !defined($credit) || $credit->credited == 0) {
3150 $credit = pop @credits or last;
3153 if ($cust_bill->owed >= $credit->credited) {
3154 $amount=$credit->credited;
3156 $amount=$cust_bill->owed;
3159 my $cust_credit_bill = new FS::cust_credit_bill ( {
3160 'crednum' => $credit->crednum,
3161 'invnum' => $cust_bill->invnum,
3162 'amount' => $amount,
3164 my $error = $cust_credit_bill->insert;
3165 die $error if $error;
3167 redo if ($cust_bill->owed > 0);
3171 return $self->total_credited;
3174 =item apply_payments
3176 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3177 to outstanding invoice balances in chronological order.
3179 #and returns the value of any remaining unapplied payments.
3183 sub apply_payments {
3188 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3189 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3191 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3192 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3196 foreach my $cust_bill ( @invoices ) {
3199 if ( !defined($payment) || $payment->unapplied == 0 ) {
3200 $payment = pop @payments or last;
3203 if ( $cust_bill->owed >= $payment->unapplied ) {
3204 $amount = $payment->unapplied;
3206 $amount = $cust_bill->owed;
3209 my $cust_bill_pay = new FS::cust_bill_pay ( {
3210 'paynum' => $payment->paynum,
3211 'invnum' => $cust_bill->invnum,
3212 'amount' => $amount,
3214 my $error = $cust_bill_pay->insert;
3215 die $error if $error;
3217 redo if ( $cust_bill->owed > 0);
3221 return $self->total_unapplied_payments;
3224 =item total_credited
3226 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3227 customer. See L<FS::cust_credit/credited>.
3231 sub total_credited {
3233 my $total_credit = 0;
3234 foreach my $cust_credit ( qsearch('cust_credit', {
3235 'custnum' => $self->custnum,
3237 $total_credit += $cust_credit->credited;
3239 sprintf( "%.2f", $total_credit );
3242 =item total_unapplied_payments
3244 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3245 See L<FS::cust_pay/unapplied>.
3249 sub total_unapplied_payments {
3251 my $total_unapplied = 0;
3252 foreach my $cust_pay ( qsearch('cust_pay', {
3253 'custnum' => $self->custnum,
3255 $total_unapplied += $cust_pay->unapplied;
3257 sprintf( "%.2f", $total_unapplied );
3262 Returns the balance for this customer (total_owed minus total_credited
3263 minus total_unapplied_payments).
3270 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
3274 =item balance_date TIME
3276 Returns the balance for this customer, only considering invoices with date
3277 earlier than TIME (total_owed_date minus total_credited minus
3278 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3279 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3288 $self->total_owed_date($time)
3289 - $self->total_credited
3290 - $self->total_unapplied_payments
3294 =item in_transit_payments
3296 Returns the total of requests for payments for this customer pending in
3297 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3301 sub in_transit_payments {
3303 my $in_transit_payments = 0;
3304 foreach my $pay_batch ( qsearch('pay_batch', {
3307 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3308 'batchnum' => $pay_batch->batchnum,
3309 'custnum' => $self->custnum,
3311 $in_transit_payments += $cust_pay_batch->amount;
3314 sprintf( "%.2f", $in_transit_payments );
3317 =item paydate_monthyear
3319 Returns a two-element list consisting of the month and year of this customer's
3320 paydate (credit card expiration date for CARD customers)
3324 sub paydate_monthyear {
3326 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3328 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3335 =item payinfo_masked
3337 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.
3339 Credit Cards - Mask all but the last four characters.
3340 Checks - Mask all but last 2 of account number and bank routing number.
3341 Others - Do nothing, return the unmasked string.
3345 sub payinfo_masked {
3347 return $self->paymask;
3350 =item invoicing_list [ ARRAYREF ]
3352 If an arguement is given, sets these email addresses as invoice recipients
3353 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3354 (except as warnings), so use check_invoicing_list first.
3356 Returns a list of email addresses (with svcnum entries expanded).
3358 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3359 check it without disturbing anything by passing nothing.
3361 This interface may change in the future.
3365 sub invoicing_list {
3366 my( $self, $arrayref ) = @_;
3369 my @cust_main_invoice;
3370 if ( $self->custnum ) {
3371 @cust_main_invoice =
3372 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3374 @cust_main_invoice = ();
3376 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3377 #warn $cust_main_invoice->destnum;
3378 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3379 #warn $cust_main_invoice->destnum;
3380 my $error = $cust_main_invoice->delete;
3381 warn $error if $error;
3384 if ( $self->custnum ) {
3385 @cust_main_invoice =
3386 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3388 @cust_main_invoice = ();
3390 my %seen = map { $_->address => 1 } @cust_main_invoice;
3391 foreach my $address ( @{$arrayref} ) {
3392 next if exists $seen{$address} && $seen{$address};
3393 $seen{$address} = 1;
3394 my $cust_main_invoice = new FS::cust_main_invoice ( {
3395 'custnum' => $self->custnum,
3398 my $error = $cust_main_invoice->insert;
3399 warn $error if $error;
3403 if ( $self->custnum ) {
3405 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3412 =item check_invoicing_list ARRAYREF
3414 Checks these arguements as valid input for the invoicing_list method. If there
3415 is an error, returns the error, otherwise returns false.
3419 sub check_invoicing_list {
3420 my( $self, $arrayref ) = @_;
3421 foreach my $address ( @{$arrayref} ) {
3423 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3424 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3427 my $cust_main_invoice = new FS::cust_main_invoice ( {
3428 'custnum' => $self->custnum,
3431 my $error = $self->custnum
3432 ? $cust_main_invoice->check
3433 : $cust_main_invoice->checkdest
3435 return $error if $error;
3440 =item set_default_invoicing_list
3442 Sets the invoicing list to all accounts associated with this customer,
3443 overwriting any previous invoicing list.
3447 sub set_default_invoicing_list {
3449 $self->invoicing_list($self->all_emails);
3454 Returns the email addresses of all accounts provisioned for this customer.
3461 foreach my $cust_pkg ( $self->all_pkgs ) {
3462 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3464 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3465 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3467 $list{$_}=1 foreach map { $_->email } @svc_acct;
3472 =item invoicing_list_addpost
3474 Adds postal invoicing to this customer. If this customer is already configured
3475 to receive postal invoices, does nothing.
3479 sub invoicing_list_addpost {
3481 return if grep { $_ eq 'POST' } $self->invoicing_list;
3482 my @invoicing_list = $self->invoicing_list;
3483 push @invoicing_list, 'POST';
3484 $self->invoicing_list(\@invoicing_list);
3487 =item invoicing_list_emailonly
3489 Returns the list of email invoice recipients (invoicing_list without non-email
3490 destinations such as POST and FAX).
3494 sub invoicing_list_emailonly {
3496 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3499 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3501 Returns an array of customers referred by this customer (referral_custnum set
3502 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3503 customers referred by customers referred by this customer and so on, inclusive.
3504 The default behavior is DEPTH 1 (no recursion).
3508 sub referral_cust_main {
3510 my $depth = @_ ? shift : 1;
3511 my $exclude = @_ ? shift : {};
3514 map { $exclude->{$_->custnum}++; $_; }
3515 grep { ! $exclude->{ $_->custnum } }
3516 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3520 map { $_->referral_cust_main($depth-1, $exclude) }
3527 =item referral_cust_main_ncancelled
3529 Same as referral_cust_main, except only returns customers with uncancelled
3534 sub referral_cust_main_ncancelled {
3536 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3539 =item referral_cust_pkg [ DEPTH ]
3541 Like referral_cust_main, except returns a flat list of all unsuspended (and
3542 uncancelled) packages for each customer. The number of items in this list may
3543 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3547 sub referral_cust_pkg {
3549 my $depth = @_ ? shift : 1;
3551 map { $_->unsuspended_pkgs }
3552 grep { $_->unsuspended_pkgs }
3553 $self->referral_cust_main($depth);
3556 =item referring_cust_main
3558 Returns the single cust_main record for the customer who referred this customer
3559 (referral_custnum), or false.
3563 sub referring_cust_main {
3565 return '' unless $self->referral_custnum;
3566 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3569 =item credit AMOUNT, REASON
3571 Applies a credit to this customer. If there is an error, returns the error,
3572 otherwise returns false.
3577 my( $self, $amount, $reason ) = @_;
3578 my $cust_credit = new FS::cust_credit {
3579 'custnum' => $self->custnum,
3580 'amount' => $amount,
3581 'reason' => $reason,
3583 $cust_credit->insert;
3586 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3588 Creates a one-time charge for this customer. If there is an error, returns
3589 the error, otherwise returns false.
3594 my ( $self, $amount ) = ( shift, shift );
3595 my $pkg = @_ ? shift : 'One-time charge';
3596 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3597 my $taxclass = @_ ? shift : '';
3599 local $SIG{HUP} = 'IGNORE';
3600 local $SIG{INT} = 'IGNORE';
3601 local $SIG{QUIT} = 'IGNORE';
3602 local $SIG{TERM} = 'IGNORE';
3603 local $SIG{TSTP} = 'IGNORE';
3604 local $SIG{PIPE} = 'IGNORE';
3606 my $oldAutoCommit = $FS::UID::AutoCommit;
3607 local $FS::UID::AutoCommit = 0;
3610 my $part_pkg = new FS::part_pkg ( {
3612 'comment' => $comment,
3613 #'setup' => $amount,
3616 'plandata' => "setup_fee=$amount",
3619 'taxclass' => $taxclass,
3622 my $error = $part_pkg->insert;
3624 $dbh->rollback if $oldAutoCommit;
3628 my $pkgpart = $part_pkg->pkgpart;
3629 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3630 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3631 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3632 $error = $type_pkgs->insert;
3634 $dbh->rollback if $oldAutoCommit;
3639 my $cust_pkg = new FS::cust_pkg ( {
3640 'custnum' => $self->custnum,
3641 'pkgpart' => $pkgpart,
3644 $error = $cust_pkg->insert;
3646 $dbh->rollback if $oldAutoCommit;
3650 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3657 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3663 sort { $a->_date <=> $b->_date }
3664 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3667 =item open_cust_bill
3669 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3674 sub open_cust_bill {
3676 grep { $_->owed > 0 } $self->cust_bill;
3681 Returns all the credits (see L<FS::cust_credit>) for this customer.
3687 sort { $a->_date <=> $b->_date }
3688 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3693 Returns all the payments (see L<FS::cust_pay>) for this customer.
3699 sort { $a->_date <=> $b->_date }
3700 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3705 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3711 sort { $a->_date <=> $b->_date }
3712 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3718 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3724 sort { $a->_date <=> $b->_date }
3725 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3728 =item select_for_update
3730 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3735 sub select_for_update {
3737 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3742 Returns a name string for this customer, either "Company (Last, First)" or
3749 my $name = $self->contact;
3750 $name = $self->company. " ($name)" if $self->company;
3756 Returns a name string for this (service/shipping) contact, either
3757 "Company (Last, First)" or "Last, First".
3763 if ( $self->get('ship_last') ) {
3764 my $name = $self->ship_contact;
3765 $name = $self->ship_company. " ($name)" if $self->ship_company;
3774 Returns this customer's full (billing) contact name only, "Last, First"
3780 $self->get('last'). ', '. $self->first;
3785 Returns this customer's full (shipping) contact name only, "Last, First"
3791 $self->get('ship_last')
3792 ? $self->get('ship_last'). ', '. $self->ship_first
3798 Returns this customer's full country name
3804 code2country($self->country);
3809 Returns a status string for this customer, currently:
3813 =item prospect - No packages have ever been ordered
3815 =item active - One or more recurring packages is active
3817 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3819 =item suspended - All non-cancelled recurring packages are suspended
3821 =item cancelled - All recurring packages are cancelled
3829 for my $status (qw( prospect active inactive suspended cancelled )) {
3830 my $method = $status.'_sql';
3831 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3832 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3833 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3834 return $status if $sth->fetchrow_arrayref->[0];
3840 Returns a hex triplet color string for this customer's status.
3844 use vars qw(%statuscolor);
3846 'prospect' => '7e0079', #'000000', #black? naw, purple
3847 'active' => '00CC00', #green
3848 'inactive' => '0000CC', #blue
3849 'suspended' => 'FF9900', #yellow
3850 'cancelled' => 'FF0000', #red
3855 $statuscolor{$self->status};
3860 =head1 CLASS METHODS
3866 Returns an SQL expression identifying prospective cust_main records (customers
3867 with no packages ever ordered)
3871 use vars qw($select_count_pkgs);
3872 $select_count_pkgs =
3873 "SELECT COUNT(*) FROM cust_pkg
3874 WHERE cust_pkg.custnum = cust_main.custnum";
3876 sub select_count_pkgs_sql {
3880 sub prospect_sql { "
3881 0 = ( $select_count_pkgs )
3886 Returns an SQL expression identifying active cust_main records (customers with
3887 no active recurring packages, but otherwise unsuspended/uncancelled).
3892 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
3898 Returns an SQL expression identifying inactive cust_main records (customers with
3899 active recurring packages).
3903 sub inactive_sql { "
3904 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3906 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
3912 Returns an SQL expression identifying suspended cust_main records.
3917 sub suspended_sql { susp_sql(@_); }
3919 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
3921 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3927 Returns an SQL expression identifying cancelled cust_main records.
3931 sub cancelled_sql { cancel_sql(@_); }
3934 my $recurring_sql = FS::cust_pkg->recurring_sql;
3935 #my $recurring_sql = "
3936 # '0' != ( select freq from part_pkg
3937 # where cust_pkg.pkgpart = part_pkg.pkgpart )
3941 0 < ( $select_count_pkgs )
3942 AND 0 = ( $select_count_pkgs AND $recurring_sql
3943 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3949 =item uncancelled_sql
3951 Returns an SQL expression identifying un-cancelled cust_main records.
3955 sub uncancelled_sql { uncancel_sql(@_); }
3956 sub uncancel_sql { "
3957 ( 0 < ( $select_count_pkgs
3958 AND ( cust_pkg.cancel IS NULL
3959 OR cust_pkg.cancel = 0
3962 OR 0 = ( $select_count_pkgs )
3966 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3968 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3969 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
3970 appropriate ship_ field is also searched).
3972 Additional options are the same as FS::Record::qsearch
3977 my( $self, $fuzzy, $hash, @opt) = @_;
3982 check_and_rebuild_fuzzyfiles();
3983 foreach my $field ( keys %$fuzzy ) {
3985 my $all = $self->all_X($field);
3986 next unless scalar(@$all);
3989 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
3992 foreach ( keys %match ) {
3993 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3994 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
3997 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
4000 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
4002 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
4014 =item smart_search OPTION => VALUE ...
4016 Accepts the following options: I<search>, the string to search for. The string
4017 will be searched for as a customer number, phone number, name or company name,
4018 as an exact, or, in some cases, a substring or fuzzy match (see the source code
4019 for the exact heuristics used).
4021 Any additional options are treated as an additional qualifier on the search
4024 Returns a (possibly empty) array of FS::cust_main objects.
4031 #here is the agent virtualization
4032 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
4036 my $search = delete $options{'search'};
4037 ( my $alphanum_search = $search ) =~ s/\W//g;
4039 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
4041 #false laziness w/Record::ut_phone
4042 my $phonen = "$1-$2-$3";
4043 $phonen .= " x$4" if $4;
4045 push @cust_main, qsearch( {
4046 'table' => 'cust_main',
4047 'hashref' => { %options },
4048 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4050 join(' OR ', map "$_ = '$phonen'",
4051 qw( daytime night fax
4052 ship_daytime ship_night ship_fax )
4055 " AND $agentnums_sql", #agent virtualization
4058 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
4059 #try looking for matches with extensions unless one was specified
4061 push @cust_main, qsearch( {
4062 'table' => 'cust_main',
4063 'hashref' => { %options },
4064 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4066 join(' OR ', map "$_ LIKE '$phonen\%'",
4068 ship_daytime ship_night )
4071 " AND $agentnums_sql", #agent virtualization
4076 } elsif ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
4078 push @cust_main, qsearch( {
4079 'table' => 'cust_main',
4080 'hashref' => { 'custnum' => $1, %options },
4081 'extra_sql' => " AND $agentnums_sql", #agent virtualization
4084 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
4086 my($company, $last, $first) = ( $1, $2, $3 );
4088 # "Company (Last, First)"
4089 #this is probably something a browser remembered,
4090 #so just do an exact search
4092 foreach my $prefix ( '', 'ship_' ) {
4093 push @cust_main, qsearch( {
4094 'table' => 'cust_main',
4095 'hashref' => { $prefix.'first' => $first,
4096 $prefix.'last' => $last,
4097 $prefix.'company' => $company,
4100 'extra_sql' => " AND $agentnums_sql",
4104 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
4105 # try (ship_){last,company}
4109 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
4110 # # full strings the browser remembers won't work
4111 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
4113 use Lingua::EN::NameParse;
4114 my $NameParse = new Lingua::EN::NameParse(
4116 allow_reversed => 1,
4119 my($last, $first) = ( '', '' );
4120 #maybe disable this too and just rely on NameParse?
4121 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
4123 ($last, $first) = ( $1, $2 );
4125 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
4126 } elsif ( ! $NameParse->parse($value) ) {
4128 my %name = $NameParse->components;
4129 $first = $name{'given_name_1'};
4130 $last = $name{'surname_1'};
4134 if ( $first && $last ) {
4136 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
4139 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4141 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
4142 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
4145 push @cust_main, qsearch( {
4146 'table' => 'cust_main',
4147 'hashref' => \%options,
4148 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4151 # or it just be something that was typed in... (try that in a sec)
4155 my $q_value = dbh->quote($value);
4158 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4159 $sql .= " ( LOWER(last) = $q_value
4160 OR LOWER(company) = $q_value
4161 OR LOWER(ship_last) = $q_value
4162 OR LOWER(ship_company) = $q_value
4165 push @cust_main, qsearch( {
4166 'table' => 'cust_main',
4167 'hashref' => \%options,
4168 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4171 #always do substring & fuzzy,
4172 #getting complains searches are not returning enough
4173 #unless ( @cust_main ) { #no exact match, trying substring/fuzzy
4175 #still some false laziness w/ search/cust_main.cgi
4180 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
4181 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
4184 if ( $first && $last ) {
4187 { 'first' => { op=>'ILIKE', value=>"%$first%" },
4188 'last' => { op=>'ILIKE', value=>"%$last%" },
4190 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
4191 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
4198 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
4199 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
4203 foreach my $hashref ( @hashrefs ) {
4205 push @cust_main, qsearch( {
4206 'table' => 'cust_main',
4207 'hashref' => { %$hashref,
4210 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
4219 " AND $agentnums_sql", #extra_sql #agent virtualization
4222 if ( $first && $last ) {
4223 push @cust_main, FS::cust_main->fuzzy_search(
4224 { 'last' => $last, #fuzzy hashref
4225 'first' => $first }, #
4229 foreach my $field ( 'last', 'company' ) {
4231 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
4236 #eliminate duplicates
4238 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
4246 =item check_and_rebuild_fuzzyfiles
4250 use vars qw(@fuzzyfields);
4251 @fuzzyfields = ( 'last', 'first', 'company' );
4253 sub check_and_rebuild_fuzzyfiles {
4254 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4255 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
4258 =item rebuild_fuzzyfiles
4262 sub rebuild_fuzzyfiles {
4264 use Fcntl qw(:flock);
4266 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4267 mkdir $dir, 0700 unless -d $dir;
4269 foreach my $fuzzy ( @fuzzyfields ) {
4271 open(LOCK,">>$dir/cust_main.$fuzzy")
4272 or die "can't open $dir/cust_main.$fuzzy: $!";
4274 or die "can't lock $dir/cust_main.$fuzzy: $!";
4276 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
4277 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
4279 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
4280 my $sth = dbh->prepare("SELECT $field FROM cust_main".
4281 " WHERE $field != '' AND $field IS NOT NULL");
4282 $sth->execute or die $sth->errstr;
4284 while ( my $row = $sth->fetchrow_arrayref ) {
4285 print CACHE $row->[0]. "\n";
4290 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
4292 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
4303 my( $self, $field ) = @_;
4304 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4305 open(CACHE,"<$dir/cust_main.$field")
4306 or die "can't open $dir/cust_main.$field: $!";
4307 my @array = map { chomp; $_; } <CACHE>;
4312 =item append_fuzzyfiles LASTNAME COMPANY
4316 sub append_fuzzyfiles {
4317 #my( $first, $last, $company ) = @_;
4319 &check_and_rebuild_fuzzyfiles;
4321 use Fcntl qw(:flock);
4323 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4325 foreach my $field (qw( first last company )) {
4330 open(CACHE,">>$dir/cust_main.$field")
4331 or die "can't open $dir/cust_main.$field: $!";
4332 flock(CACHE,LOCK_EX)
4333 or die "can't lock $dir/cust_main.$field: $!";
4335 print CACHE "$value\n";
4337 flock(CACHE,LOCK_UN)
4338 or die "can't unlock $dir/cust_main.$field: $!";
4353 #warn join('-',keys %$param);
4354 my $fh = $param->{filehandle};
4355 my $agentnum = $param->{agentnum};
4357 my $refnum = $param->{refnum};
4358 my $pkgpart = $param->{pkgpart};
4360 #my @fields = @{$param->{fields}};
4361 my $format = $param->{'format'};
4364 if ( $format eq 'simple' ) {
4365 @fields = qw( cust_pkg.setup dayphone first last
4366 address1 address2 city state zip comments );
4368 } elsif ( $format eq 'extended' ) {
4369 @fields = qw( agent_custid refnum
4370 last first address1 address2 city state zip country
4372 ship_last ship_first ship_address1 ship_address2
4373 ship_city ship_state ship_zip ship_country
4374 payinfo paycvv paydate
4377 svc_acct.username svc_acct._password
4381 die "unknown format $format";
4384 eval "use Text::CSV_XS;";
4387 my $csv = new Text::CSV_XS;
4394 local $SIG{HUP} = 'IGNORE';
4395 local $SIG{INT} = 'IGNORE';
4396 local $SIG{QUIT} = 'IGNORE';
4397 local $SIG{TERM} = 'IGNORE';
4398 local $SIG{TSTP} = 'IGNORE';
4399 local $SIG{PIPE} = 'IGNORE';
4401 my $oldAutoCommit = $FS::UID::AutoCommit;
4402 local $FS::UID::AutoCommit = 0;
4405 #while ( $columns = $csv->getline($fh) ) {
4407 while ( defined($line=<$fh>) ) {
4409 $csv->parse($line) or do {
4410 $dbh->rollback if $oldAutoCommit;
4411 return "can't parse: ". $csv->error_input();
4414 my @columns = $csv->fields();
4415 #warn join('-',@columns);
4418 agentnum => $agentnum,
4420 country => $conf->config('countrydefault') || 'US',
4421 payby => $payby, #default
4422 paydate => '12/2037', #default
4424 my $billtime = time;
4425 my %cust_pkg = ( pkgpart => $pkgpart );
4427 foreach my $field ( @fields ) {
4429 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|expire|cancel)$/ ) {
4431 #$cust_pkg{$1} = str2time( shift @$columns );
4432 if ( $1 eq 'pkgpart' ) {
4433 $cust_pkg{$1} = shift @columns;
4434 } elsif ( $1 eq 'setup' ) {
4435 $billtime = str2time(shift @columns);
4437 $cust_pkg{$1} = str2time( shift @columns );
4440 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
4442 $svc_acct{$1} = shift @columns;
4446 #refnum interception
4447 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
4449 my $referral = $columns[0];
4450 my %hash = ( 'referral' => $referral,
4451 'agentnum' => $agentnum,
4455 my $part_referral = qsearchs('part_referral', \%hash )
4456 || new FS::part_referral \%hash;
4458 unless ( $part_referral->refnum ) {
4459 my $error = $part_referral->insert;
4461 $dbh->rollback if $oldAutoCommit;
4462 return "can't auto-insert advertising source: $referral: $error";
4466 $columns[0] = $part_referral->refnum;
4469 #$cust_main{$field} = shift @$columns;
4470 $cust_main{$field} = shift @columns;
4474 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
4476 my $invoicing_list = $cust_main{'invoicing_list'}
4477 ? [ delete $cust_main{'invoicing_list'} ]
4480 my $cust_main = new FS::cust_main ( \%cust_main );
4483 tie my %hash, 'Tie::RefHash'; #this part is important
4485 if ( $cust_pkg{'pkgpart'} ) {
4486 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
4489 if ( $svc_acct{'username'} ) {
4490 my $part_pkg = $cust_pkg->part_pkg;
4491 unless ( $part_pkg ) {
4492 $dbh->rollback if $oldAutoCommit;
4493 return "unknown pkgnum ". $cust_pkg{'pkgpart'};
4495 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
4496 push @svc_acct, new FS::svc_acct ( \%svc_acct )
4499 $hash{$cust_pkg} = \@svc_acct;
4502 my $error = $cust_main->insert( \%hash, $invoicing_list );
4505 $dbh->rollback if $oldAutoCommit;
4506 return "can't insert customer for $line: $error";
4509 if ( $format eq 'simple' ) {
4511 #false laziness w/bill.cgi
4512 $error = $cust_main->bill( 'time' => $billtime );
4514 $dbh->rollback if $oldAutoCommit;
4515 return "can't bill customer for $line: $error";
4518 $cust_main->apply_payments;
4519 $cust_main->apply_credits;
4521 $error = $cust_main->collect();
4523 $dbh->rollback if $oldAutoCommit;
4524 return "can't collect customer for $line: $error";
4532 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4534 return "Empty file!" unless $imported;
4546 #warn join('-',keys %$param);
4547 my $fh = $param->{filehandle};
4548 my @fields = @{$param->{fields}};
4550 eval "use Text::CSV_XS;";
4553 my $csv = new Text::CSV_XS;
4560 local $SIG{HUP} = 'IGNORE';
4561 local $SIG{INT} = 'IGNORE';
4562 local $SIG{QUIT} = 'IGNORE';
4563 local $SIG{TERM} = 'IGNORE';
4564 local $SIG{TSTP} = 'IGNORE';
4565 local $SIG{PIPE} = 'IGNORE';
4567 my $oldAutoCommit = $FS::UID::AutoCommit;
4568 local $FS::UID::AutoCommit = 0;
4571 #while ( $columns = $csv->getline($fh) ) {
4573 while ( defined($line=<$fh>) ) {
4575 $csv->parse($line) or do {
4576 $dbh->rollback if $oldAutoCommit;
4577 return "can't parse: ". $csv->error_input();
4580 my @columns = $csv->fields();
4581 #warn join('-',@columns);
4584 foreach my $field ( @fields ) {
4585 $row{$field} = shift @columns;
4588 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4589 unless ( $cust_main ) {
4590 $dbh->rollback if $oldAutoCommit;
4591 return "unknown custnum $row{'custnum'}";
4594 if ( $row{'amount'} > 0 ) {
4595 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4597 $dbh->rollback if $oldAutoCommit;
4601 } elsif ( $row{'amount'} < 0 ) {
4602 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4605 $dbh->rollback if $oldAutoCommit;
4615 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4617 return "Empty file!" unless $imported;
4629 The delete method should possibly take an FS::cust_main object reference
4630 instead of a scalar customer number.
4632 Bill and collect options should probably be passed as references instead of a
4635 There should probably be a configuration file with a list of allowed credit
4638 No multiple currency support (probably a larger project than just this module).
4640 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4642 Birthdates rely on negative epoch values.
4646 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4647 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4648 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.