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;
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' => { 'mg_profile_indicator' => { 'mg_profile_details' }, },
480 #'mg_watchlist_header' => { 'mg_watchlist_details' },
481 #'mg_user_grid_header' => { 'mg_user_grid_details' },
482 #'mg_portfolio_header' => { 'mg_portfolio_trades' => { 'mg_portfolio_trades_positions' } },
483 my @tables = eval($conf->config('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 ) = @_;
497 my $dbdef_table = dbdef->table($table);
498 my $primary_key = $dbdef_table->primary_key
499 or return "$table has no primary key".
500 " (or do you need to run dbdef-create?)";
502 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
503 join (', ', keys %child_tables). "\n"
506 foreach my $child_table ( keys %child_tables ) {
508 my $child_pkey = dbdef->table($child_table)->primary_key;
509 # or return "$table has no primary key".
510 # " (or do you need to run dbdef-create?)\n";
512 if ( keys %{ $child_tables{$child_table} } ) {
514 return "$child_table has no primary key\n" unless $child_pkey;
516 #false laziness w/Record::insert and only works on Pg
517 #refactor the proper last-inserted-id stuff out of Record::insert if this
518 # ever gets use for anything besides a quick kludge for one customer
519 my $default = dbdef->table($child_table)->column($child_pkey)->default;
520 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
521 or return "can't parse $child_table.$child_pkey default value ".
522 " for sequence name: $default";
527 my @sel_columns = grep { $_ ne $primary_key }
528 dbdef->table($child_table)->columns;
529 my $sel_columns = ' ( '. join(', ', @sel_columns ). ' ) ';
531 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
532 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
533 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
535 my $sel_st = "SELECT $sel_columns FROM $child_table".
536 " WHERE $primary_key = $sourceid";
539 my $sel_sth = dbh->prepare( $sel_st )
540 or return dbh->errstr;
542 $sel_sth->execute or return $sel_sth->errstr;
544 while ( my $row = $sel_sth->fetchrow_hashref ) {
546 warn " selected row: ".
547 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
551 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
552 my $ins_sth =dbh->prepare($statement)
553 or return dbh->errstr;
554 my @param = ( $destid, map $row->{$_}, @ins_columns );
555 warn " $statement: [ ". join(', ', @param). " ]\n"
557 $ins_sth->execute( @param )
558 or return $ins_sth->errstr;
560 #next unless keys %{ $child_tables{$child_table} };
561 next unless $sequence;
563 #another section of that laziness
564 my $seq_sql = "SELECT currval('$sequence')";
565 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
566 $seq_sth->execute or return $seq_sth->errstr;
567 my $insertid = $seq_sth->fetchrow_arrayref->[0];
569 # don't drink soap! recurse! recurse! okay!
571 _copy_skel( $child_table,
572 $row->{$child_pkey}, #sourceid
574 %{ $child_tables{$child_table} },
576 return $error if $error;
586 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
588 Like the insert method on an existing record, this method orders a package
589 and included services atomicaly. Pass a Tie::RefHash data structure to this
590 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
591 be a better explanation of this, but until then, here's an example:
594 tie %hash, 'Tie::RefHash'; #this part is important
596 $cust_pkg => [ $svc_acct ],
599 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
601 Services can be new, in which case they are inserted, or existing unaudited
602 services, in which case they are linked to the newly-created package.
604 Currently available options are: I<depend_jobnum> and I<noexport>.
606 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
607 on the supplied jobnum (they will not run until the specific job completes).
608 This can be used to defer provisioning until some action completes (such
609 as running the customer's credit card successfully).
611 The I<noexport> option is deprecated. If I<noexport> is set true, no
612 provisioning jobs (exports) are scheduled. (You can schedule them later with
613 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
614 on the cust_main object is not recommended, as existing services will also be
621 my $cust_pkgs = shift;
624 my %svc_options = ();
625 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
626 if exists $options{'depend_jobnum'};
627 warn "$me order_pkgs called with options ".
628 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
631 local $SIG{HUP} = 'IGNORE';
632 local $SIG{INT} = 'IGNORE';
633 local $SIG{QUIT} = 'IGNORE';
634 local $SIG{TERM} = 'IGNORE';
635 local $SIG{TSTP} = 'IGNORE';
636 local $SIG{PIPE} = 'IGNORE';
638 my $oldAutoCommit = $FS::UID::AutoCommit;
639 local $FS::UID::AutoCommit = 0;
642 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
644 foreach my $cust_pkg ( keys %$cust_pkgs ) {
645 $cust_pkg->custnum( $self->custnum );
646 my $error = $cust_pkg->insert;
648 $dbh->rollback if $oldAutoCommit;
649 return "inserting cust_pkg (transaction rolled back): $error";
651 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
652 if ( $svc_something->svcnum ) {
653 my $old_cust_svc = $svc_something->cust_svc;
654 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
655 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
656 $error = $new_cust_svc->replace($old_cust_svc);
658 $svc_something->pkgnum( $cust_pkg->pkgnum );
659 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
660 $svc_something->seconds( $svc_something->seconds + $$seconds );
663 $error = $svc_something->insert(%svc_options);
666 $dbh->rollback if $oldAutoCommit;
667 #return "inserting svc_ (transaction rolled back): $error";
673 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
677 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF ]
679 Recharges this (existing) customer with the specified prepaid card (see
680 L<FS::prepay_credit>), specified either by I<identifier> or as an
681 FS::prepay_credit object. If there is an error, returns the error, otherwise
684 Optionally, two scalar references can be passed as well. They will have their
685 values filled in with the amount and number of seconds applied by this prepaid
690 sub recharge_prepay {
691 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
693 local $SIG{HUP} = 'IGNORE';
694 local $SIG{INT} = 'IGNORE';
695 local $SIG{QUIT} = 'IGNORE';
696 local $SIG{TERM} = 'IGNORE';
697 local $SIG{TSTP} = 'IGNORE';
698 local $SIG{PIPE} = 'IGNORE';
700 my $oldAutoCommit = $FS::UID::AutoCommit;
701 local $FS::UID::AutoCommit = 0;
704 my( $amount, $seconds ) = ( 0, 0 );
706 my $error = $self->get_prepay($prepay_credit, \$amount, \$seconds)
707 || $self->increment_seconds($seconds)
708 || $self->insert_cust_pay_prepay( $amount,
710 ? $prepay_credit->identifier
715 $dbh->rollback if $oldAutoCommit;
719 if ( defined($amountref) ) { $$amountref = $amount; }
720 if ( defined($secondsref) ) { $$secondsref = $seconds; }
722 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
727 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
729 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
730 specified either by I<identifier> or as an FS::prepay_credit object.
732 References to I<amount> and I<seconds> scalars should be passed as arguments
733 and will be incremented by the values of the prepaid card.
735 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
736 check or set this customer's I<agentnum>.
738 If there is an error, returns the error, otherwise returns false.
744 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
746 local $SIG{HUP} = 'IGNORE';
747 local $SIG{INT} = 'IGNORE';
748 local $SIG{QUIT} = 'IGNORE';
749 local $SIG{TERM} = 'IGNORE';
750 local $SIG{TSTP} = 'IGNORE';
751 local $SIG{PIPE} = 'IGNORE';
753 my $oldAutoCommit = $FS::UID::AutoCommit;
754 local $FS::UID::AutoCommit = 0;
757 unless ( ref($prepay_credit) ) {
759 my $identifier = $prepay_credit;
761 $prepay_credit = qsearchs(
763 { 'identifier' => $prepay_credit },
768 unless ( $prepay_credit ) {
769 $dbh->rollback if $oldAutoCommit;
770 return "Invalid prepaid card: ". $identifier;
775 if ( $prepay_credit->agentnum ) {
776 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
777 $dbh->rollback if $oldAutoCommit;
778 return "prepaid card not valid for agent ". $self->agentnum;
780 $self->agentnum($prepay_credit->agentnum);
783 my $error = $prepay_credit->delete;
785 $dbh->rollback if $oldAutoCommit;
786 return "removing prepay_credit (transaction rolled back): $error";
789 $$amountref += $prepay_credit->amount;
790 $$secondsref += $prepay_credit->seconds;
792 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
797 =item increment_seconds SECONDS
799 Updates this customer's single or primary account (see L<FS::svc_acct>) by
800 the specified number of seconds. If there is an error, returns the error,
801 otherwise returns false.
805 sub increment_seconds {
806 my( $self, $seconds ) = @_;
807 warn "$me increment_seconds called: $seconds seconds\n"
810 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
811 $self->ncancelled_pkgs;
814 return 'No packages with primary or single services found'.
815 ' to apply pre-paid time';
816 } elsif ( scalar(@cust_pkg) > 1 ) {
817 #maybe have a way to specify the package/account?
818 return 'Multiple packages found to apply pre-paid time';
821 my $cust_pkg = $cust_pkg[0];
822 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
826 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
829 return 'No account found to apply pre-paid time';
830 } elsif ( scalar(@cust_svc) > 1 ) {
831 return 'Multiple accounts found to apply pre-paid time';
834 my $svc_acct = $cust_svc[0]->svc_x;
835 warn " found service svcnum ". $svc_acct->pkgnum.
836 ' ('. $svc_acct->email. ")\n"
839 $svc_acct->increment_seconds($seconds);
843 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
845 Inserts a prepayment in the specified amount for this customer. An optional
846 second argument can specify the prepayment identifier for tracking purposes.
847 If there is an error, returns the error, otherwise returns false.
851 sub insert_cust_pay_prepay {
852 shift->insert_cust_pay('PREP', @_);
855 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
857 Inserts a cash payment in the specified amount for this customer. An optional
858 second argument can specify the payment identifier for tracking purposes.
859 If there is an error, returns the error, otherwise returns false.
863 sub insert_cust_pay_cash {
864 shift->insert_cust_pay('CASH', @_);
867 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
869 Inserts a Western Union payment in the specified amount for this customer. An
870 optional second argument can specify the prepayment identifier for tracking
871 purposes. If there is an error, returns the error, otherwise returns false.
875 sub insert_cust_pay_west {
876 shift->insert_cust_pay('WEST', @_);
879 sub insert_cust_pay {
880 my( $self, $payby, $amount ) = splice(@_, 0, 3);
881 my $payinfo = scalar(@_) ? shift : '';
883 my $cust_pay = new FS::cust_pay {
884 'custnum' => $self->custnum,
885 'paid' => sprintf('%.2f', $amount),
886 #'_date' => #date the prepaid card was purchased???
888 'payinfo' => $payinfo,
896 This method is deprecated. See the I<depend_jobnum> option to the insert and
897 order_pkgs methods for a better way to defer provisioning.
899 Re-schedules all exports by calling the B<reexport> method of all associated
900 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
901 otherwise returns false.
908 carp "WARNING: FS::cust_main::reexport is deprectated; ".
909 "use the depend_jobnum option to insert or order_pkgs to delay export";
911 local $SIG{HUP} = 'IGNORE';
912 local $SIG{INT} = 'IGNORE';
913 local $SIG{QUIT} = 'IGNORE';
914 local $SIG{TERM} = 'IGNORE';
915 local $SIG{TSTP} = 'IGNORE';
916 local $SIG{PIPE} = 'IGNORE';
918 my $oldAutoCommit = $FS::UID::AutoCommit;
919 local $FS::UID::AutoCommit = 0;
922 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
923 my $error = $cust_pkg->reexport;
925 $dbh->rollback if $oldAutoCommit;
930 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
935 =item delete NEW_CUSTNUM
937 This deletes the customer. If there is an error, returns the error, otherwise
940 This will completely remove all traces of the customer record. This is not
941 what you want when a customer cancels service; for that, cancel all of the
942 customer's packages (see L</cancel>).
944 If the customer has any uncancelled packages, you need to pass a new (valid)
945 customer number for those packages to be transferred to. Cancelled packages
946 will be deleted. Did I mention that this is NOT what you want when a customer
947 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
949 You can't delete a customer with invoices (see L<FS::cust_bill>),
950 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
951 refunds (see L<FS::cust_refund>).
958 local $SIG{HUP} = 'IGNORE';
959 local $SIG{INT} = 'IGNORE';
960 local $SIG{QUIT} = 'IGNORE';
961 local $SIG{TERM} = 'IGNORE';
962 local $SIG{TSTP} = 'IGNORE';
963 local $SIG{PIPE} = 'IGNORE';
965 my $oldAutoCommit = $FS::UID::AutoCommit;
966 local $FS::UID::AutoCommit = 0;
969 if ( $self->cust_bill ) {
970 $dbh->rollback if $oldAutoCommit;
971 return "Can't delete a customer with invoices";
973 if ( $self->cust_credit ) {
974 $dbh->rollback if $oldAutoCommit;
975 return "Can't delete a customer with credits";
977 if ( $self->cust_pay ) {
978 $dbh->rollback if $oldAutoCommit;
979 return "Can't delete a customer with payments";
981 if ( $self->cust_refund ) {
982 $dbh->rollback if $oldAutoCommit;
983 return "Can't delete a customer with refunds";
986 my @cust_pkg = $self->ncancelled_pkgs;
988 my $new_custnum = shift;
989 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
990 $dbh->rollback if $oldAutoCommit;
991 return "Invalid new customer number: $new_custnum";
993 foreach my $cust_pkg ( @cust_pkg ) {
994 my %hash = $cust_pkg->hash;
995 $hash{'custnum'} = $new_custnum;
996 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
997 my $error = $new_cust_pkg->replace($cust_pkg);
999 $dbh->rollback if $oldAutoCommit;
1004 my @cancelled_cust_pkg = $self->all_pkgs;
1005 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1006 my $error = $cust_pkg->delete;
1008 $dbh->rollback if $oldAutoCommit;
1013 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1014 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1016 my $error = $cust_main_invoice->delete;
1018 $dbh->rollback if $oldAutoCommit;
1023 my $error = $self->SUPER::delete;
1025 $dbh->rollback if $oldAutoCommit;
1029 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1034 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1036 Replaces the OLD_RECORD with this one in the database. If there is an error,
1037 returns the error, otherwise returns false.
1039 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1040 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1041 expected and rollback the entire transaction; it is not necessary to call
1042 check_invoicing_list first. Here's an example:
1044 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1052 warn "$me replace called\n"
1055 local $SIG{HUP} = 'IGNORE';
1056 local $SIG{INT} = 'IGNORE';
1057 local $SIG{QUIT} = 'IGNORE';
1058 local $SIG{TERM} = 'IGNORE';
1059 local $SIG{TSTP} = 'IGNORE';
1060 local $SIG{PIPE} = 'IGNORE';
1062 # If the mask is blank then try to set it - if we can...
1063 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
1064 $self->paymask($self->payinfo);
1067 # We absolutely have to have an old vs. new record to make this work.
1068 if (!defined($old)) {
1069 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1072 my $curuser = $FS::CurrentUser::CurrentUser;
1073 if ( $self->payby eq 'COMP'
1074 && $self->payby ne $old->payby
1075 && ! $curuser->access_right('Complimentary customer')
1078 return "You are not permitted to create complimentary accounts.";
1081 local($ignore_expired_card) = 1
1082 if $old->payby =~ /^(CARD|DCRD)$/
1083 && $self->payby =~ /^(CARD|DCRD)$/
1084 && $old->payinfo eq $self->payinfo;
1086 my $oldAutoCommit = $FS::UID::AutoCommit;
1087 local $FS::UID::AutoCommit = 0;
1090 my $error = $self->SUPER::replace($old);
1093 $dbh->rollback if $oldAutoCommit;
1097 if ( @param ) { # INVOICING_LIST_ARYREF
1098 my $invoicing_list = shift @param;
1099 $error = $self->check_invoicing_list( $invoicing_list );
1101 $dbh->rollback if $oldAutoCommit;
1104 $self->invoicing_list( $invoicing_list );
1107 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1108 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1109 # card/check/lec info has changed, want to retry realtime_ invoice events
1110 my $error = $self->retry_realtime;
1112 $dbh->rollback if $oldAutoCommit;
1117 unless ( $import || $skip_fuzzyfiles ) {
1118 $error = $self->queue_fuzzyfiles_update;
1120 $dbh->rollback if $oldAutoCommit;
1121 return "updating fuzzy search cache: $error";
1125 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1130 =item queue_fuzzyfiles_update
1132 Used by insert & replace to update the fuzzy search cache
1136 sub queue_fuzzyfiles_update {
1139 local $SIG{HUP} = 'IGNORE';
1140 local $SIG{INT} = 'IGNORE';
1141 local $SIG{QUIT} = 'IGNORE';
1142 local $SIG{TERM} = 'IGNORE';
1143 local $SIG{TSTP} = 'IGNORE';
1144 local $SIG{PIPE} = 'IGNORE';
1146 my $oldAutoCommit = $FS::UID::AutoCommit;
1147 local $FS::UID::AutoCommit = 0;
1150 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1151 my $error = $queue->insert( map $self->getfield($_),
1152 qw(first last company)
1155 $dbh->rollback if $oldAutoCommit;
1156 return "queueing job (transaction rolled back): $error";
1159 if ( $self->ship_last ) {
1160 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1161 $error = $queue->insert( map $self->getfield("ship_$_"),
1162 qw(first last company)
1165 $dbh->rollback if $oldAutoCommit;
1166 return "queueing job (transaction rolled back): $error";
1170 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1177 Checks all fields to make sure this is a valid customer record. If there is
1178 an error, returns the error, otherwise returns false. Called by the insert
1179 and replace methods.
1186 warn "$me check BEFORE: \n". $self->_dump
1190 $self->ut_numbern('custnum')
1191 || $self->ut_number('agentnum')
1192 || $self->ut_textn('agent_custid')
1193 || $self->ut_number('refnum')
1194 || $self->ut_name('last')
1195 || $self->ut_name('first')
1196 || $self->ut_textn('company')
1197 || $self->ut_text('address1')
1198 || $self->ut_textn('address2')
1199 || $self->ut_text('city')
1200 || $self->ut_textn('county')
1201 || $self->ut_textn('state')
1202 || $self->ut_country('country')
1203 || $self->ut_anything('comments')
1204 || $self->ut_numbern('referral_custnum')
1206 #barf. need message catalogs. i18n. etc.
1207 $error .= "Please select an advertising source."
1208 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1209 return $error if $error;
1211 return "Unknown agent"
1212 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1214 return "Unknown refnum"
1215 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1217 return "Unknown referring custnum: ". $self->referral_custnum
1218 unless ! $self->referral_custnum
1219 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1221 if ( $self->ss eq '' ) {
1226 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1227 or return "Illegal social security number: ". $self->ss;
1228 $self->ss("$1-$2-$3");
1232 # bad idea to disable, causes billing to fail because of no tax rates later
1233 # unless ( $import ) {
1234 unless ( qsearch('cust_main_county', {
1235 'country' => $self->country,
1238 return "Unknown state/county/country: ".
1239 $self->state. "/". $self->county. "/". $self->country
1240 unless qsearch('cust_main_county',{
1241 'state' => $self->state,
1242 'county' => $self->county,
1243 'country' => $self->country,
1249 $self->ut_phonen('daytime', $self->country)
1250 || $self->ut_phonen('night', $self->country)
1251 || $self->ut_phonen('fax', $self->country)
1252 || $self->ut_zip('zip', $self->country)
1254 return $error if $error;
1257 last first company address1 address2 city county state zip
1258 country daytime night fax
1261 if ( defined $self->dbdef_table->column('ship_last') ) {
1262 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1264 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1268 $self->ut_name('ship_last')
1269 || $self->ut_name('ship_first')
1270 || $self->ut_textn('ship_company')
1271 || $self->ut_text('ship_address1')
1272 || $self->ut_textn('ship_address2')
1273 || $self->ut_text('ship_city')
1274 || $self->ut_textn('ship_county')
1275 || $self->ut_textn('ship_state')
1276 || $self->ut_country('ship_country')
1278 return $error if $error;
1280 #false laziness with above
1281 unless ( qsearchs('cust_main_county', {
1282 'country' => $self->ship_country,
1285 return "Unknown ship_state/ship_county/ship_country: ".
1286 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1287 unless qsearch('cust_main_county',{
1288 'state' => $self->ship_state,
1289 'county' => $self->ship_county,
1290 'country' => $self->ship_country,
1296 $self->ut_phonen('ship_daytime', $self->ship_country)
1297 || $self->ut_phonen('ship_night', $self->ship_country)
1298 || $self->ut_phonen('ship_fax', $self->ship_country)
1299 || $self->ut_zip('ship_zip', $self->ship_country)
1301 return $error if $error;
1303 } else { # ship_ info eq billing info, so don't store dup info in database
1304 $self->setfield("ship_$_", '')
1305 foreach qw( last first company address1 address2 city county state zip
1306 country daytime night fax );
1310 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1311 or return "Illegal payby: ". $self->payby;
1313 $error = $self->ut_numbern('paystart_month')
1314 || $self->ut_numbern('paystart_year')
1315 || $self->ut_numbern('payissue')
1317 return $error if $error;
1319 if ( $self->payip eq '' ) {
1322 $error = $self->ut_ip('payip');
1323 return $error if $error;
1326 # If it is encrypted and the private key is not availaible then we can't
1327 # check the credit card.
1329 my $check_payinfo = 1;
1331 if ($self->is_encrypted($self->payinfo)) {
1337 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1339 my $payinfo = $self->payinfo;
1340 $payinfo =~ s/\D//g;
1341 $payinfo =~ /^(\d{13,16})$/
1342 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1344 $self->payinfo($payinfo);
1346 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1348 return gettext('unknown_card_type')
1349 if cardtype($self->payinfo) eq "Unknown";
1351 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1353 return 'Banned credit card: banned on '.
1354 time2str('%a %h %o at %r', $ban->_date).
1355 ' by '. $ban->otaker.
1356 ' (ban# '. $ban->bannum. ')';
1359 if ( defined $self->dbdef_table->column('paycvv') ) {
1360 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1361 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1362 $self->paycvv =~ /^(\d{4})$/
1363 or return "CVV2 (CID) for American Express cards is four digits.";
1366 $self->paycvv =~ /^(\d{3})$/
1367 or return "CVV2 (CVC2/CID) is three digits.";
1375 my $cardtype = cardtype($payinfo);
1376 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1378 return "Start date or issue number is required for $cardtype cards"
1379 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1381 return "Start month must be between 1 and 12"
1382 if $self->paystart_month
1383 and $self->paystart_month < 1 || $self->paystart_month > 12;
1385 return "Start year must be 1990 or later"
1386 if $self->paystart_year
1387 and $self->paystart_year < 1990;
1389 return "Issue number must be beween 1 and 99"
1391 and $self->payissue < 1 || $self->payissue > 99;
1394 $self->paystart_month('');
1395 $self->paystart_year('');
1396 $self->payissue('');
1399 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1401 my $payinfo = $self->payinfo;
1402 $payinfo =~ s/[^\d\@]//g;
1403 if ( $conf->exists('echeck-nonus') ) {
1404 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1405 $payinfo = "$1\@$2";
1407 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1408 $payinfo = "$1\@$2";
1410 $self->payinfo($payinfo);
1411 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1413 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1415 return 'Banned ACH account: banned on '.
1416 time2str('%a %h %o at %r', $ban->_date).
1417 ' by '. $ban->otaker.
1418 ' (ban# '. $ban->bannum. ')';
1421 } elsif ( $self->payby eq 'LECB' ) {
1423 my $payinfo = $self->payinfo;
1424 $payinfo =~ s/\D//g;
1425 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1427 $self->payinfo($payinfo);
1428 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1430 } elsif ( $self->payby eq 'BILL' ) {
1432 $error = $self->ut_textn('payinfo');
1433 return "Illegal P.O. number: ". $self->payinfo if $error;
1434 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1436 } elsif ( $self->payby eq 'COMP' ) {
1438 my $curuser = $FS::CurrentUser::CurrentUser;
1439 if ( ! $self->custnum
1440 && ! $curuser->access_right('Complimentary customer')
1443 return "You are not permitted to create complimentary accounts."
1446 $error = $self->ut_textn('payinfo');
1447 return "Illegal comp account issuer: ". $self->payinfo if $error;
1448 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1450 } elsif ( $self->payby eq 'PREPAY' ) {
1452 my $payinfo = $self->payinfo;
1453 $payinfo =~ s/\W//g; #anything else would just confuse things
1454 $self->payinfo($payinfo);
1455 $error = $self->ut_alpha('payinfo');
1456 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1457 return "Unknown prepayment identifier"
1458 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1459 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1463 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1464 return "Expiration date required"
1465 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1469 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1470 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1471 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1472 ( $m, $y ) = ( $3, "20$2" );
1474 return "Illegal expiration date: ". $self->paydate;
1476 $self->paydate("$y-$m-01");
1477 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1478 return gettext('expired_card')
1480 && !$ignore_expired_card
1481 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1484 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1485 ( ! $conf->exists('require_cardname')
1486 || $self->payby !~ /^(CARD|DCRD)$/ )
1488 $self->payname( $self->first. " ". $self->getfield('last') );
1490 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1491 or return gettext('illegal_name'). " payname: ". $self->payname;
1495 foreach my $flag (qw( tax spool_cdr )) {
1496 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1500 $self->otaker(getotaker) unless $self->otaker;
1502 warn "$me check AFTER: \n". $self->_dump
1505 $self->SUPER::check;
1510 Returns all packages (see L<FS::cust_pkg>) for this customer.
1516 if ( $self->{'_pkgnum'} ) {
1517 values %{ $self->{'_pkgnum'}->cache };
1519 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1523 =item ncancelled_pkgs
1525 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1529 sub ncancelled_pkgs {
1531 if ( $self->{'_pkgnum'} ) {
1532 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1534 @{ [ # force list context
1535 qsearch( 'cust_pkg', {
1536 'custnum' => $self->custnum,
1539 qsearch( 'cust_pkg', {
1540 'custnum' => $self->custnum,
1547 =item suspended_pkgs
1549 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1553 sub suspended_pkgs {
1555 grep { $_->susp } $self->ncancelled_pkgs;
1558 =item unflagged_suspended_pkgs
1560 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1561 customer (thouse packages without the `manual_flag' set).
1565 sub unflagged_suspended_pkgs {
1567 return $self->suspended_pkgs
1568 unless dbdef->table('cust_pkg')->column('manual_flag');
1569 grep { ! $_->manual_flag } $self->suspended_pkgs;
1572 =item unsuspended_pkgs
1574 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1579 sub unsuspended_pkgs {
1581 grep { ! $_->susp } $self->ncancelled_pkgs;
1584 =item num_cancelled_pkgs
1586 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1591 sub num_cancelled_pkgs {
1593 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1597 my( $self, $sql ) = @_;
1598 my $sth = dbh->prepare(
1599 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1600 ) or die dbh->errstr;
1601 $sth->execute($self->custnum) or die $sth->errstr;
1602 $sth->fetchrow_arrayref->[0];
1607 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1608 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1609 on success or a list of errors.
1615 grep { $_->unsuspend } $self->suspended_pkgs;
1620 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1622 Returns a list: an empty list on success or a list of errors.
1628 grep { $_->suspend } $self->unsuspended_pkgs;
1631 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1633 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1634 PKGPARTs (see L<FS::part_pkg>).
1636 Returns a list: an empty list on success or a list of errors.
1640 sub suspend_if_pkgpart {
1643 grep { $_->suspend }
1644 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1645 $self->unsuspended_pkgs;
1648 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1650 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1651 listed PKGPARTs (see L<FS::part_pkg>).
1653 Returns a list: an empty list on success or a list of errors.
1657 sub suspend_unless_pkgpart {
1660 grep { $_->suspend }
1661 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1662 $self->unsuspended_pkgs;
1665 =item cancel [ OPTION => VALUE ... ]
1667 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1669 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1671 I<quiet> can be set true to supress email cancellation notices.
1673 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1675 I<ban> can be set true to ban this customer's credit card or ACH information,
1678 Always returns a list: an empty list on success or a list of errors.
1686 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1688 #should try decryption (we might have the private key)
1689 # and if not maybe queue a job for the server that does?
1690 return ( "Can't (yet) ban encrypted credit cards" )
1691 if $self->is_encrypted($self->payinfo);
1693 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1694 my $error = $ban->insert;
1695 return ( $error ) if $error;
1699 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1702 sub _banned_pay_hashref {
1713 'payby' => $payby2ban{$self->payby},
1714 'payinfo' => md5_base64($self->payinfo),
1721 Returns the agent (see L<FS::agent>) for this customer.
1727 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1732 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1733 conjunction with the collect method.
1735 Options are passed as name-value pairs.
1737 Currently available options are:
1739 resetup - if set true, re-charges setup fees.
1741 time - bills the customer as if it were that time. Specified as a UNIX
1742 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1743 L<Date::Parse> for conversion functions. For example:
1747 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1750 If there is an error, returns the error, otherwise returns false.
1755 my( $self, %options ) = @_;
1756 return '' if $self->payby eq 'COMP';
1757 warn "$me bill customer ". $self->custnum. "\n"
1760 my $time = $options{'time'} || time;
1765 local $SIG{HUP} = 'IGNORE';
1766 local $SIG{INT} = 'IGNORE';
1767 local $SIG{QUIT} = 'IGNORE';
1768 local $SIG{TERM} = 'IGNORE';
1769 local $SIG{TSTP} = 'IGNORE';
1770 local $SIG{PIPE} = 'IGNORE';
1772 my $oldAutoCommit = $FS::UID::AutoCommit;
1773 local $FS::UID::AutoCommit = 0;
1776 $self->select_for_update; #mutex
1778 #create a new invoice
1779 #(we'll remove it later if it doesn't actually need to be generated [contains
1780 # no line items] and we're inside a transaciton so nothing else will see it)
1781 my $cust_bill = new FS::cust_bill ( {
1782 'custnum' => $self->custnum,
1784 #'charged' => $charged,
1787 $error = $cust_bill->insert;
1789 $dbh->rollback if $oldAutoCommit;
1790 return "can't create invoice for customer #". $self->custnum. ": $error";
1792 my $invnum = $cust_bill->invnum;
1795 # find the packages which are due for billing, find out how much they are
1796 # & generate invoice database.
1799 my( $total_setup, $total_recur ) = ( 0, 0 );
1801 my @precommit_hooks = ();
1803 foreach my $cust_pkg (
1804 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1807 #NO!! next if $cust_pkg->cancel;
1808 next if $cust_pkg->getfield('cancel');
1810 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1812 #? to avoid use of uninitialized value errors... ?
1813 $cust_pkg->setfield('bill', '')
1814 unless defined($cust_pkg->bill);
1816 my $part_pkg = $cust_pkg->part_pkg;
1818 my %hash = $cust_pkg->hash;
1819 my $old_cust_pkg = new FS::cust_pkg \%hash;
1828 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1830 warn " bill setup\n" if $DEBUG > 1;
1832 $setup = eval { $cust_pkg->calc_setup( $time ) };
1834 $dbh->rollback if $oldAutoCommit;
1835 return "$@ running calc_setup for $cust_pkg\n";
1838 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1842 # bill recurring fee
1847 if ( $part_pkg->getfield('freq') ne '0' &&
1848 ! $cust_pkg->getfield('susp') &&
1849 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1852 warn " bill recur\n" if $DEBUG > 1;
1854 # XXX shared with $recur_prog
1855 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1857 #over two params! lets at least switch to a hashref for the rest...
1858 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
1860 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
1862 $dbh->rollback if $oldAutoCommit;
1863 return "$@ running calc_recur for $cust_pkg\n";
1866 #change this bit to use Date::Manip? CAREFUL with timezones (see
1867 # mailing list archive)
1868 my ($sec,$min,$hour,$mday,$mon,$year) =
1869 (localtime($sdate) )[0,1,2,3,4,5];
1871 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1872 # only for figuring next bill date, nothing else, so, reset $sdate again
1874 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1875 $cust_pkg->last_bill($sdate)
1876 if $cust_pkg->dbdef_table->column('last_bill');
1878 if ( $part_pkg->freq =~ /^\d+$/ ) {
1879 $mon += $part_pkg->freq;
1880 until ( $mon < 12 ) { $mon -= 12; $year++; }
1881 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1883 $mday += $weeks * 7;
1884 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1887 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
1891 $dbh->rollback if $oldAutoCommit;
1892 return "unparsable frequency: ". $part_pkg->freq;
1894 $cust_pkg->setfield('bill',
1895 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1898 warn "\$setup is undefined" unless defined($setup);
1899 warn "\$recur is undefined" unless defined($recur);
1900 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1903 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
1906 if ( $cust_pkg->modified ) {
1908 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
1911 $error=$cust_pkg->replace($old_cust_pkg);
1912 if ( $error ) { #just in case
1913 $dbh->rollback if $oldAutoCommit;
1914 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1917 $setup = sprintf( "%.2f", $setup );
1918 $recur = sprintf( "%.2f", $recur );
1919 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1920 $dbh->rollback if $oldAutoCommit;
1921 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1923 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1924 $dbh->rollback if $oldAutoCommit;
1925 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1928 if ( $setup != 0 || $recur != 0 ) {
1930 warn " charges (setup=$setup, recur=$recur); adding line items\n"
1932 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1933 'invnum' => $invnum,
1934 'pkgnum' => $cust_pkg->pkgnum,
1938 'edate' => $cust_pkg->bill,
1939 'details' => \@details,
1941 $error = $cust_bill_pkg->insert;
1943 $dbh->rollback if $oldAutoCommit;
1944 return "can't create invoice line item for invoice #$invnum: $error";
1946 $total_setup += $setup;
1947 $total_recur += $recur;
1953 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1956 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
1959 my %taxhash = map { $_ => $self->get("$prefix$_") }
1960 qw( state county country );
1962 $taxhash{'taxclass'} = $part_pkg->taxclass;
1964 my @taxes = qsearch( 'cust_main_county', \%taxhash );
1967 $taxhash{'taxclass'} = '';
1968 @taxes = qsearch( 'cust_main_county', \%taxhash );
1971 #one more try at a whole-country tax rate
1973 $taxhash{$_} = '' foreach qw( state county );
1974 @taxes = qsearch( 'cust_main_county', \%taxhash );
1977 # maybe eliminate this entirely, along with all the 0% records
1979 $dbh->rollback if $oldAutoCommit;
1981 "fatal: can't find tax rate for state/county/country/taxclass ".
1982 join('/', ( map $self->get("$prefix$_"),
1983 qw(state county country)
1985 $part_pkg->taxclass ). "\n";
1988 foreach my $tax ( @taxes ) {
1990 my $taxable_charged = 0;
1991 $taxable_charged += $setup
1992 unless $part_pkg->setuptax =~ /^Y$/i
1993 || $tax->setuptax =~ /^Y$/i;
1994 $taxable_charged += $recur
1995 unless $part_pkg->recurtax =~ /^Y$/i
1996 || $tax->recurtax =~ /^Y$/i;
1997 next unless $taxable_charged;
1999 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2000 #my ($mon,$year) = (localtime($sdate) )[4,5];
2001 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2003 my $freq = $part_pkg->freq || 1;
2004 if ( $freq !~ /(\d+)$/ ) {
2005 $dbh->rollback if $oldAutoCommit;
2006 return "daily/weekly package definitions not (yet?)".
2007 " compatible with monthly tax exemptions";
2009 my $taxable_per_month =
2010 sprintf("%.2f", $taxable_charged / $freq );
2012 #call the whole thing off if this customer has any old
2013 #exemption records...
2014 my @cust_tax_exempt =
2015 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2016 if ( @cust_tax_exempt ) {
2017 $dbh->rollback if $oldAutoCommit;
2019 'this customer still has old-style tax exemption records; '.
2020 'run bin/fs-migrate-cust_tax_exempt?';
2023 foreach my $which_month ( 1 .. $freq ) {
2025 #maintain the new exemption table now
2028 FROM cust_tax_exempt_pkg
2029 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2030 LEFT JOIN cust_bill USING ( invnum )
2036 my $sth = dbh->prepare($sql) or do {
2037 $dbh->rollback if $oldAutoCommit;
2038 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2046 $dbh->rollback if $oldAutoCommit;
2047 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2049 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2051 my $remaining_exemption =
2052 $tax->exempt_amount - $existing_exemption;
2053 if ( $remaining_exemption > 0 ) {
2054 my $addl = $remaining_exemption > $taxable_per_month
2055 ? $taxable_per_month
2056 : $remaining_exemption;
2057 $taxable_charged -= $addl;
2059 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2060 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2061 'taxnum' => $tax->taxnum,
2062 'year' => 1900+$year,
2064 'amount' => sprintf("%.2f", $addl ),
2066 $error = $cust_tax_exempt_pkg->insert;
2068 $dbh->rollback if $oldAutoCommit;
2069 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2071 } # if $remaining_exemption > 0
2075 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2076 until ( $mon < 13 ) { $mon -= 12; $year++; }
2078 } #foreach $which_month
2080 } #if $tax->exempt_amount
2082 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2084 #$tax += $taxable_charged * $cust_main_county->tax / 100
2085 $tax{ $tax->taxname || 'Tax' } +=
2086 $taxable_charged * $tax->tax / 100
2088 } #foreach my $tax ( @taxes )
2090 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2092 } #if $setup != 0 || $recur != 0
2094 } #if $cust_pkg->modified
2096 } #foreach my $cust_pkg
2098 unless ( $cust_bill->cust_bill_pkg ) {
2099 $cust_bill->delete; #don't create an invoice w/o line items
2100 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2104 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2106 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2107 my $tax = sprintf("%.2f", $tax{$taxname} );
2108 $charged = sprintf( "%.2f", $charged+$tax );
2110 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2111 'invnum' => $invnum,
2117 'itemdesc' => $taxname,
2119 $error = $cust_bill_pkg->insert;
2121 $dbh->rollback if $oldAutoCommit;
2122 return "can't create invoice line item for invoice #$invnum: $error";
2124 $total_setup += $tax;
2128 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2129 $error = $cust_bill->replace;
2131 $dbh->rollback if $oldAutoCommit;
2132 return "can't update charged for invoice #$invnum: $error";
2135 foreach my $hook ( @precommit_hooks ) {
2137 &{$hook}; #($self) ?
2140 $dbh->rollback if $oldAutoCommit;
2141 return "$@ running precommit hook $hook\n";
2145 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2149 =item collect OPTIONS
2151 (Attempt to) collect money for this customer's outstanding invoices (see
2152 L<FS::cust_bill>). Usually used after the bill method.
2154 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2155 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2156 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2158 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2159 and the invoice events web interface.
2161 If there is an error, returns the error, otherwise returns false.
2163 Options are passed as name-value pairs.
2165 Currently available options are:
2167 invoice_time - Use this time when deciding when to print invoices and
2168 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>
2169 for conversion functions.
2171 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2174 quiet - set true to surpress email card/ACH decline notices.
2176 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2179 payby - allows for one time override of normal customer billing method
2184 my( $self, %options ) = @_;
2185 my $invoice_time = $options{'invoice_time'} || time;
2188 local $SIG{HUP} = 'IGNORE';
2189 local $SIG{INT} = 'IGNORE';
2190 local $SIG{QUIT} = 'IGNORE';
2191 local $SIG{TERM} = 'IGNORE';
2192 local $SIG{TSTP} = 'IGNORE';
2193 local $SIG{PIPE} = 'IGNORE';
2195 my $oldAutoCommit = $FS::UID::AutoCommit;
2196 local $FS::UID::AutoCommit = 0;
2199 $self->select_for_update; #mutex
2201 my $balance = $self->balance;
2202 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2204 unless ( $balance > 0 ) { #redundant?????
2205 $dbh->rollback if $oldAutoCommit; #hmm
2209 if ( exists($options{'retry_card'}) ) {
2210 carp 'retry_card option passed to collect is deprecated; use retry';
2211 $options{'retry'} ||= $options{'retry_card'};
2213 if ( exists($options{'retry'}) && $options{'retry'} ) {
2214 my $error = $self->retry_realtime;
2216 $dbh->rollback if $oldAutoCommit;
2222 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2223 $extra_sql = " AND freq = '1m' ";
2225 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2228 foreach my $cust_bill ( $self->open_cust_bill ) {
2230 # don't try to charge for the same invoice if it's already in a batch
2231 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2233 last if $self->balance <= 0;
2235 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2238 foreach my $part_bill_event (
2239 sort { $a->seconds <=> $b->seconds
2240 || $a->weight <=> $b->weight
2241 || $a->eventpart <=> $b->eventpart }
2242 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
2243 && ! qsearch( 'cust_bill_event', {
2244 'invnum' => $cust_bill->invnum,
2245 'eventpart' => $_->eventpart,
2250 'table' => 'part_bill_event',
2251 'hashref' => { 'payby' => (exists($options{'payby'})
2255 'disabled' => '', },
2256 'extra_sql' => $extra_sql,
2260 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2261 || $self->balance <= 0; # or if balance<=0
2263 warn " calling invoice event (". $part_bill_event->eventcode. ")\n"
2265 my $cust_main = $self; #for callback
2269 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2270 local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
2271 $error = eval $part_bill_event->eventcode;
2275 my $statustext = '';
2279 } elsif ( $error ) {
2281 $statustext = $error;
2286 #add cust_bill_event
2287 my $cust_bill_event = new FS::cust_bill_event {
2288 'invnum' => $cust_bill->invnum,
2289 'eventpart' => $part_bill_event->eventpart,
2290 #'_date' => $invoice_time,
2292 'status' => $status,
2293 'statustext' => $statustext,
2295 $error = $cust_bill_event->insert;
2297 #$dbh->rollback if $oldAutoCommit;
2298 #return "error: $error";
2300 # gah, even with transactions.
2301 $dbh->commit if $oldAutoCommit; #well.
2302 my $e = 'WARNING: Event run but database not updated - '.
2303 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
2304 ', eventpart '. $part_bill_event->eventpart.
2315 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2320 =item retry_realtime
2322 Schedules realtime credit card / electronic check / LEC billing events for
2323 for retry. Useful if card information has changed or manual retry is desired.
2324 The 'collect' method must be called to actually retry the transaction.
2326 Implementation details: For each of this customer's open invoices, changes
2327 the status of the first "done" (with statustext error) realtime processing
2332 sub retry_realtime {
2335 local $SIG{HUP} = 'IGNORE';
2336 local $SIG{INT} = 'IGNORE';
2337 local $SIG{QUIT} = 'IGNORE';
2338 local $SIG{TERM} = 'IGNORE';
2339 local $SIG{TSTP} = 'IGNORE';
2340 local $SIG{PIPE} = 'IGNORE';
2342 my $oldAutoCommit = $FS::UID::AutoCommit;
2343 local $FS::UID::AutoCommit = 0;
2346 foreach my $cust_bill (
2347 grep { $_->cust_bill_event }
2348 $self->open_cust_bill
2350 my @cust_bill_event =
2351 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2353 #$_->part_bill_event->plan eq 'realtime-card'
2354 $_->part_bill_event->eventcode =~
2355 /\$cust_bill\->realtime_(card|ach|lec)/
2356 && $_->status eq 'done'
2359 $cust_bill->cust_bill_event;
2360 next unless @cust_bill_event;
2361 my $error = $cust_bill_event[0]->retry;
2363 $dbh->rollback if $oldAutoCommit;
2364 return "error scheduling invoice event for retry: $error";
2369 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2374 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2376 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2377 via a Business::OnlinePayment realtime gateway. See
2378 L<http://420.am/business-onlinepayment> for supported gateways.
2380 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2382 Available options are: I<description>, I<invnum>, I<quiet>
2384 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2385 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2386 if set, will override the value from the customer record.
2388 I<description> is a free-text field passed to the gateway. It defaults to
2389 "Internet services".
2391 If an I<invnum> is specified, this payment (if successful) is applied to the
2392 specified invoice. If you don't specify an I<invnum> you might want to
2393 call the B<apply_payments> method.
2395 I<quiet> can be set true to surpress email decline notices.
2397 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2402 my( $self, $method, $amount, %options ) = @_;
2404 warn "$me realtime_bop: $method $amount\n";
2405 warn " $_ => $options{$_}\n" foreach keys %options;
2408 $options{'description'} ||= 'Internet services';
2410 eval "use Business::OnlinePayment";
2413 my $payinfo = exists($options{'payinfo'})
2414 ? $options{'payinfo'}
2422 if ( $options{'invnum'} ) {
2423 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2424 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2426 map { $_->part_pkg->taxclass }
2428 map { $_->cust_pkg }
2429 $cust_bill->cust_bill_pkg;
2430 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2431 #different taxclasses
2432 $taxclass = $taxclasses[0];
2436 #look for an agent gateway override first
2438 if ( $method eq 'CC' ) {
2439 $cardtype = cardtype($payinfo);
2440 } elsif ( $method eq 'ECHECK' ) {
2443 $cardtype = $method;
2447 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2448 cardtype => $cardtype,
2449 taxclass => $taxclass, } )
2450 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2452 taxclass => $taxclass, } )
2453 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2454 cardtype => $cardtype,
2456 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2458 taxclass => '', } );
2460 my $payment_gateway = '';
2461 my( $processor, $login, $password, $action, @bop_options );
2462 if ( $override ) { #use a payment gateway override
2464 $payment_gateway = $override->payment_gateway;
2466 $processor = $payment_gateway->gateway_module;
2467 $login = $payment_gateway->gateway_username;
2468 $password = $payment_gateway->gateway_password;
2469 $action = $payment_gateway->gateway_action;
2470 @bop_options = $payment_gateway->options;
2472 } else { #use the standard settings from the config
2474 ( $processor, $login, $password, $action, @bop_options ) =
2475 $self->default_payment_gateway($method);
2483 my $address = exists($options{'address1'})
2484 ? $options{'address1'}
2486 my $address2 = exists($options{'address2'})
2487 ? $options{'address2'}
2489 $address .= ", ". $address2 if length($address2);
2491 my $o_payname = exists($options{'payname'})
2492 ? $options{'payname'}
2494 my($payname, $payfirst, $paylast);
2495 if ( $o_payname && $method ne 'ECHECK' ) {
2496 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2497 or return "Illegal payname $payname";
2498 ($payfirst, $paylast) = ($1, $2);
2500 $payfirst = $self->getfield('first');
2501 $paylast = $self->getfield('last');
2502 $payname = "$payfirst $paylast";
2505 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2506 if ( $conf->exists('emailinvoiceauto')
2507 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2508 push @invoicing_list, $self->all_emails;
2511 my $email = ($conf->exists('business-onlinepayment-email-override'))
2512 ? $conf->config('business-onlinepayment-email-override')
2513 : $invoicing_list[0];
2517 my $payip = exists($options{'payip'})
2520 $content{customer_ip} = $payip
2523 if ( $method eq 'CC' ) {
2525 $content{card_number} = $payinfo;
2526 my $paydate = exists($options{'paydate'})
2527 ? $options{'paydate'}
2529 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2530 $content{expiration} = "$2/$1";
2532 my $paycvv = exists($options{'paycvv'})
2533 ? $options{'paycvv'}
2535 $content{cvv2} = $self->paycvv
2538 my $paystart_month = exists($options{'paystart_month'})
2539 ? $options{'paystart_month'}
2540 : $self->paystart_month;
2542 my $paystart_year = exists($options{'paystart_year'})
2543 ? $options{'paystart_year'}
2544 : $self->paystart_year;
2546 $content{card_start} = "$paystart_month/$paystart_year"
2547 if $paystart_month && $paystart_year;
2549 my $payissue = exists($options{'payissue'})
2550 ? $options{'payissue'}
2552 $content{issue_number} = $payissue if $payissue;
2554 $content{recurring_billing} = 'YES'
2555 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2557 'payinfo' => $payinfo,
2560 } elsif ( $method eq 'ECHECK' ) {
2561 ( $content{account_number}, $content{routing_code} ) =
2562 split('@', $payinfo);
2563 $content{bank_name} = $o_payname;
2564 $content{account_type} = 'CHECKING';
2565 $content{account_name} = $payname;
2566 $content{customer_org} = $self->company ? 'B' : 'I';
2567 $content{customer_ssn} = exists($options{'ss'})
2570 } elsif ( $method eq 'LEC' ) {
2571 $content{phone} = $payinfo;
2575 # run transaction(s)
2578 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2580 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2581 $transaction->content(
2584 'password' => $password,
2585 'action' => $action1,
2586 'description' => $options{'description'},
2587 'amount' => $amount,
2588 'invoice_number' => $options{'invnum'},
2589 'customer_id' => $self->custnum,
2590 'last_name' => $paylast,
2591 'first_name' => $payfirst,
2593 'address' => $address,
2594 'city' => ( exists($options{'city'})
2597 'state' => ( exists($options{'state'})
2600 'zip' => ( exists($options{'zip'})
2603 'country' => ( exists($options{'country'})
2604 ? $options{'country'}
2606 'referer' => 'http://cleanwhisker.420.am/',
2608 'phone' => $self->daytime || $self->night,
2611 $transaction->submit();
2613 if ( $transaction->is_success() && $action2 ) {
2614 my $auth = $transaction->authorization;
2615 my $ordernum = $transaction->can('order_number')
2616 ? $transaction->order_number
2620 new Business::OnlinePayment( $processor, @bop_options );
2627 password => $password,
2628 order_number => $ordernum,
2630 authorization => $auth,
2631 description => $options{'description'},
2634 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2635 transaction_sequence_num local_transaction_date
2636 local_transaction_time AVS_result_code )) {
2637 $capture{$field} = $transaction->$field() if $transaction->can($field);
2640 $capture->content( %capture );
2644 unless ( $capture->is_success ) {
2645 my $e = "Authorization successful but capture failed, custnum #".
2646 $self->custnum. ': '. $capture->result_code.
2647 ": ". $capture->error_message;
2655 # remove paycvv after initial transaction
2658 #false laziness w/misc/process/payment.cgi - check both to make sure working
2660 if ( defined $self->dbdef_table->column('paycvv')
2661 && length($self->paycvv)
2662 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2664 my $error = $self->remove_cvv;
2666 warn "WARNING: error removing cvv: $error\n";
2674 if ( $transaction->is_success() ) {
2676 my %method2payby = (
2683 if ( $payment_gateway ) { # agent override
2684 $paybatch = $payment_gateway->gatewaynum. '-';
2687 $paybatch .= "$processor:". $transaction->authorization;
2689 $paybatch .= ':'. $transaction->order_number
2690 if $transaction->can('order_number')
2691 && length($transaction->order_number);
2693 my $cust_pay = new FS::cust_pay ( {
2694 'custnum' => $self->custnum,
2695 'invnum' => $options{'invnum'},
2698 'payby' => $method2payby{$method},
2699 'payinfo' => $payinfo,
2700 'paybatch' => $paybatch,
2702 my $error = $cust_pay->insert;
2704 $cust_pay->invnum(''); #try again with no specific invnum
2705 my $error2 = $cust_pay->insert;
2707 # gah, even with transactions.
2708 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2709 "error inserting payment ($processor): $error2".
2710 " (previously tried insert with invnum #$options{'invnum'}" .
2716 return ''; #no error
2720 my $perror = "$processor error: ". $transaction->error_message;
2722 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2723 && $conf->exists('emaildecline')
2724 && grep { $_ ne 'POST' } $self->invoicing_list
2725 && ! grep { $transaction->error_message =~ /$_/ }
2726 $conf->config('emaildecline-exclude')
2728 my @templ = $conf->config('declinetemplate');
2729 my $template = new Text::Template (
2731 SOURCE => [ map "$_\n", @templ ],
2732 ) or return "($perror) can't create template: $Text::Template::ERROR";
2733 $template->compile()
2734 or return "($perror) can't compile template: $Text::Template::ERROR";
2736 my $templ_hash = { error => $transaction->error_message };
2738 my $error = send_email(
2739 'from' => $conf->config('invoice_from'),
2740 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2741 'subject' => 'Your payment could not be processed',
2742 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2745 $perror .= " (also received error sending decline notification: $error)"
2755 =item default_payment_gateway
2759 sub default_payment_gateway {
2760 my( $self, $method ) = @_;
2762 die "Real-time processing not enabled\n"
2763 unless $conf->exists('business-onlinepayment');
2766 my $bop_config = 'business-onlinepayment';
2767 $bop_config .= '-ach'
2768 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2769 my ( $processor, $login, $password, $action, @bop_options ) =
2770 $conf->config($bop_config);
2771 $action ||= 'normal authorization';
2772 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2773 die "No real-time processor is enabled - ".
2774 "did you set the business-onlinepayment configuration value?\n"
2777 ( $processor, $login, $password, $action, @bop_options )
2782 Removes the I<paycvv> field from the database directly.
2784 If there is an error, returns the error, otherwise returns false.
2790 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2791 or return dbh->errstr;
2792 $sth->execute($self->custnum)
2793 or return $sth->errstr;
2798 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2800 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2801 via a Business::OnlinePayment realtime gateway. See
2802 L<http://420.am/business-onlinepayment> for supported gateways.
2804 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2806 Available options are: I<amount>, I<reason>, I<paynum>
2808 Most gateways require a reference to an original payment transaction to refund,
2809 so you probably need to specify a I<paynum>.
2811 I<amount> defaults to the original amount of the payment if not specified.
2813 I<reason> specifies a reason for the refund.
2815 Implementation note: If I<amount> is unspecified or equal to the amount of the
2816 orignal payment, first an attempt is made to "void" the transaction via
2817 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2818 the normal attempt is made to "refund" ("credit") the transaction via the
2819 gateway is attempted.
2821 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2822 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2823 #if set, will override the value from the customer record.
2825 #If an I<invnum> is specified, this payment (if successful) is applied to the
2826 #specified invoice. If you don't specify an I<invnum> you might want to
2827 #call the B<apply_payments> method.
2831 #some false laziness w/realtime_bop, not enough to make it worth merging
2832 #but some useful small subs should be pulled out
2833 sub realtime_refund_bop {
2834 my( $self, $method, %options ) = @_;
2836 warn "$me realtime_refund_bop: $method refund\n";
2837 warn " $_ => $options{$_}\n" foreach keys %options;
2840 eval "use Business::OnlinePayment";
2844 # look up the original payment and optionally a gateway for that payment
2848 my $amount = $options{'amount'};
2850 my( $processor, $login, $password, @bop_options ) ;
2851 my( $auth, $order_number ) = ( '', '', '' );
2853 if ( $options{'paynum'} ) {
2855 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
2856 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2857 or return "Unknown paynum $options{'paynum'}";
2858 $amount ||= $cust_pay->paid;
2860 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2861 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2862 $cust_pay->paybatch;
2863 my $gatewaynum = '';
2864 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2866 if ( $gatewaynum ) { #gateway for the payment to be refunded
2868 my $payment_gateway =
2869 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2870 die "payment gateway $gatewaynum not found"
2871 unless $payment_gateway;
2873 $processor = $payment_gateway->gateway_module;
2874 $login = $payment_gateway->gateway_username;
2875 $password = $payment_gateway->gateway_password;
2876 @bop_options = $payment_gateway->options;
2878 } else { #try the default gateway
2880 my( $conf_processor, $unused_action );
2881 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2882 $self->default_payment_gateway($method);
2884 return "processor of payment $options{'paynum'} $processor does not".
2885 " match default processor $conf_processor"
2886 unless $processor eq $conf_processor;
2891 } else { # didn't specify a paynum, so look for agent gateway overrides
2892 # like a normal transaction
2895 if ( $method eq 'CC' ) {
2896 $cardtype = cardtype($self->payinfo);
2897 } elsif ( $method eq 'ECHECK' ) {
2900 $cardtype = $method;
2903 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2904 cardtype => $cardtype,
2906 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2908 taxclass => '', } );
2910 if ( $override ) { #use a payment gateway override
2912 my $payment_gateway = $override->payment_gateway;
2914 $processor = $payment_gateway->gateway_module;
2915 $login = $payment_gateway->gateway_username;
2916 $password = $payment_gateway->gateway_password;
2917 #$action = $payment_gateway->gateway_action;
2918 @bop_options = $payment_gateway->options;
2920 } else { #use the standard settings from the config
2923 ( $processor, $login, $password, $unused_action, @bop_options ) =
2924 $self->default_payment_gateway($method);
2929 return "neither amount nor paynum specified" unless $amount;
2934 'password' => $password,
2935 'order_number' => $order_number,
2936 'amount' => $amount,
2937 'referer' => 'http://cleanwhisker.420.am/',
2939 $content{authorization} = $auth
2940 if length($auth); #echeck/ACH transactions have an order # but no auth
2941 #(at least with authorize.net)
2943 #first try void if applicable
2944 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2945 warn " attempting void\n" if $DEBUG > 1;
2946 my $void = new Business::OnlinePayment( $processor, @bop_options );
2947 $void->content( 'action' => 'void', %content );
2949 if ( $void->is_success ) {
2950 my $error = $cust_pay->void($options{'reason'});
2952 # gah, even with transactions.
2953 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2954 "error voiding payment: $error";
2958 warn " void successful\n" if $DEBUG > 1;
2963 warn " void unsuccessful, trying refund\n"
2967 my $address = $self->address1;
2968 $address .= ", ". $self->address2 if $self->address2;
2970 my($payname, $payfirst, $paylast);
2971 if ( $self->payname && $method ne 'ECHECK' ) {
2972 $payname = $self->payname;
2973 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2974 or return "Illegal payname $payname";
2975 ($payfirst, $paylast) = ($1, $2);
2977 $payfirst = $self->getfield('first');
2978 $paylast = $self->getfield('last');
2979 $payname = "$payfirst $paylast";
2982 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2983 if ( $conf->exists('emailinvoiceauto')
2984 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2985 push @invoicing_list, $self->all_emails;
2988 my $email = ($conf->exists('business-onlinepayment-email-override'))
2989 ? $conf->config('business-onlinepayment-email-override')
2990 : $invoicing_list[0];
2992 my $payip = exists($options{'payip'})
2995 $content{customer_ip} = $payip
2999 if ( $method eq 'CC' ) {
3002 $content{card_number} = $payinfo = $cust_pay->payinfo;
3003 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3004 #$content{expiration} = "$2/$1";
3006 $content{card_number} = $payinfo = $self->payinfo;
3007 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3008 $content{expiration} = "$2/$1";
3011 } elsif ( $method eq 'ECHECK' ) {
3012 ( $content{account_number}, $content{routing_code} ) =
3013 split('@', $payinfo = $self->payinfo);
3014 $content{bank_name} = $self->payname;
3015 $content{account_type} = 'CHECKING';
3016 $content{account_name} = $payname;
3017 $content{customer_org} = $self->company ? 'B' : 'I';
3018 $content{customer_ssn} = $self->ss;
3019 } elsif ( $method eq 'LEC' ) {
3020 $content{phone} = $payinfo = $self->payinfo;
3024 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3025 my %sub_content = $refund->content(
3026 'action' => 'credit',
3027 'customer_id' => $self->custnum,
3028 'last_name' => $paylast,
3029 'first_name' => $payfirst,
3031 'address' => $address,
3032 'city' => $self->city,
3033 'state' => $self->state,
3034 'zip' => $self->zip,
3035 'country' => $self->country,
3037 'phone' => $self->daytime || $self->night,
3040 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3044 return "$processor error: ". $refund->error_message
3045 unless $refund->is_success();
3047 my %method2payby = (
3053 my $paybatch = "$processor:". $refund->authorization;
3054 $paybatch .= ':'. $refund->order_number
3055 if $refund->can('order_number') && $refund->order_number;
3057 while ( $cust_pay && $cust_pay->unappled < $amount ) {
3058 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3059 last unless @cust_bill_pay;
3060 my $cust_bill_pay = pop @cust_bill_pay;
3061 my $error = $cust_bill_pay->delete;
3065 my $cust_refund = new FS::cust_refund ( {
3066 'custnum' => $self->custnum,
3067 'paynum' => $options{'paynum'},
3068 'refund' => $amount,
3070 'payby' => $method2payby{$method},
3071 'payinfo' => $payinfo,
3072 'paybatch' => $paybatch,
3073 'reason' => $options{'reason'} || 'card or ACH refund',
3075 my $error = $cust_refund->insert;
3077 $cust_refund->paynum(''); #try again with no specific paynum
3078 my $error2 = $cust_refund->insert;
3080 # gah, even with transactions.
3081 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3082 "error inserting refund ($processor): $error2".
3083 " (previously tried insert with paynum #$options{'paynum'}" .
3096 Returns the total owed for this customer on all invoices
3097 (see L<FS::cust_bill/owed>).
3103 $self->total_owed_date(2145859200); #12/31/2037
3106 =item total_owed_date TIME
3108 Returns the total owed for this customer on all invoices with date earlier than
3109 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3110 see L<Time::Local> and L<Date::Parse> for conversion functions.
3114 sub total_owed_date {
3118 foreach my $cust_bill (
3119 grep { $_->_date <= $time }
3120 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3122 $total_bill += $cust_bill->owed;
3124 sprintf( "%.2f", $total_bill );
3127 =item apply_credits OPTION => VALUE ...
3129 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3130 to outstanding invoice balances in chronological order (or reverse
3131 chronological order if the I<order> option is set to B<newest>) and returns the
3132 value of any remaining unapplied credits available for refund (see
3133 L<FS::cust_refund>).
3141 return 0 unless $self->total_credited;
3143 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3144 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3146 my @invoices = $self->open_cust_bill;
3147 @invoices = sort { $b->_date <=> $a->_date } @invoices
3148 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3151 foreach my $cust_bill ( @invoices ) {
3154 if ( !defined($credit) || $credit->credited == 0) {
3155 $credit = pop @credits or last;
3158 if ($cust_bill->owed >= $credit->credited) {
3159 $amount=$credit->credited;
3161 $amount=$cust_bill->owed;
3164 my $cust_credit_bill = new FS::cust_credit_bill ( {
3165 'crednum' => $credit->crednum,
3166 'invnum' => $cust_bill->invnum,
3167 'amount' => $amount,
3169 my $error = $cust_credit_bill->insert;
3170 die $error if $error;
3172 redo if ($cust_bill->owed > 0);
3176 return $self->total_credited;
3179 =item apply_payments
3181 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3182 to outstanding invoice balances in chronological order.
3184 #and returns the value of any remaining unapplied payments.
3188 sub apply_payments {
3193 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3194 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3196 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3197 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3201 foreach my $cust_bill ( @invoices ) {
3204 if ( !defined($payment) || $payment->unapplied == 0 ) {
3205 $payment = pop @payments or last;
3208 if ( $cust_bill->owed >= $payment->unapplied ) {
3209 $amount = $payment->unapplied;
3211 $amount = $cust_bill->owed;
3214 my $cust_bill_pay = new FS::cust_bill_pay ( {
3215 'paynum' => $payment->paynum,
3216 'invnum' => $cust_bill->invnum,
3217 'amount' => $amount,
3219 my $error = $cust_bill_pay->insert;
3220 die $error if $error;
3222 redo if ( $cust_bill->owed > 0);
3226 return $self->total_unapplied_payments;
3229 =item total_credited
3231 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3232 customer. See L<FS::cust_credit/credited>.
3236 sub total_credited {
3238 my $total_credit = 0;
3239 foreach my $cust_credit ( qsearch('cust_credit', {
3240 'custnum' => $self->custnum,
3242 $total_credit += $cust_credit->credited;
3244 sprintf( "%.2f", $total_credit );
3247 =item total_unapplied_payments
3249 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3250 See L<FS::cust_pay/unapplied>.
3254 sub total_unapplied_payments {
3256 my $total_unapplied = 0;
3257 foreach my $cust_pay ( qsearch('cust_pay', {
3258 'custnum' => $self->custnum,
3260 $total_unapplied += $cust_pay->unapplied;
3262 sprintf( "%.2f", $total_unapplied );
3267 Returns the balance for this customer (total_owed minus total_credited
3268 minus total_unapplied_payments).
3275 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
3279 =item balance_date TIME
3281 Returns the balance for this customer, only considering invoices with date
3282 earlier than TIME (total_owed_date minus total_credited minus
3283 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3284 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3293 $self->total_owed_date($time)
3294 - $self->total_credited
3295 - $self->total_unapplied_payments
3299 =item in_transit_payments
3301 Returns the total of requests for payments for this customer pending in
3302 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3306 sub in_transit_payments {
3308 my $in_transit_payments = 0;
3309 foreach my $pay_batch ( qsearch('pay_batch', {
3312 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3313 'batchnum' => $pay_batch->batchnum,
3314 'custnum' => $self->custnum,
3316 $in_transit_payments += $cust_pay_batch->amount;
3319 sprintf( "%.2f", $in_transit_payments );
3322 =item paydate_monthyear
3324 Returns a two-element list consisting of the month and year of this customer's
3325 paydate (credit card expiration date for CARD customers)
3329 sub paydate_monthyear {
3331 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3333 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3340 =item payinfo_masked
3342 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.
3344 Credit Cards - Mask all but the last four characters.
3345 Checks - Mask all but last 2 of account number and bank routing number.
3346 Others - Do nothing, return the unmasked string.
3350 sub payinfo_masked {
3352 return $self->paymask;
3355 =item invoicing_list [ ARRAYREF ]
3357 If an arguement is given, sets these email addresses as invoice recipients
3358 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3359 (except as warnings), so use check_invoicing_list first.
3361 Returns a list of email addresses (with svcnum entries expanded).
3363 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3364 check it without disturbing anything by passing nothing.
3366 This interface may change in the future.
3370 sub invoicing_list {
3371 my( $self, $arrayref ) = @_;
3374 my @cust_main_invoice;
3375 if ( $self->custnum ) {
3376 @cust_main_invoice =
3377 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3379 @cust_main_invoice = ();
3381 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3382 #warn $cust_main_invoice->destnum;
3383 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3384 #warn $cust_main_invoice->destnum;
3385 my $error = $cust_main_invoice->delete;
3386 warn $error if $error;
3389 if ( $self->custnum ) {
3390 @cust_main_invoice =
3391 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3393 @cust_main_invoice = ();
3395 my %seen = map { $_->address => 1 } @cust_main_invoice;
3396 foreach my $address ( @{$arrayref} ) {
3397 next if exists $seen{$address} && $seen{$address};
3398 $seen{$address} = 1;
3399 my $cust_main_invoice = new FS::cust_main_invoice ( {
3400 'custnum' => $self->custnum,
3403 my $error = $cust_main_invoice->insert;
3404 warn $error if $error;
3408 if ( $self->custnum ) {
3410 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3417 =item check_invoicing_list ARRAYREF
3419 Checks these arguements as valid input for the invoicing_list method. If there
3420 is an error, returns the error, otherwise returns false.
3424 sub check_invoicing_list {
3425 my( $self, $arrayref ) = @_;
3426 foreach my $address ( @{$arrayref} ) {
3428 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3429 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3432 my $cust_main_invoice = new FS::cust_main_invoice ( {
3433 'custnum' => $self->custnum,
3436 my $error = $self->custnum
3437 ? $cust_main_invoice->check
3438 : $cust_main_invoice->checkdest
3440 return $error if $error;
3445 =item set_default_invoicing_list
3447 Sets the invoicing list to all accounts associated with this customer,
3448 overwriting any previous invoicing list.
3452 sub set_default_invoicing_list {
3454 $self->invoicing_list($self->all_emails);
3459 Returns the email addresses of all accounts provisioned for this customer.
3466 foreach my $cust_pkg ( $self->all_pkgs ) {
3467 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3469 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3470 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3472 $list{$_}=1 foreach map { $_->email } @svc_acct;
3477 =item invoicing_list_addpost
3479 Adds postal invoicing to this customer. If this customer is already configured
3480 to receive postal invoices, does nothing.
3484 sub invoicing_list_addpost {
3486 return if grep { $_ eq 'POST' } $self->invoicing_list;
3487 my @invoicing_list = $self->invoicing_list;
3488 push @invoicing_list, 'POST';
3489 $self->invoicing_list(\@invoicing_list);
3492 =item invoicing_list_emailonly
3494 Returns the list of email invoice recipients (invoicing_list without non-email
3495 destinations such as POST and FAX).
3499 sub invoicing_list_emailonly {
3501 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3504 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3506 Returns an array of customers referred by this customer (referral_custnum set
3507 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3508 customers referred by customers referred by this customer and so on, inclusive.
3509 The default behavior is DEPTH 1 (no recursion).
3513 sub referral_cust_main {
3515 my $depth = @_ ? shift : 1;
3516 my $exclude = @_ ? shift : {};
3519 map { $exclude->{$_->custnum}++; $_; }
3520 grep { ! $exclude->{ $_->custnum } }
3521 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3525 map { $_->referral_cust_main($depth-1, $exclude) }
3532 =item referral_cust_main_ncancelled
3534 Same as referral_cust_main, except only returns customers with uncancelled
3539 sub referral_cust_main_ncancelled {
3541 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3544 =item referral_cust_pkg [ DEPTH ]
3546 Like referral_cust_main, except returns a flat list of all unsuspended (and
3547 uncancelled) packages for each customer. The number of items in this list may
3548 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3552 sub referral_cust_pkg {
3554 my $depth = @_ ? shift : 1;
3556 map { $_->unsuspended_pkgs }
3557 grep { $_->unsuspended_pkgs }
3558 $self->referral_cust_main($depth);
3561 =item referring_cust_main
3563 Returns the single cust_main record for the customer who referred this customer
3564 (referral_custnum), or false.
3568 sub referring_cust_main {
3570 return '' unless $self->referral_custnum;
3571 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3574 =item credit AMOUNT, REASON
3576 Applies a credit to this customer. If there is an error, returns the error,
3577 otherwise returns false.
3582 my( $self, $amount, $reason ) = @_;
3583 my $cust_credit = new FS::cust_credit {
3584 'custnum' => $self->custnum,
3585 'amount' => $amount,
3586 'reason' => $reason,
3588 $cust_credit->insert;
3591 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3593 Creates a one-time charge for this customer. If there is an error, returns
3594 the error, otherwise returns false.
3599 my ( $self, $amount ) = ( shift, shift );
3600 my $pkg = @_ ? shift : 'One-time charge';
3601 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3602 my $taxclass = @_ ? shift : '';
3604 local $SIG{HUP} = 'IGNORE';
3605 local $SIG{INT} = 'IGNORE';
3606 local $SIG{QUIT} = 'IGNORE';
3607 local $SIG{TERM} = 'IGNORE';
3608 local $SIG{TSTP} = 'IGNORE';
3609 local $SIG{PIPE} = 'IGNORE';
3611 my $oldAutoCommit = $FS::UID::AutoCommit;
3612 local $FS::UID::AutoCommit = 0;
3615 my $part_pkg = new FS::part_pkg ( {
3617 'comment' => $comment,
3618 #'setup' => $amount,
3621 'plandata' => "setup_fee=$amount",
3624 'taxclass' => $taxclass,
3627 my $error = $part_pkg->insert;
3629 $dbh->rollback if $oldAutoCommit;
3633 my $pkgpart = $part_pkg->pkgpart;
3634 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3635 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3636 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3637 $error = $type_pkgs->insert;
3639 $dbh->rollback if $oldAutoCommit;
3644 my $cust_pkg = new FS::cust_pkg ( {
3645 'custnum' => $self->custnum,
3646 'pkgpart' => $pkgpart,
3649 $error = $cust_pkg->insert;
3651 $dbh->rollback if $oldAutoCommit;
3655 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3662 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3668 sort { $a->_date <=> $b->_date }
3669 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3672 =item open_cust_bill
3674 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3679 sub open_cust_bill {
3681 grep { $_->owed > 0 } $self->cust_bill;
3686 Returns all the credits (see L<FS::cust_credit>) for this customer.
3692 sort { $a->_date <=> $b->_date }
3693 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3698 Returns all the payments (see L<FS::cust_pay>) for this customer.
3704 sort { $a->_date <=> $b->_date }
3705 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3710 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3716 sort { $a->_date <=> $b->_date }
3717 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3723 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3729 sort { $a->_date <=> $b->_date }
3730 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3733 =item select_for_update
3735 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3740 sub select_for_update {
3742 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3747 Returns a name string for this customer, either "Company (Last, First)" or
3754 my $name = $self->contact;
3755 $name = $self->company. " ($name)" if $self->company;
3761 Returns a name string for this (service/shipping) contact, either
3762 "Company (Last, First)" or "Last, First".
3768 if ( $self->get('ship_last') ) {
3769 my $name = $self->ship_contact;
3770 $name = $self->ship_company. " ($name)" if $self->ship_company;
3779 Returns this customer's full (billing) contact name only, "Last, First"
3785 $self->get('last'). ', '. $self->first;
3790 Returns this customer's full (shipping) contact name only, "Last, First"
3796 $self->get('ship_last')
3797 ? $self->get('ship_last'). ', '. $self->ship_first
3803 Returns this customer's full country name
3809 code2country($self->country);
3814 Returns a status string for this customer, currently:
3818 =item prospect - No packages have ever been ordered
3820 =item active - One or more recurring packages is active
3822 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3824 =item suspended - All non-cancelled recurring packages are suspended
3826 =item cancelled - All recurring packages are cancelled
3834 for my $status (qw( prospect active inactive suspended cancelled )) {
3835 my $method = $status.'_sql';
3836 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3837 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3838 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3839 return $status if $sth->fetchrow_arrayref->[0];
3845 Returns a hex triplet color string for this customer's status.
3849 use vars qw(%statuscolor);
3851 'prospect' => '7e0079', #'000000', #black? naw, purple
3852 'active' => '00CC00', #green
3853 'inactive' => '0000CC', #blue
3854 'suspended' => 'FF9900', #yellow
3855 'cancelled' => 'FF0000', #red
3860 $statuscolor{$self->status};
3865 =head1 CLASS METHODS
3871 Returns an SQL expression identifying prospective cust_main records (customers
3872 with no packages ever ordered)
3876 use vars qw($select_count_pkgs);
3877 $select_count_pkgs =
3878 "SELECT COUNT(*) FROM cust_pkg
3879 WHERE cust_pkg.custnum = cust_main.custnum";
3881 sub select_count_pkgs_sql {
3885 sub prospect_sql { "
3886 0 = ( $select_count_pkgs )
3891 Returns an SQL expression identifying active cust_main records (customers with
3892 no active recurring packages, but otherwise unsuspended/uncancelled).
3897 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
3903 Returns an SQL expression identifying inactive cust_main records (customers with
3904 active recurring packages).
3908 sub inactive_sql { "
3909 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3911 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
3917 Returns an SQL expression identifying suspended cust_main records.
3922 sub suspended_sql { susp_sql(@_); }
3924 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
3926 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3932 Returns an SQL expression identifying cancelled cust_main records.
3936 sub cancelled_sql { cancel_sql(@_); }
3939 my $recurring_sql = FS::cust_pkg->recurring_sql;
3940 #my $recurring_sql = "
3941 # '0' != ( select freq from part_pkg
3942 # where cust_pkg.pkgpart = part_pkg.pkgpart )
3946 0 < ( $select_count_pkgs )
3947 AND 0 = ( $select_count_pkgs AND $recurring_sql
3948 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3954 =item uncancelled_sql
3956 Returns an SQL expression identifying un-cancelled cust_main records.
3960 sub uncancelled_sql { uncancel_sql(@_); }
3961 sub uncancel_sql { "
3962 ( 0 < ( $select_count_pkgs
3963 AND ( cust_pkg.cancel IS NULL
3964 OR cust_pkg.cancel = 0
3967 OR 0 = ( $select_count_pkgs )
3971 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3973 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3974 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
3975 appropriate ship_ field is also searched).
3977 Additional options are the same as FS::Record::qsearch
3982 my( $self, $fuzzy, $hash, @opt) = @_;
3987 check_and_rebuild_fuzzyfiles();
3988 foreach my $field ( keys %$fuzzy ) {
3990 $match{$_}=1 foreach ( amatch( $fuzzy->{$field},
3992 @{ $self->all_X($field) }
3997 foreach ( keys %match ) {
3998 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3999 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
4002 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
4005 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
4007 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
4019 =item smart_search OPTION => VALUE ...
4021 Accepts the following options: I<search>, the string to search for. The string
4022 will be searched for as a customer number, phone number, name or company name,
4023 first searching for an exact match then fuzzy and substring matches (in some
4024 cases - see the source code for the exact heuristics used).
4026 Any additional options treated as an additional qualifier on the search
4029 Returns a (possibly empty) array of FS::cust_main objects.
4036 #here is the agent virtualization
4037 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
4041 my $search = delete $options{'search'};
4042 ( my $alphanum_search = $search ) =~ s/\W//g;
4044 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
4046 #false laziness w/Record::ut_phone
4047 my $phonen = "$1-$2-$3";
4048 $phonen .= " x$4" if $4;
4050 push @cust_main, qsearch( {
4051 'table' => 'cust_main',
4052 'hashref' => { %options },
4053 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4055 join(' OR ', map "$_ = '$phonen'",
4056 qw( daytime night fax
4057 ship_daytime ship_night ship_fax )
4060 " AND $agentnums_sql", #agent virtualization
4063 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
4064 #try looking for matches with extensions unless one was specified
4066 push @cust_main, qsearch( {
4067 'table' => 'cust_main',
4068 'hashref' => { %options },
4069 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4071 join(' OR ', map "$_ LIKE '$phonen\%'",
4073 ship_daytime ship_night )
4076 " AND $agentnums_sql", #agent virtualization
4081 } elsif ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
4083 push @cust_main, qsearch( {
4084 'table' => 'cust_main',
4085 'hashref' => { 'custnum' => $1, %options },
4086 'extra_sql' => " AND $agentnums_sql", #agent virtualization
4089 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
4091 my($company, $last, $first) = ( $1, $2, $3 );
4093 # "Company (Last, First)"
4094 #this is probably something a browser remembered,
4095 #so just do an exact search
4097 foreach my $prefix ( '', 'ship_' ) {
4098 push @cust_main, qsearch( {
4099 'table' => 'cust_main',
4100 'hashref' => { $prefix.'first' => $first,
4101 $prefix.'last' => $last,
4102 $prefix.'company' => $company,
4105 'extra_sql' => " AND $agentnums_sql",
4109 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
4110 # try (ship_){last,company}
4114 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
4115 # # full strings the browser remembers won't work
4116 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
4118 use Lingua::EN::NameParse;
4119 my $NameParse = new Lingua::EN::NameParse(
4121 allow_reversed => 1,
4124 my($last, $first) = ( '', '' );
4125 #maybe disable this too and just rely on NameParse?
4126 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
4128 ($last, $first) = ( $1, $2 );
4130 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
4131 } elsif ( ! $NameParse->parse($value) ) {
4133 my %name = $NameParse->components;
4134 $first = $name{'given_name_1'};
4135 $last = $name{'surname_1'};
4139 if ( $first && $last ) {
4141 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
4144 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4146 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
4147 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
4150 push @cust_main, qsearch( {
4151 'table' => 'cust_main',
4152 'hashref' => \%options,
4153 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4156 # or it just be something that was typed in... (try that in a sec)
4160 my $q_value = dbh->quote($value);
4163 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4164 $sql .= " ( LOWER(last) = $q_value
4165 OR LOWER(company) = $q_value
4166 OR LOWER(ship_last) = $q_value
4167 OR LOWER(ship_company) = $q_value
4170 push @cust_main, qsearch( {
4171 'table' => 'cust_main',
4172 'hashref' => \%options,
4173 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4176 unless ( @cust_main ) { #no exact match, trying substring/fuzzy
4178 #still some false laziness w/ search/cust_main.cgi
4183 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
4184 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
4187 if ( $first && $last ) {
4190 { 'first' => { op=>'ILIKE', value=>"%$first%" },
4191 'last' => { op=>'ILIKE', value=>"%$last%" },
4193 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
4194 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
4201 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
4202 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
4206 foreach my $hashref ( @hashrefs ) {
4208 push @cust_main, qsearch( {
4209 'table' => 'cust_main',
4210 'hashref' => { %$hashref,
4213 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
4222 " AND $agentnums_sql", #extra_sql #agent virtualization
4225 if ( $first && $last ) {
4226 push @cust_main, FS::cust_main->fuzzy_search(
4227 { 'last' => $last, #fuzzy hashref
4228 'first' => $first }, #
4232 foreach my $field ( 'last', 'company' ) {
4234 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
4239 #eliminate duplicates
4241 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
4249 =item check_and_rebuild_fuzzyfiles
4253 use vars qw(@fuzzyfields);
4254 @fuzzyfields = ( 'last', 'first', 'company' );
4256 sub check_and_rebuild_fuzzyfiles {
4257 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4258 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
4261 =item rebuild_fuzzyfiles
4265 sub rebuild_fuzzyfiles {
4267 use Fcntl qw(:flock);
4269 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4270 mkdir $dir, 0700 unless -d $dir;
4272 foreach my $fuzzy ( @fuzzyfields ) {
4274 open(LOCK,">>$dir/cust_main.$fuzzy")
4275 or die "can't open $dir/cust_main.$fuzzy: $!";
4277 or die "can't lock $dir/cust_main.$fuzzy: $!";
4279 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
4280 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
4282 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
4283 my $sth = dbh->prepare("SELECT $field FROM cust_main".
4284 " WHERE $field != '' AND $field IS NOT NULL");
4285 $sth->execute or die $sth->errstr;
4287 while ( my $row = $sth->fetchrow_arrayref ) {
4288 print CACHE $row->[0]. "\n";
4293 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
4295 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
4306 my( $self, $field ) = @_;
4307 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4308 open(CACHE,"<$dir/cust_main.$field")
4309 or die "can't open $dir/cust_main.$field: $!";
4310 my @array = map { chomp; $_; } <CACHE>;
4315 =item append_fuzzyfiles LASTNAME COMPANY
4319 sub append_fuzzyfiles {
4320 #my( $first, $last, $company ) = @_;
4322 &check_and_rebuild_fuzzyfiles;
4324 use Fcntl qw(:flock);
4326 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4328 foreach my $field (qw( first last company )) {
4333 open(CACHE,">>$dir/cust_main.$field")
4334 or die "can't open $dir/cust_main.$field: $!";
4335 flock(CACHE,LOCK_EX)
4336 or die "can't lock $dir/cust_main.$field: $!";
4338 print CACHE "$value\n";
4340 flock(CACHE,LOCK_UN)
4341 or die "can't unlock $dir/cust_main.$field: $!";
4356 #warn join('-',keys %$param);
4357 my $fh = $param->{filehandle};
4358 my $agentnum = $param->{agentnum};
4360 my $refnum = $param->{refnum};
4361 my $pkgpart = $param->{pkgpart};
4363 #my @fields = @{$param->{fields}};
4364 my $format = $param->{'format'};
4367 if ( $format eq 'simple' ) {
4368 @fields = qw( cust_pkg.setup dayphone first last
4369 address1 address2 city state zip comments );
4371 } elsif ( $format eq 'extended' ) {
4372 @fields = qw( agent_custid refnum
4373 last first address1 address2 city state zip country
4375 ship_last ship_first ship_address1 ship_address2
4376 ship_city ship_state ship_zip ship_country
4377 payinfo paycvv paydate
4380 svc_acct.username svc_acct._password
4384 die "unknown format $format";
4387 eval "use Text::CSV_XS;";
4390 my $csv = new Text::CSV_XS;
4397 local $SIG{HUP} = 'IGNORE';
4398 local $SIG{INT} = 'IGNORE';
4399 local $SIG{QUIT} = 'IGNORE';
4400 local $SIG{TERM} = 'IGNORE';
4401 local $SIG{TSTP} = 'IGNORE';
4402 local $SIG{PIPE} = 'IGNORE';
4404 my $oldAutoCommit = $FS::UID::AutoCommit;
4405 local $FS::UID::AutoCommit = 0;
4408 #while ( $columns = $csv->getline($fh) ) {
4410 while ( defined($line=<$fh>) ) {
4412 $csv->parse($line) or do {
4413 $dbh->rollback if $oldAutoCommit;
4414 return "can't parse: ". $csv->error_input();
4417 my @columns = $csv->fields();
4418 #warn join('-',@columns);
4421 agentnum => $agentnum,
4423 country => $conf->config('countrydefault') || 'US',
4424 payby => $payby, #default
4425 paydate => '12/2037', #default
4427 my $billtime = time;
4428 my %cust_pkg = ( pkgpart => $pkgpart );
4430 foreach my $field ( @fields ) {
4432 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|expire|cancel)$/ ) {
4434 #$cust_pkg{$1} = str2time( shift @$columns );
4435 if ( $1 eq 'pkgpart' ) {
4436 $cust_pkg{$1} = shift @columns;
4437 } elsif ( $1 eq 'setup' ) {
4438 $billtime = str2time(shift @columns);
4440 $cust_pkg{$1} = str2time( shift @columns );
4443 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
4445 $svc_acct{$1} = shift @columns;
4449 #refnum interception
4450 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
4452 my $referral = $columns[0];
4453 my $part_referral = new FS::part_referral {
4454 'referral' => $referral,
4455 'agentnum' => $agentnum,
4458 my $error = $part_referral->insert;
4460 $dbh->rollback if $oldAutoCommit;
4461 return "can't auto-insert advertising source: $referral: $error";
4463 $columns[0] = $part_referral->refnum;
4466 #$cust_main{$field} = shift @$columns;
4467 $cust_main{$field} = shift @columns;
4471 my $invoicing_list = $cust_main{'invoicing_list'}
4472 ? [ delete $cust_main{'invoicing_list'} ]
4475 my $cust_main = new FS::cust_main ( \%cust_main );
4478 tie my %hash, 'Tie::RefHash'; #this part is important
4480 if ( $cust_pkg{'pkgpart'} ) {
4481 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
4484 if ( $svc_acct{'username'} ) {
4485 $svc_acct{svcpart} = $cust_pkg->part_pkg->svcpart( 'svc_acct' );
4486 push @svc_acct, new FS::svc_acct ( \%svc_acct )
4489 $hash{$cust_pkg} = \@svc_acct;
4492 my $error = $cust_main->insert( \%hash, $invoicing_list );
4495 $dbh->rollback if $oldAutoCommit;
4496 return "can't insert customer for $line: $error";
4499 if ( $format eq 'simple' ) {
4501 #false laziness w/bill.cgi
4502 $error = $cust_main->bill( 'time' => $billtime );
4504 $dbh->rollback if $oldAutoCommit;
4505 return "can't bill customer for $line: $error";
4508 $cust_main->apply_payments;
4509 $cust_main->apply_credits;
4511 $error = $cust_main->collect();
4513 $dbh->rollback if $oldAutoCommit;
4514 return "can't collect customer for $line: $error";
4522 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4524 return "Empty file!" unless $imported;
4536 #warn join('-',keys %$param);
4537 my $fh = $param->{filehandle};
4538 my @fields = @{$param->{fields}};
4540 eval "use Text::CSV_XS;";
4543 my $csv = new Text::CSV_XS;
4550 local $SIG{HUP} = 'IGNORE';
4551 local $SIG{INT} = 'IGNORE';
4552 local $SIG{QUIT} = 'IGNORE';
4553 local $SIG{TERM} = 'IGNORE';
4554 local $SIG{TSTP} = 'IGNORE';
4555 local $SIG{PIPE} = 'IGNORE';
4557 my $oldAutoCommit = $FS::UID::AutoCommit;
4558 local $FS::UID::AutoCommit = 0;
4561 #while ( $columns = $csv->getline($fh) ) {
4563 while ( defined($line=<$fh>) ) {
4565 $csv->parse($line) or do {
4566 $dbh->rollback if $oldAutoCommit;
4567 return "can't parse: ". $csv->error_input();
4570 my @columns = $csv->fields();
4571 #warn join('-',@columns);
4574 foreach my $field ( @fields ) {
4575 $row{$field} = shift @columns;
4578 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4579 unless ( $cust_main ) {
4580 $dbh->rollback if $oldAutoCommit;
4581 return "unknown custnum $row{'custnum'}";
4584 if ( $row{'amount'} > 0 ) {
4585 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4587 $dbh->rollback if $oldAutoCommit;
4591 } elsif ( $row{'amount'} < 0 ) {
4592 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4595 $dbh->rollback if $oldAutoCommit;
4605 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4607 return "Empty file!" unless $imported;
4619 The delete method should possibly take an FS::cust_main object reference
4620 instead of a scalar customer number.
4622 Bill and collect options should probably be passed as references instead of a
4625 There should probably be a configuration file with a list of allowed credit
4628 No multiple currency support (probably a larger project than just this module).
4630 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4634 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4635 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4636 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.