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_sth = dbh->prepare( "SELECT $sel_columns FROM $child_table".
536 " WHERE $primary_key = $sourceid")
537 or return dbh->errstr;
539 $sel_sth->execute or return $sel_sth->errstr;
541 while ( my $row = $sel_sth->fetchrow_hashref ) {
543 warn " selected row: ".
544 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
548 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
549 my $ins_sth =dbh->prepare($statement)
550 or return dbh->errstr;
551 my @param = ( $destid, map $row->{$_}, @ins_columns );
552 warn " $statement: [ ". join(', ', @param). " ]\n"
554 $ins_sth->execute( @param )
555 or return $ins_sth->errstr;
557 #next unless keys %{ $child_tables{$child_table} };
558 next unless $sequence;
560 #another section of that laziness
561 my $seq_sql = "SELECT currval('$sequence')";
562 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
563 $seq_sth->execute or return $seq_sth->errstr;
564 my $insertid = $seq_sth->fetchrow_arrayref->[0];
566 # don't drink soap! recurse! recurse! okay!
568 _copy_skel( $child_table,
569 $row->{$child_pkey}, #sourceid
571 %{ $child_tables{$child_table} },
573 return $error if $error;
583 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
585 Like the insert method on an existing record, this method orders a package
586 and included services atomicaly. Pass a Tie::RefHash data structure to this
587 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
588 be a better explanation of this, but until then, here's an example:
591 tie %hash, 'Tie::RefHash'; #this part is important
593 $cust_pkg => [ $svc_acct ],
596 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
598 Services can be new, in which case they are inserted, or existing unaudited
599 services, in which case they are linked to the newly-created package.
601 Currently available options are: I<depend_jobnum> and I<noexport>.
603 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
604 on the supplied jobnum (they will not run until the specific job completes).
605 This can be used to defer provisioning until some action completes (such
606 as running the customer's credit card successfully).
608 The I<noexport> option is deprecated. If I<noexport> is set true, no
609 provisioning jobs (exports) are scheduled. (You can schedule them later with
610 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
611 on the cust_main object is not recommended, as existing services will also be
618 my $cust_pkgs = shift;
621 my %svc_options = ();
622 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
623 if exists $options{'depend_jobnum'};
624 warn "$me order_pkgs called with options ".
625 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
628 local $SIG{HUP} = 'IGNORE';
629 local $SIG{INT} = 'IGNORE';
630 local $SIG{QUIT} = 'IGNORE';
631 local $SIG{TERM} = 'IGNORE';
632 local $SIG{TSTP} = 'IGNORE';
633 local $SIG{PIPE} = 'IGNORE';
635 my $oldAutoCommit = $FS::UID::AutoCommit;
636 local $FS::UID::AutoCommit = 0;
639 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
641 foreach my $cust_pkg ( keys %$cust_pkgs ) {
642 $cust_pkg->custnum( $self->custnum );
643 my $error = $cust_pkg->insert;
645 $dbh->rollback if $oldAutoCommit;
646 return "inserting cust_pkg (transaction rolled back): $error";
648 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
649 if ( $svc_something->svcnum ) {
650 my $old_cust_svc = $svc_something->cust_svc;
651 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
652 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
653 $error = $new_cust_svc->replace($old_cust_svc);
655 $svc_something->pkgnum( $cust_pkg->pkgnum );
656 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
657 $svc_something->seconds( $svc_something->seconds + $$seconds );
660 $error = $svc_something->insert(%svc_options);
663 $dbh->rollback if $oldAutoCommit;
664 #return "inserting svc_ (transaction rolled back): $error";
670 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
674 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF ]
676 Recharges this (existing) customer with the specified prepaid card (see
677 L<FS::prepay_credit>), specified either by I<identifier> or as an
678 FS::prepay_credit object. If there is an error, returns the error, otherwise
681 Optionally, two scalar references can be passed as well. They will have their
682 values filled in with the amount and number of seconds applied by this prepaid
687 sub recharge_prepay {
688 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
690 local $SIG{HUP} = 'IGNORE';
691 local $SIG{INT} = 'IGNORE';
692 local $SIG{QUIT} = 'IGNORE';
693 local $SIG{TERM} = 'IGNORE';
694 local $SIG{TSTP} = 'IGNORE';
695 local $SIG{PIPE} = 'IGNORE';
697 my $oldAutoCommit = $FS::UID::AutoCommit;
698 local $FS::UID::AutoCommit = 0;
701 my( $amount, $seconds ) = ( 0, 0 );
703 my $error = $self->get_prepay($prepay_credit, \$amount, \$seconds)
704 || $self->increment_seconds($seconds)
705 || $self->insert_cust_pay_prepay( $amount,
707 ? $prepay_credit->identifier
712 $dbh->rollback if $oldAutoCommit;
716 if ( defined($amountref) ) { $$amountref = $amount; }
717 if ( defined($secondsref) ) { $$secondsref = $seconds; }
719 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
724 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
726 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
727 specified either by I<identifier> or as an FS::prepay_credit object.
729 References to I<amount> and I<seconds> scalars should be passed as arguments
730 and will be incremented by the values of the prepaid card.
732 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
733 check or set this customer's I<agentnum>.
735 If there is an error, returns the error, otherwise returns false.
741 my( $self, $prepay_credit, $amountref, $secondsref ) = @_;
743 local $SIG{HUP} = 'IGNORE';
744 local $SIG{INT} = 'IGNORE';
745 local $SIG{QUIT} = 'IGNORE';
746 local $SIG{TERM} = 'IGNORE';
747 local $SIG{TSTP} = 'IGNORE';
748 local $SIG{PIPE} = 'IGNORE';
750 my $oldAutoCommit = $FS::UID::AutoCommit;
751 local $FS::UID::AutoCommit = 0;
754 unless ( ref($prepay_credit) ) {
756 my $identifier = $prepay_credit;
758 $prepay_credit = qsearchs(
760 { 'identifier' => $prepay_credit },
765 unless ( $prepay_credit ) {
766 $dbh->rollback if $oldAutoCommit;
767 return "Invalid prepaid card: ". $identifier;
772 if ( $prepay_credit->agentnum ) {
773 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
774 $dbh->rollback if $oldAutoCommit;
775 return "prepaid card not valid for agent ". $self->agentnum;
777 $self->agentnum($prepay_credit->agentnum);
780 my $error = $prepay_credit->delete;
782 $dbh->rollback if $oldAutoCommit;
783 return "removing prepay_credit (transaction rolled back): $error";
786 $$amountref += $prepay_credit->amount;
787 $$secondsref += $prepay_credit->seconds;
789 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
794 =item increment_seconds SECONDS
796 Updates this customer's single or primary account (see L<FS::svc_acct>) by
797 the specified number of seconds. If there is an error, returns the error,
798 otherwise returns false.
802 sub increment_seconds {
803 my( $self, $seconds ) = @_;
804 warn "$me increment_seconds called: $seconds seconds\n"
807 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
808 $self->ncancelled_pkgs;
811 return 'No packages with primary or single services found'.
812 ' to apply pre-paid time';
813 } elsif ( scalar(@cust_pkg) > 1 ) {
814 #maybe have a way to specify the package/account?
815 return 'Multiple packages found to apply pre-paid time';
818 my $cust_pkg = $cust_pkg[0];
819 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
823 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
826 return 'No account found to apply pre-paid time';
827 } elsif ( scalar(@cust_svc) > 1 ) {
828 return 'Multiple accounts found to apply pre-paid time';
831 my $svc_acct = $cust_svc[0]->svc_x;
832 warn " found service svcnum ". $svc_acct->pkgnum.
833 ' ('. $svc_acct->email. ")\n"
836 $svc_acct->increment_seconds($seconds);
840 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
842 Inserts a prepayment in the specified amount for this customer. An optional
843 second argument can specify the prepayment identifier for tracking purposes.
844 If there is an error, returns the error, otherwise returns false.
848 sub insert_cust_pay_prepay {
849 shift->insert_cust_pay('PREP', @_);
852 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
854 Inserts a cash payment in the specified amount for this customer. An optional
855 second argument can specify the payment identifier for tracking purposes.
856 If there is an error, returns the error, otherwise returns false.
860 sub insert_cust_pay_cash {
861 shift->insert_cust_pay('CASH', @_);
864 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
866 Inserts a Western Union payment in the specified amount for this customer. An
867 optional second argument can specify the prepayment identifier for tracking
868 purposes. If there is an error, returns the error, otherwise returns false.
872 sub insert_cust_pay_west {
873 shift->insert_cust_pay('WEST', @_);
876 sub insert_cust_pay {
877 my( $self, $payby, $amount ) = splice(@_, 0, 3);
878 my $payinfo = scalar(@_) ? shift : '';
880 my $cust_pay = new FS::cust_pay {
881 'custnum' => $self->custnum,
882 'paid' => sprintf('%.2f', $amount),
883 #'_date' => #date the prepaid card was purchased???
885 'payinfo' => $payinfo,
893 This method is deprecated. See the I<depend_jobnum> option to the insert and
894 order_pkgs methods for a better way to defer provisioning.
896 Re-schedules all exports by calling the B<reexport> method of all associated
897 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
898 otherwise returns false.
905 carp "WARNING: FS::cust_main::reexport is deprectated; ".
906 "use the depend_jobnum option to insert or order_pkgs to delay export";
908 local $SIG{HUP} = 'IGNORE';
909 local $SIG{INT} = 'IGNORE';
910 local $SIG{QUIT} = 'IGNORE';
911 local $SIG{TERM} = 'IGNORE';
912 local $SIG{TSTP} = 'IGNORE';
913 local $SIG{PIPE} = 'IGNORE';
915 my $oldAutoCommit = $FS::UID::AutoCommit;
916 local $FS::UID::AutoCommit = 0;
919 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
920 my $error = $cust_pkg->reexport;
922 $dbh->rollback if $oldAutoCommit;
927 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
932 =item delete NEW_CUSTNUM
934 This deletes the customer. If there is an error, returns the error, otherwise
937 This will completely remove all traces of the customer record. This is not
938 what you want when a customer cancels service; for that, cancel all of the
939 customer's packages (see L</cancel>).
941 If the customer has any uncancelled packages, you need to pass a new (valid)
942 customer number for those packages to be transferred to. Cancelled packages
943 will be deleted. Did I mention that this is NOT what you want when a customer
944 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
946 You can't delete a customer with invoices (see L<FS::cust_bill>),
947 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
948 refunds (see L<FS::cust_refund>).
955 local $SIG{HUP} = 'IGNORE';
956 local $SIG{INT} = 'IGNORE';
957 local $SIG{QUIT} = 'IGNORE';
958 local $SIG{TERM} = 'IGNORE';
959 local $SIG{TSTP} = 'IGNORE';
960 local $SIG{PIPE} = 'IGNORE';
962 my $oldAutoCommit = $FS::UID::AutoCommit;
963 local $FS::UID::AutoCommit = 0;
966 if ( $self->cust_bill ) {
967 $dbh->rollback if $oldAutoCommit;
968 return "Can't delete a customer with invoices";
970 if ( $self->cust_credit ) {
971 $dbh->rollback if $oldAutoCommit;
972 return "Can't delete a customer with credits";
974 if ( $self->cust_pay ) {
975 $dbh->rollback if $oldAutoCommit;
976 return "Can't delete a customer with payments";
978 if ( $self->cust_refund ) {
979 $dbh->rollback if $oldAutoCommit;
980 return "Can't delete a customer with refunds";
983 my @cust_pkg = $self->ncancelled_pkgs;
985 my $new_custnum = shift;
986 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
987 $dbh->rollback if $oldAutoCommit;
988 return "Invalid new customer number: $new_custnum";
990 foreach my $cust_pkg ( @cust_pkg ) {
991 my %hash = $cust_pkg->hash;
992 $hash{'custnum'} = $new_custnum;
993 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
994 my $error = $new_cust_pkg->replace($cust_pkg);
996 $dbh->rollback if $oldAutoCommit;
1001 my @cancelled_cust_pkg = $self->all_pkgs;
1002 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1003 my $error = $cust_pkg->delete;
1005 $dbh->rollback if $oldAutoCommit;
1010 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1011 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1013 my $error = $cust_main_invoice->delete;
1015 $dbh->rollback if $oldAutoCommit;
1020 my $error = $self->SUPER::delete;
1022 $dbh->rollback if $oldAutoCommit;
1026 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1031 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1033 Replaces the OLD_RECORD with this one in the database. If there is an error,
1034 returns the error, otherwise returns false.
1036 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1037 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1038 expected and rollback the entire transaction; it is not necessary to call
1039 check_invoicing_list first. Here's an example:
1041 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1049 warn "$me replace called\n"
1052 local $SIG{HUP} = 'IGNORE';
1053 local $SIG{INT} = 'IGNORE';
1054 local $SIG{QUIT} = 'IGNORE';
1055 local $SIG{TERM} = 'IGNORE';
1056 local $SIG{TSTP} = 'IGNORE';
1057 local $SIG{PIPE} = 'IGNORE';
1059 # If the mask is blank then try to set it - if we can...
1060 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
1061 $self->paymask($self->payinfo);
1064 # We absolutely have to have an old vs. new record to make this work.
1065 if (!defined($old)) {
1066 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1069 my $curuser = $FS::CurrentUser::CurrentUser;
1070 if ( $self->payby eq 'COMP'
1071 && $self->payby ne $old->payby
1072 && ! $curuser->access_right('Complimentary customer')
1075 return "You are not permitted to create complimentary accounts.";
1078 local($ignore_expired_card) = 1
1079 if $old->payby =~ /^(CARD|DCRD)$/
1080 && $self->payby =~ /^(CARD|DCRD)$/
1081 && $old->payinfo eq $self->payinfo;
1083 my $oldAutoCommit = $FS::UID::AutoCommit;
1084 local $FS::UID::AutoCommit = 0;
1087 my $error = $self->SUPER::replace($old);
1090 $dbh->rollback if $oldAutoCommit;
1094 if ( @param ) { # INVOICING_LIST_ARYREF
1095 my $invoicing_list = shift @param;
1096 $error = $self->check_invoicing_list( $invoicing_list );
1098 $dbh->rollback if $oldAutoCommit;
1101 $self->invoicing_list( $invoicing_list );
1104 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1105 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1106 # card/check/lec info has changed, want to retry realtime_ invoice events
1107 my $error = $self->retry_realtime;
1109 $dbh->rollback if $oldAutoCommit;
1114 unless ( $import || $skip_fuzzyfiles ) {
1115 $error = $self->queue_fuzzyfiles_update;
1117 $dbh->rollback if $oldAutoCommit;
1118 return "updating fuzzy search cache: $error";
1122 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1127 =item queue_fuzzyfiles_update
1129 Used by insert & replace to update the fuzzy search cache
1133 sub queue_fuzzyfiles_update {
1136 local $SIG{HUP} = 'IGNORE';
1137 local $SIG{INT} = 'IGNORE';
1138 local $SIG{QUIT} = 'IGNORE';
1139 local $SIG{TERM} = 'IGNORE';
1140 local $SIG{TSTP} = 'IGNORE';
1141 local $SIG{PIPE} = 'IGNORE';
1143 my $oldAutoCommit = $FS::UID::AutoCommit;
1144 local $FS::UID::AutoCommit = 0;
1147 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1148 my $error = $queue->insert( map $self->getfield($_),
1149 qw(first last company)
1152 $dbh->rollback if $oldAutoCommit;
1153 return "queueing job (transaction rolled back): $error";
1156 if ( $self->ship_last ) {
1157 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1158 $error = $queue->insert( map $self->getfield("ship_$_"),
1159 qw(first last company)
1162 $dbh->rollback if $oldAutoCommit;
1163 return "queueing job (transaction rolled back): $error";
1167 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1174 Checks all fields to make sure this is a valid customer record. If there is
1175 an error, returns the error, otherwise returns false. Called by the insert
1176 and replace methods.
1183 warn "$me check BEFORE: \n". $self->_dump
1187 $self->ut_numbern('custnum')
1188 || $self->ut_number('agentnum')
1189 || $self->ut_textn('agent_custid')
1190 || $self->ut_number('refnum')
1191 || $self->ut_name('last')
1192 || $self->ut_name('first')
1193 || $self->ut_textn('company')
1194 || $self->ut_text('address1')
1195 || $self->ut_textn('address2')
1196 || $self->ut_text('city')
1197 || $self->ut_textn('county')
1198 || $self->ut_textn('state')
1199 || $self->ut_country('country')
1200 || $self->ut_anything('comments')
1201 || $self->ut_numbern('referral_custnum')
1203 #barf. need message catalogs. i18n. etc.
1204 $error .= "Please select an advertising source."
1205 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1206 return $error if $error;
1208 return "Unknown agent"
1209 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1211 return "Unknown refnum"
1212 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1214 return "Unknown referring custnum: ". $self->referral_custnum
1215 unless ! $self->referral_custnum
1216 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1218 if ( $self->ss eq '' ) {
1223 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1224 or return "Illegal social security number: ". $self->ss;
1225 $self->ss("$1-$2-$3");
1229 # bad idea to disable, causes billing to fail because of no tax rates later
1230 # unless ( $import ) {
1231 unless ( qsearch('cust_main_county', {
1232 'country' => $self->country,
1235 return "Unknown state/county/country: ".
1236 $self->state. "/". $self->county. "/". $self->country
1237 unless qsearch('cust_main_county',{
1238 'state' => $self->state,
1239 'county' => $self->county,
1240 'country' => $self->country,
1246 $self->ut_phonen('daytime', $self->country)
1247 || $self->ut_phonen('night', $self->country)
1248 || $self->ut_phonen('fax', $self->country)
1249 || $self->ut_zip('zip', $self->country)
1251 return $error if $error;
1254 last first company address1 address2 city county state zip
1255 country daytime night fax
1258 if ( defined $self->dbdef_table->column('ship_last') ) {
1259 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1261 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1265 $self->ut_name('ship_last')
1266 || $self->ut_name('ship_first')
1267 || $self->ut_textn('ship_company')
1268 || $self->ut_text('ship_address1')
1269 || $self->ut_textn('ship_address2')
1270 || $self->ut_text('ship_city')
1271 || $self->ut_textn('ship_county')
1272 || $self->ut_textn('ship_state')
1273 || $self->ut_country('ship_country')
1275 return $error if $error;
1277 #false laziness with above
1278 unless ( qsearchs('cust_main_county', {
1279 'country' => $self->ship_country,
1282 return "Unknown ship_state/ship_county/ship_country: ".
1283 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1284 unless qsearch('cust_main_county',{
1285 'state' => $self->ship_state,
1286 'county' => $self->ship_county,
1287 'country' => $self->ship_country,
1293 $self->ut_phonen('ship_daytime', $self->ship_country)
1294 || $self->ut_phonen('ship_night', $self->ship_country)
1295 || $self->ut_phonen('ship_fax', $self->ship_country)
1296 || $self->ut_zip('ship_zip', $self->ship_country)
1298 return $error if $error;
1300 } else { # ship_ info eq billing info, so don't store dup info in database
1301 $self->setfield("ship_$_", '')
1302 foreach qw( last first company address1 address2 city county state zip
1303 country daytime night fax );
1307 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1308 or return "Illegal payby: ". $self->payby;
1310 $error = $self->ut_numbern('paystart_month')
1311 || $self->ut_numbern('paystart_year')
1312 || $self->ut_numbern('payissue')
1314 return $error if $error;
1316 if ( $self->payip eq '' ) {
1319 $error = $self->ut_ip('payip');
1320 return $error if $error;
1323 # If it is encrypted and the private key is not availaible then we can't
1324 # check the credit card.
1326 my $check_payinfo = 1;
1328 if ($self->is_encrypted($self->payinfo)) {
1334 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1336 my $payinfo = $self->payinfo;
1337 $payinfo =~ s/\D//g;
1338 $payinfo =~ /^(\d{13,16})$/
1339 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1341 $self->payinfo($payinfo);
1343 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1345 return gettext('unknown_card_type')
1346 if cardtype($self->payinfo) eq "Unknown";
1348 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1350 return 'Banned credit card: banned on '.
1351 time2str('%a %h %o at %r', $ban->_date).
1352 ' by '. $ban->otaker.
1353 ' (ban# '. $ban->bannum. ')';
1356 if ( defined $self->dbdef_table->column('paycvv') ) {
1357 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1358 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1359 $self->paycvv =~ /^(\d{4})$/
1360 or return "CVV2 (CID) for American Express cards is four digits.";
1363 $self->paycvv =~ /^(\d{3})$/
1364 or return "CVV2 (CVC2/CID) is three digits.";
1372 my $cardtype = cardtype($payinfo);
1373 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1375 return "Start date or issue number is required for $cardtype cards"
1376 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1378 return "Start month must be between 1 and 12"
1379 if $self->paystart_month
1380 and $self->paystart_month < 1 || $self->paystart_month > 12;
1382 return "Start year must be 1990 or later"
1383 if $self->paystart_year
1384 and $self->paystart_year < 1990;
1386 return "Issue number must be beween 1 and 99"
1388 and $self->payissue < 1 || $self->payissue > 99;
1391 $self->paystart_month('');
1392 $self->paystart_year('');
1393 $self->payissue('');
1396 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1398 my $payinfo = $self->payinfo;
1399 $payinfo =~ s/[^\d\@]//g;
1400 if ( $conf->exists('echeck-nonus') ) {
1401 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1402 $payinfo = "$1\@$2";
1404 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1405 $payinfo = "$1\@$2";
1407 $self->payinfo($payinfo);
1408 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1410 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1412 return 'Banned ACH account: banned on '.
1413 time2str('%a %h %o at %r', $ban->_date).
1414 ' by '. $ban->otaker.
1415 ' (ban# '. $ban->bannum. ')';
1418 } elsif ( $self->payby eq 'LECB' ) {
1420 my $payinfo = $self->payinfo;
1421 $payinfo =~ s/\D//g;
1422 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1424 $self->payinfo($payinfo);
1425 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1427 } elsif ( $self->payby eq 'BILL' ) {
1429 $error = $self->ut_textn('payinfo');
1430 return "Illegal P.O. number: ". $self->payinfo if $error;
1431 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1433 } elsif ( $self->payby eq 'COMP' ) {
1435 my $curuser = $FS::CurrentUser::CurrentUser;
1436 if ( ! $self->custnum
1437 && ! $curuser->access_right('Complimentary customer')
1440 return "You are not permitted to create complimentary accounts."
1443 $error = $self->ut_textn('payinfo');
1444 return "Illegal comp account issuer: ". $self->payinfo if $error;
1445 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1447 } elsif ( $self->payby eq 'PREPAY' ) {
1449 my $payinfo = $self->payinfo;
1450 $payinfo =~ s/\W//g; #anything else would just confuse things
1451 $self->payinfo($payinfo);
1452 $error = $self->ut_alpha('payinfo');
1453 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1454 return "Unknown prepayment identifier"
1455 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1456 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1460 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1461 return "Expiration date required"
1462 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1466 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1467 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1468 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1469 ( $m, $y ) = ( $3, "20$2" );
1471 return "Illegal expiration date: ". $self->paydate;
1473 $self->paydate("$y-$m-01");
1474 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1475 return gettext('expired_card')
1477 && !$ignore_expired_card
1478 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1481 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1482 ( ! $conf->exists('require_cardname')
1483 || $self->payby !~ /^(CARD|DCRD)$/ )
1485 $self->payname( $self->first. " ". $self->getfield('last') );
1487 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1488 or return gettext('illegal_name'). " payname: ". $self->payname;
1492 foreach my $flag (qw( tax spool_cdr )) {
1493 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1497 $self->otaker(getotaker) unless $self->otaker;
1499 warn "$me check AFTER: \n". $self->_dump
1502 $self->SUPER::check;
1507 Returns all packages (see L<FS::cust_pkg>) for this customer.
1513 if ( $self->{'_pkgnum'} ) {
1514 values %{ $self->{'_pkgnum'}->cache };
1516 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1520 =item ncancelled_pkgs
1522 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1526 sub ncancelled_pkgs {
1528 if ( $self->{'_pkgnum'} ) {
1529 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1531 @{ [ # force list context
1532 qsearch( 'cust_pkg', {
1533 'custnum' => $self->custnum,
1536 qsearch( 'cust_pkg', {
1537 'custnum' => $self->custnum,
1544 =item suspended_pkgs
1546 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1550 sub suspended_pkgs {
1552 grep { $_->susp } $self->ncancelled_pkgs;
1555 =item unflagged_suspended_pkgs
1557 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1558 customer (thouse packages without the `manual_flag' set).
1562 sub unflagged_suspended_pkgs {
1564 return $self->suspended_pkgs
1565 unless dbdef->table('cust_pkg')->column('manual_flag');
1566 grep { ! $_->manual_flag } $self->suspended_pkgs;
1569 =item unsuspended_pkgs
1571 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1576 sub unsuspended_pkgs {
1578 grep { ! $_->susp } $self->ncancelled_pkgs;
1581 =item num_cancelled_pkgs
1583 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1588 sub num_cancelled_pkgs {
1590 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1594 my( $self, $sql ) = @_;
1595 my $sth = dbh->prepare(
1596 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1597 ) or die dbh->errstr;
1598 $sth->execute($self->custnum) or die $sth->errstr;
1599 $sth->fetchrow_arrayref->[0];
1604 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1605 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1606 on success or a list of errors.
1612 grep { $_->unsuspend } $self->suspended_pkgs;
1617 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1619 Returns a list: an empty list on success or a list of errors.
1625 grep { $_->suspend } $self->unsuspended_pkgs;
1628 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1630 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1631 PKGPARTs (see L<FS::part_pkg>).
1633 Returns a list: an empty list on success or a list of errors.
1637 sub suspend_if_pkgpart {
1640 grep { $_->suspend }
1641 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1642 $self->unsuspended_pkgs;
1645 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1647 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1648 listed PKGPARTs (see L<FS::part_pkg>).
1650 Returns a list: an empty list on success or a list of errors.
1654 sub suspend_unless_pkgpart {
1657 grep { $_->suspend }
1658 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1659 $self->unsuspended_pkgs;
1662 =item cancel [ OPTION => VALUE ... ]
1664 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1666 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1668 I<quiet> can be set true to supress email cancellation notices.
1670 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1672 I<ban> can be set true to ban this customer's credit card or ACH information,
1675 Always returns a list: an empty list on success or a list of errors.
1683 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1685 #should try decryption (we might have the private key)
1686 # and if not maybe queue a job for the server that does?
1687 return ( "Can't (yet) ban encrypted credit cards" )
1688 if $self->is_encrypted($self->payinfo);
1690 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1691 my $error = $ban->insert;
1692 return ( $error ) if $error;
1696 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1699 sub _banned_pay_hashref {
1710 'payby' => $payby2ban{$self->payby},
1711 'payinfo' => md5_base64($self->payinfo),
1718 Returns the agent (see L<FS::agent>) for this customer.
1724 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1729 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1730 conjunction with the collect method.
1732 Options are passed as name-value pairs.
1734 Currently available options are:
1736 resetup - if set true, re-charges setup fees.
1738 time - bills the customer as if it were that time. Specified as a UNIX
1739 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1740 L<Date::Parse> for conversion functions. For example:
1744 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1747 If there is an error, returns the error, otherwise returns false.
1752 my( $self, %options ) = @_;
1753 return '' if $self->payby eq 'COMP';
1754 warn "$me bill customer ". $self->custnum. "\n"
1757 my $time = $options{'time'} || time;
1762 local $SIG{HUP} = 'IGNORE';
1763 local $SIG{INT} = 'IGNORE';
1764 local $SIG{QUIT} = 'IGNORE';
1765 local $SIG{TERM} = 'IGNORE';
1766 local $SIG{TSTP} = 'IGNORE';
1767 local $SIG{PIPE} = 'IGNORE';
1769 my $oldAutoCommit = $FS::UID::AutoCommit;
1770 local $FS::UID::AutoCommit = 0;
1773 $self->select_for_update; #mutex
1775 #create a new invoice
1776 #(we'll remove it later if it doesn't actually need to be generated [contains
1777 # no line items] and we're inside a transaciton so nothing else will see it)
1778 my $cust_bill = new FS::cust_bill ( {
1779 'custnum' => $self->custnum,
1781 #'charged' => $charged,
1784 $error = $cust_bill->insert;
1786 $dbh->rollback if $oldAutoCommit;
1787 return "can't create invoice for customer #". $self->custnum. ": $error";
1789 my $invnum = $cust_bill->invnum;
1792 # find the packages which are due for billing, find out how much they are
1793 # & generate invoice database.
1796 my( $total_setup, $total_recur ) = ( 0, 0 );
1798 my @precommit_hooks = ();
1800 foreach my $cust_pkg (
1801 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1804 #NO!! next if $cust_pkg->cancel;
1805 next if $cust_pkg->getfield('cancel');
1807 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1809 #? to avoid use of uninitialized value errors... ?
1810 $cust_pkg->setfield('bill', '')
1811 unless defined($cust_pkg->bill);
1813 my $part_pkg = $cust_pkg->part_pkg;
1815 my %hash = $cust_pkg->hash;
1816 my $old_cust_pkg = new FS::cust_pkg \%hash;
1825 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1827 warn " bill setup\n" if $DEBUG > 1;
1829 $setup = eval { $cust_pkg->calc_setup( $time ) };
1831 $dbh->rollback if $oldAutoCommit;
1832 return "$@ running calc_setup for $cust_pkg\n";
1835 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1839 # bill recurring fee
1844 if ( $part_pkg->getfield('freq') ne '0' &&
1845 ! $cust_pkg->getfield('susp') &&
1846 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1849 warn " bill recur\n" if $DEBUG > 1;
1851 # XXX shared with $recur_prog
1852 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1854 #over two params! lets at least switch to a hashref for the rest...
1855 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
1857 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
1859 $dbh->rollback if $oldAutoCommit;
1860 return "$@ running calc_recur for $cust_pkg\n";
1863 #change this bit to use Date::Manip? CAREFUL with timezones (see
1864 # mailing list archive)
1865 my ($sec,$min,$hour,$mday,$mon,$year) =
1866 (localtime($sdate) )[0,1,2,3,4,5];
1868 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1869 # only for figuring next bill date, nothing else, so, reset $sdate again
1871 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1872 $cust_pkg->last_bill($sdate)
1873 if $cust_pkg->dbdef_table->column('last_bill');
1875 if ( $part_pkg->freq =~ /^\d+$/ ) {
1876 $mon += $part_pkg->freq;
1877 until ( $mon < 12 ) { $mon -= 12; $year++; }
1878 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1880 $mday += $weeks * 7;
1881 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1884 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
1888 $dbh->rollback if $oldAutoCommit;
1889 return "unparsable frequency: ". $part_pkg->freq;
1891 $cust_pkg->setfield('bill',
1892 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1895 warn "\$setup is undefined" unless defined($setup);
1896 warn "\$recur is undefined" unless defined($recur);
1897 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1900 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
1903 if ( $cust_pkg->modified ) {
1905 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
1908 $error=$cust_pkg->replace($old_cust_pkg);
1909 if ( $error ) { #just in case
1910 $dbh->rollback if $oldAutoCommit;
1911 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1914 $setup = sprintf( "%.2f", $setup );
1915 $recur = sprintf( "%.2f", $recur );
1916 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1917 $dbh->rollback if $oldAutoCommit;
1918 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1920 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1921 $dbh->rollback if $oldAutoCommit;
1922 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1925 if ( $setup != 0 || $recur != 0 ) {
1927 warn " charges (setup=$setup, recur=$recur); adding line items\n"
1929 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1930 'invnum' => $invnum,
1931 'pkgnum' => $cust_pkg->pkgnum,
1935 'edate' => $cust_pkg->bill,
1936 'details' => \@details,
1938 $error = $cust_bill_pkg->insert;
1940 $dbh->rollback if $oldAutoCommit;
1941 return "can't create invoice line item for invoice #$invnum: $error";
1943 $total_setup += $setup;
1944 $total_recur += $recur;
1950 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1953 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
1956 my %taxhash = map { $_ => $self->get("$prefix$_") }
1957 qw( state county country );
1959 $taxhash{'taxclass'} = $part_pkg->taxclass;
1961 my @taxes = qsearch( 'cust_main_county', \%taxhash );
1964 $taxhash{'taxclass'} = '';
1965 @taxes = qsearch( 'cust_main_county', \%taxhash );
1968 #one more try at a whole-country tax rate
1970 $taxhash{$_} = '' foreach qw( state county );
1971 @taxes = qsearch( 'cust_main_county', \%taxhash );
1974 # maybe eliminate this entirely, along with all the 0% records
1976 $dbh->rollback if $oldAutoCommit;
1978 "fatal: can't find tax rate for state/county/country/taxclass ".
1979 join('/', ( map $self->get("$prefix$_"),
1980 qw(state county country)
1982 $part_pkg->taxclass ). "\n";
1985 foreach my $tax ( @taxes ) {
1987 my $taxable_charged = 0;
1988 $taxable_charged += $setup
1989 unless $part_pkg->setuptax =~ /^Y$/i
1990 || $tax->setuptax =~ /^Y$/i;
1991 $taxable_charged += $recur
1992 unless $part_pkg->recurtax =~ /^Y$/i
1993 || $tax->recurtax =~ /^Y$/i;
1994 next unless $taxable_charged;
1996 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
1997 #my ($mon,$year) = (localtime($sdate) )[4,5];
1998 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2000 my $freq = $part_pkg->freq || 1;
2001 if ( $freq !~ /(\d+)$/ ) {
2002 $dbh->rollback if $oldAutoCommit;
2003 return "daily/weekly package definitions not (yet?)".
2004 " compatible with monthly tax exemptions";
2006 my $taxable_per_month =
2007 sprintf("%.2f", $taxable_charged / $freq );
2009 #call the whole thing off if this customer has any old
2010 #exemption records...
2011 my @cust_tax_exempt =
2012 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2013 if ( @cust_tax_exempt ) {
2014 $dbh->rollback if $oldAutoCommit;
2016 'this customer still has old-style tax exemption records; '.
2017 'run bin/fs-migrate-cust_tax_exempt?';
2020 foreach my $which_month ( 1 .. $freq ) {
2022 #maintain the new exemption table now
2025 FROM cust_tax_exempt_pkg
2026 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2027 LEFT JOIN cust_bill USING ( invnum )
2033 my $sth = dbh->prepare($sql) or do {
2034 $dbh->rollback if $oldAutoCommit;
2035 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2043 $dbh->rollback if $oldAutoCommit;
2044 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2046 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2048 my $remaining_exemption =
2049 $tax->exempt_amount - $existing_exemption;
2050 if ( $remaining_exemption > 0 ) {
2051 my $addl = $remaining_exemption > $taxable_per_month
2052 ? $taxable_per_month
2053 : $remaining_exemption;
2054 $taxable_charged -= $addl;
2056 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2057 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2058 'taxnum' => $tax->taxnum,
2059 'year' => 1900+$year,
2061 'amount' => sprintf("%.2f", $addl ),
2063 $error = $cust_tax_exempt_pkg->insert;
2065 $dbh->rollback if $oldAutoCommit;
2066 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2068 } # if $remaining_exemption > 0
2072 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2073 until ( $mon < 13 ) { $mon -= 12; $year++; }
2075 } #foreach $which_month
2077 } #if $tax->exempt_amount
2079 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2081 #$tax += $taxable_charged * $cust_main_county->tax / 100
2082 $tax{ $tax->taxname || 'Tax' } +=
2083 $taxable_charged * $tax->tax / 100
2085 } #foreach my $tax ( @taxes )
2087 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2089 } #if $setup != 0 || $recur != 0
2091 } #if $cust_pkg->modified
2093 } #foreach my $cust_pkg
2095 unless ( $cust_bill->cust_bill_pkg ) {
2096 $cust_bill->delete; #don't create an invoice w/o line items
2097 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2101 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2103 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2104 my $tax = sprintf("%.2f", $tax{$taxname} );
2105 $charged = sprintf( "%.2f", $charged+$tax );
2107 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2108 'invnum' => $invnum,
2114 'itemdesc' => $taxname,
2116 $error = $cust_bill_pkg->insert;
2118 $dbh->rollback if $oldAutoCommit;
2119 return "can't create invoice line item for invoice #$invnum: $error";
2121 $total_setup += $tax;
2125 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2126 $error = $cust_bill->replace;
2128 $dbh->rollback if $oldAutoCommit;
2129 return "can't update charged for invoice #$invnum: $error";
2132 foreach my $hook ( @precommit_hooks ) {
2134 &{$hook}; #($self) ?
2137 $dbh->rollback if $oldAutoCommit;
2138 return "$@ running precommit hook $hook\n";
2142 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2146 =item collect OPTIONS
2148 (Attempt to) collect money for this customer's outstanding invoices (see
2149 L<FS::cust_bill>). Usually used after the bill method.
2151 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2152 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2153 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2155 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2156 and the invoice events web interface.
2158 If there is an error, returns the error, otherwise returns false.
2160 Options are passed as name-value pairs.
2162 Currently available options are:
2164 invoice_time - Use this time when deciding when to print invoices and
2165 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>
2166 for conversion functions.
2168 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2171 quiet - set true to surpress email card/ACH decline notices.
2173 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2176 payby - allows for one time override of normal customer billing method
2181 my( $self, %options ) = @_;
2182 my $invoice_time = $options{'invoice_time'} || time;
2185 local $SIG{HUP} = 'IGNORE';
2186 local $SIG{INT} = 'IGNORE';
2187 local $SIG{QUIT} = 'IGNORE';
2188 local $SIG{TERM} = 'IGNORE';
2189 local $SIG{TSTP} = 'IGNORE';
2190 local $SIG{PIPE} = 'IGNORE';
2192 my $oldAutoCommit = $FS::UID::AutoCommit;
2193 local $FS::UID::AutoCommit = 0;
2196 $self->select_for_update; #mutex
2198 my $balance = $self->balance;
2199 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2201 unless ( $balance > 0 ) { #redundant?????
2202 $dbh->rollback if $oldAutoCommit; #hmm
2206 if ( exists($options{'retry_card'}) ) {
2207 carp 'retry_card option passed to collect is deprecated; use retry';
2208 $options{'retry'} ||= $options{'retry_card'};
2210 if ( exists($options{'retry'}) && $options{'retry'} ) {
2211 my $error = $self->retry_realtime;
2213 $dbh->rollback if $oldAutoCommit;
2219 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2220 $extra_sql = " AND freq = '1m' ";
2222 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2225 foreach my $cust_bill ( $self->open_cust_bill ) {
2227 # don't try to charge for the same invoice if it's already in a batch
2228 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2230 last if $self->balance <= 0;
2232 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2235 foreach my $part_bill_event (
2236 sort { $a->seconds <=> $b->seconds
2237 || $a->weight <=> $b->weight
2238 || $a->eventpart <=> $b->eventpart }
2239 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
2240 && ! qsearch( 'cust_bill_event', {
2241 'invnum' => $cust_bill->invnum,
2242 'eventpart' => $_->eventpart,
2247 'table' => 'part_bill_event',
2248 'hashref' => { 'payby' => (exists($options{'payby'})
2252 'disabled' => '', },
2253 'extra_sql' => $extra_sql,
2257 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2258 || $self->balance <= 0; # or if balance<=0
2260 warn " calling invoice event (". $part_bill_event->eventcode. ")\n"
2262 my $cust_main = $self; #for callback
2266 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2267 local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
2268 $error = eval $part_bill_event->eventcode;
2272 my $statustext = '';
2276 } elsif ( $error ) {
2278 $statustext = $error;
2283 #add cust_bill_event
2284 my $cust_bill_event = new FS::cust_bill_event {
2285 'invnum' => $cust_bill->invnum,
2286 'eventpart' => $part_bill_event->eventpart,
2287 #'_date' => $invoice_time,
2289 'status' => $status,
2290 'statustext' => $statustext,
2292 $error = $cust_bill_event->insert;
2294 #$dbh->rollback if $oldAutoCommit;
2295 #return "error: $error";
2297 # gah, even with transactions.
2298 $dbh->commit if $oldAutoCommit; #well.
2299 my $e = 'WARNING: Event run but database not updated - '.
2300 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
2301 ', eventpart '. $part_bill_event->eventpart.
2312 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2317 =item retry_realtime
2319 Schedules realtime credit card / electronic check / LEC billing events for
2320 for retry. Useful if card information has changed or manual retry is desired.
2321 The 'collect' method must be called to actually retry the transaction.
2323 Implementation details: For each of this customer's open invoices, changes
2324 the status of the first "done" (with statustext error) realtime processing
2329 sub retry_realtime {
2332 local $SIG{HUP} = 'IGNORE';
2333 local $SIG{INT} = 'IGNORE';
2334 local $SIG{QUIT} = 'IGNORE';
2335 local $SIG{TERM} = 'IGNORE';
2336 local $SIG{TSTP} = 'IGNORE';
2337 local $SIG{PIPE} = 'IGNORE';
2339 my $oldAutoCommit = $FS::UID::AutoCommit;
2340 local $FS::UID::AutoCommit = 0;
2343 foreach my $cust_bill (
2344 grep { $_->cust_bill_event }
2345 $self->open_cust_bill
2347 my @cust_bill_event =
2348 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2350 #$_->part_bill_event->plan eq 'realtime-card'
2351 $_->part_bill_event->eventcode =~
2352 /\$cust_bill\->realtime_(card|ach|lec)/
2353 && $_->status eq 'done'
2356 $cust_bill->cust_bill_event;
2357 next unless @cust_bill_event;
2358 my $error = $cust_bill_event[0]->retry;
2360 $dbh->rollback if $oldAutoCommit;
2361 return "error scheduling invoice event for retry: $error";
2366 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2371 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2373 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2374 via a Business::OnlinePayment realtime gateway. See
2375 L<http://420.am/business-onlinepayment> for supported gateways.
2377 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2379 Available options are: I<description>, I<invnum>, I<quiet>
2381 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2382 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2383 if set, will override the value from the customer record.
2385 I<description> is a free-text field passed to the gateway. It defaults to
2386 "Internet services".
2388 If an I<invnum> is specified, this payment (if successful) is applied to the
2389 specified invoice. If you don't specify an I<invnum> you might want to
2390 call the B<apply_payments> method.
2392 I<quiet> can be set true to surpress email decline notices.
2394 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2399 my( $self, $method, $amount, %options ) = @_;
2401 warn "$me realtime_bop: $method $amount\n";
2402 warn " $_ => $options{$_}\n" foreach keys %options;
2405 $options{'description'} ||= 'Internet services';
2407 eval "use Business::OnlinePayment";
2410 my $payinfo = exists($options{'payinfo'})
2411 ? $options{'payinfo'}
2419 if ( $options{'invnum'} ) {
2420 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2421 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2423 map { $_->part_pkg->taxclass }
2425 map { $_->cust_pkg }
2426 $cust_bill->cust_bill_pkg;
2427 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2428 #different taxclasses
2429 $taxclass = $taxclasses[0];
2433 #look for an agent gateway override first
2435 if ( $method eq 'CC' ) {
2436 $cardtype = cardtype($payinfo);
2437 } elsif ( $method eq 'ECHECK' ) {
2440 $cardtype = $method;
2444 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2445 cardtype => $cardtype,
2446 taxclass => $taxclass, } )
2447 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2449 taxclass => $taxclass, } )
2450 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2451 cardtype => $cardtype,
2453 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2455 taxclass => '', } );
2457 my $payment_gateway = '';
2458 my( $processor, $login, $password, $action, @bop_options );
2459 if ( $override ) { #use a payment gateway override
2461 $payment_gateway = $override->payment_gateway;
2463 $processor = $payment_gateway->gateway_module;
2464 $login = $payment_gateway->gateway_username;
2465 $password = $payment_gateway->gateway_password;
2466 $action = $payment_gateway->gateway_action;
2467 @bop_options = $payment_gateway->options;
2469 } else { #use the standard settings from the config
2471 ( $processor, $login, $password, $action, @bop_options ) =
2472 $self->default_payment_gateway($method);
2480 my $address = exists($options{'address1'})
2481 ? $options{'address1'}
2483 my $address2 = exists($options{'address2'})
2484 ? $options{'address2'}
2486 $address .= ", ". $address2 if length($address2);
2488 my $o_payname = exists($options{'payname'})
2489 ? $options{'payname'}
2491 my($payname, $payfirst, $paylast);
2492 if ( $o_payname && $method ne 'ECHECK' ) {
2493 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2494 or return "Illegal payname $payname";
2495 ($payfirst, $paylast) = ($1, $2);
2497 $payfirst = $self->getfield('first');
2498 $paylast = $self->getfield('last');
2499 $payname = "$payfirst $paylast";
2502 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2503 if ( $conf->exists('emailinvoiceauto')
2504 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2505 push @invoicing_list, $self->all_emails;
2508 my $email = ($conf->exists('business-onlinepayment-email-override'))
2509 ? $conf->config('business-onlinepayment-email-override')
2510 : $invoicing_list[0];
2514 my $payip = exists($options{'payip'})
2517 $content{customer_ip} = $payip
2520 if ( $method eq 'CC' ) {
2522 $content{card_number} = $payinfo;
2523 my $paydate = exists($options{'paydate'})
2524 ? $options{'paydate'}
2526 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2527 $content{expiration} = "$2/$1";
2529 my $paycvv = exists($options{'paycvv'})
2530 ? $options{'paycvv'}
2532 $content{cvv2} = $self->paycvv
2535 my $paystart_month = exists($options{'paystart_month'})
2536 ? $options{'paystart_month'}
2537 : $self->paystart_month;
2539 my $paystart_year = exists($options{'paystart_year'})
2540 ? $options{'paystart_year'}
2541 : $self->paystart_year;
2543 $content{card_start} = "$paystart_month/$paystart_year"
2544 if $paystart_month && $paystart_year;
2546 my $payissue = exists($options{'payissue'})
2547 ? $options{'payissue'}
2549 $content{issue_number} = $payissue if $payissue;
2551 $content{recurring_billing} = 'YES'
2552 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2554 'payinfo' => $payinfo,
2557 } elsif ( $method eq 'ECHECK' ) {
2558 ( $content{account_number}, $content{routing_code} ) =
2559 split('@', $payinfo);
2560 $content{bank_name} = $o_payname;
2561 $content{account_type} = 'CHECKING';
2562 $content{account_name} = $payname;
2563 $content{customer_org} = $self->company ? 'B' : 'I';
2564 $content{customer_ssn} = exists($options{'ss'})
2567 } elsif ( $method eq 'LEC' ) {
2568 $content{phone} = $payinfo;
2572 # run transaction(s)
2575 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2577 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2578 $transaction->content(
2581 'password' => $password,
2582 'action' => $action1,
2583 'description' => $options{'description'},
2584 'amount' => $amount,
2585 'invoice_number' => $options{'invnum'},
2586 'customer_id' => $self->custnum,
2587 'last_name' => $paylast,
2588 'first_name' => $payfirst,
2590 'address' => $address,
2591 'city' => ( exists($options{'city'})
2594 'state' => ( exists($options{'state'})
2597 'zip' => ( exists($options{'zip'})
2600 'country' => ( exists($options{'country'})
2601 ? $options{'country'}
2603 'referer' => 'http://cleanwhisker.420.am/',
2605 'phone' => $self->daytime || $self->night,
2608 $transaction->submit();
2610 if ( $transaction->is_success() && $action2 ) {
2611 my $auth = $transaction->authorization;
2612 my $ordernum = $transaction->can('order_number')
2613 ? $transaction->order_number
2617 new Business::OnlinePayment( $processor, @bop_options );
2624 password => $password,
2625 order_number => $ordernum,
2627 authorization => $auth,
2628 description => $options{'description'},
2631 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2632 transaction_sequence_num local_transaction_date
2633 local_transaction_time AVS_result_code )) {
2634 $capture{$field} = $transaction->$field() if $transaction->can($field);
2637 $capture->content( %capture );
2641 unless ( $capture->is_success ) {
2642 my $e = "Authorization successful but capture failed, custnum #".
2643 $self->custnum. ': '. $capture->result_code.
2644 ": ". $capture->error_message;
2652 # remove paycvv after initial transaction
2655 #false laziness w/misc/process/payment.cgi - check both to make sure working
2657 if ( defined $self->dbdef_table->column('paycvv')
2658 && length($self->paycvv)
2659 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2661 my $error = $self->remove_cvv;
2663 warn "WARNING: error removing cvv: $error\n";
2671 if ( $transaction->is_success() ) {
2673 my %method2payby = (
2680 if ( $payment_gateway ) { # agent override
2681 $paybatch = $payment_gateway->gatewaynum. '-';
2684 $paybatch .= "$processor:". $transaction->authorization;
2686 $paybatch .= ':'. $transaction->order_number
2687 if $transaction->can('order_number')
2688 && length($transaction->order_number);
2690 my $cust_pay = new FS::cust_pay ( {
2691 'custnum' => $self->custnum,
2692 'invnum' => $options{'invnum'},
2695 'payby' => $method2payby{$method},
2696 'payinfo' => $payinfo,
2697 'paybatch' => $paybatch,
2699 my $error = $cust_pay->insert;
2701 $cust_pay->invnum(''); #try again with no specific invnum
2702 my $error2 = $cust_pay->insert;
2704 # gah, even with transactions.
2705 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2706 "error inserting payment ($processor): $error2".
2707 " (previously tried insert with invnum #$options{'invnum'}" .
2713 return ''; #no error
2717 my $perror = "$processor error: ". $transaction->error_message;
2719 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2720 && $conf->exists('emaildecline')
2721 && grep { $_ ne 'POST' } $self->invoicing_list
2722 && ! grep { $transaction->error_message =~ /$_/ }
2723 $conf->config('emaildecline-exclude')
2725 my @templ = $conf->config('declinetemplate');
2726 my $template = new Text::Template (
2728 SOURCE => [ map "$_\n", @templ ],
2729 ) or return "($perror) can't create template: $Text::Template::ERROR";
2730 $template->compile()
2731 or return "($perror) can't compile template: $Text::Template::ERROR";
2733 my $templ_hash = { error => $transaction->error_message };
2735 my $error = send_email(
2736 'from' => $conf->config('invoice_from'),
2737 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2738 'subject' => 'Your payment could not be processed',
2739 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2742 $perror .= " (also received error sending decline notification: $error)"
2752 =item default_payment_gateway
2756 sub default_payment_gateway {
2757 my( $self, $method ) = @_;
2759 die "Real-time processing not enabled\n"
2760 unless $conf->exists('business-onlinepayment');
2763 my $bop_config = 'business-onlinepayment';
2764 $bop_config .= '-ach'
2765 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2766 my ( $processor, $login, $password, $action, @bop_options ) =
2767 $conf->config($bop_config);
2768 $action ||= 'normal authorization';
2769 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2770 die "No real-time processor is enabled - ".
2771 "did you set the business-onlinepayment configuration value?\n"
2774 ( $processor, $login, $password, $action, @bop_options )
2779 Removes the I<paycvv> field from the database directly.
2781 If there is an error, returns the error, otherwise returns false.
2787 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2788 or return dbh->errstr;
2789 $sth->execute($self->custnum)
2790 or return $sth->errstr;
2795 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2797 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2798 via a Business::OnlinePayment realtime gateway. See
2799 L<http://420.am/business-onlinepayment> for supported gateways.
2801 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2803 Available options are: I<amount>, I<reason>, I<paynum>
2805 Most gateways require a reference to an original payment transaction to refund,
2806 so you probably need to specify a I<paynum>.
2808 I<amount> defaults to the original amount of the payment if not specified.
2810 I<reason> specifies a reason for the refund.
2812 Implementation note: If I<amount> is unspecified or equal to the amount of the
2813 orignal payment, first an attempt is made to "void" the transaction via
2814 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2815 the normal attempt is made to "refund" ("credit") the transaction via the
2816 gateway is attempted.
2818 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2819 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2820 #if set, will override the value from the customer record.
2822 #If an I<invnum> is specified, this payment (if successful) is applied to the
2823 #specified invoice. If you don't specify an I<invnum> you might want to
2824 #call the B<apply_payments> method.
2828 #some false laziness w/realtime_bop, not enough to make it worth merging
2829 #but some useful small subs should be pulled out
2830 sub realtime_refund_bop {
2831 my( $self, $method, %options ) = @_;
2833 warn "$me realtime_refund_bop: $method refund\n";
2834 warn " $_ => $options{$_}\n" foreach keys %options;
2837 eval "use Business::OnlinePayment";
2841 # look up the original payment and optionally a gateway for that payment
2845 my $amount = $options{'amount'};
2847 my( $processor, $login, $password, @bop_options ) ;
2848 my( $auth, $order_number ) = ( '', '', '' );
2850 if ( $options{'paynum'} ) {
2852 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
2853 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2854 or return "Unknown paynum $options{'paynum'}";
2855 $amount ||= $cust_pay->paid;
2857 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2858 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2859 $cust_pay->paybatch;
2860 my $gatewaynum = '';
2861 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2863 if ( $gatewaynum ) { #gateway for the payment to be refunded
2865 my $payment_gateway =
2866 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2867 die "payment gateway $gatewaynum not found"
2868 unless $payment_gateway;
2870 $processor = $payment_gateway->gateway_module;
2871 $login = $payment_gateway->gateway_username;
2872 $password = $payment_gateway->gateway_password;
2873 @bop_options = $payment_gateway->options;
2875 } else { #try the default gateway
2877 my( $conf_processor, $unused_action );
2878 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2879 $self->default_payment_gateway($method);
2881 return "processor of payment $options{'paynum'} $processor does not".
2882 " match default processor $conf_processor"
2883 unless $processor eq $conf_processor;
2888 } else { # didn't specify a paynum, so look for agent gateway overrides
2889 # like a normal transaction
2892 if ( $method eq 'CC' ) {
2893 $cardtype = cardtype($self->payinfo);
2894 } elsif ( $method eq 'ECHECK' ) {
2897 $cardtype = $method;
2900 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2901 cardtype => $cardtype,
2903 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2905 taxclass => '', } );
2907 if ( $override ) { #use a payment gateway override
2909 my $payment_gateway = $override->payment_gateway;
2911 $processor = $payment_gateway->gateway_module;
2912 $login = $payment_gateway->gateway_username;
2913 $password = $payment_gateway->gateway_password;
2914 #$action = $payment_gateway->gateway_action;
2915 @bop_options = $payment_gateway->options;
2917 } else { #use the standard settings from the config
2920 ( $processor, $login, $password, $unused_action, @bop_options ) =
2921 $self->default_payment_gateway($method);
2926 return "neither amount nor paynum specified" unless $amount;
2931 'password' => $password,
2932 'order_number' => $order_number,
2933 'amount' => $amount,
2934 'referer' => 'http://cleanwhisker.420.am/',
2936 $content{authorization} = $auth
2937 if length($auth); #echeck/ACH transactions have an order # but no auth
2938 #(at least with authorize.net)
2940 #first try void if applicable
2941 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2942 warn " attempting void\n" if $DEBUG > 1;
2943 my $void = new Business::OnlinePayment( $processor, @bop_options );
2944 $void->content( 'action' => 'void', %content );
2946 if ( $void->is_success ) {
2947 my $error = $cust_pay->void($options{'reason'});
2949 # gah, even with transactions.
2950 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2951 "error voiding payment: $error";
2955 warn " void successful\n" if $DEBUG > 1;
2960 warn " void unsuccessful, trying refund\n"
2964 my $address = $self->address1;
2965 $address .= ", ". $self->address2 if $self->address2;
2967 my($payname, $payfirst, $paylast);
2968 if ( $self->payname && $method ne 'ECHECK' ) {
2969 $payname = $self->payname;
2970 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2971 or return "Illegal payname $payname";
2972 ($payfirst, $paylast) = ($1, $2);
2974 $payfirst = $self->getfield('first');
2975 $paylast = $self->getfield('last');
2976 $payname = "$payfirst $paylast";
2979 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2980 if ( $conf->exists('emailinvoiceauto')
2981 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2982 push @invoicing_list, $self->all_emails;
2985 my $email = ($conf->exists('business-onlinepayment-email-override'))
2986 ? $conf->config('business-onlinepayment-email-override')
2987 : $invoicing_list[0];
2989 my $payip = exists($options{'payip'})
2992 $content{customer_ip} = $payip
2996 if ( $method eq 'CC' ) {
2999 $content{card_number} = $payinfo = $cust_pay->payinfo;
3000 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3001 #$content{expiration} = "$2/$1";
3003 $content{card_number} = $payinfo = $self->payinfo;
3004 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3005 $content{expiration} = "$2/$1";
3008 } elsif ( $method eq 'ECHECK' ) {
3009 ( $content{account_number}, $content{routing_code} ) =
3010 split('@', $payinfo = $self->payinfo);
3011 $content{bank_name} = $self->payname;
3012 $content{account_type} = 'CHECKING';
3013 $content{account_name} = $payname;
3014 $content{customer_org} = $self->company ? 'B' : 'I';
3015 $content{customer_ssn} = $self->ss;
3016 } elsif ( $method eq 'LEC' ) {
3017 $content{phone} = $payinfo = $self->payinfo;
3021 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3022 my %sub_content = $refund->content(
3023 'action' => 'credit',
3024 'customer_id' => $self->custnum,
3025 'last_name' => $paylast,
3026 'first_name' => $payfirst,
3028 'address' => $address,
3029 'city' => $self->city,
3030 'state' => $self->state,
3031 'zip' => $self->zip,
3032 'country' => $self->country,
3034 'phone' => $self->daytime || $self->night,
3037 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3041 return "$processor error: ". $refund->error_message
3042 unless $refund->is_success();
3044 my %method2payby = (
3050 my $paybatch = "$processor:". $refund->authorization;
3051 $paybatch .= ':'. $refund->order_number
3052 if $refund->can('order_number') && $refund->order_number;
3054 while ( $cust_pay && $cust_pay->unappled < $amount ) {
3055 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3056 last unless @cust_bill_pay;
3057 my $cust_bill_pay = pop @cust_bill_pay;
3058 my $error = $cust_bill_pay->delete;
3062 my $cust_refund = new FS::cust_refund ( {
3063 'custnum' => $self->custnum,
3064 'paynum' => $options{'paynum'},
3065 'refund' => $amount,
3067 'payby' => $method2payby{$method},
3068 'payinfo' => $payinfo,
3069 'paybatch' => $paybatch,
3070 'reason' => $options{'reason'} || 'card or ACH refund',
3072 my $error = $cust_refund->insert;
3074 $cust_refund->paynum(''); #try again with no specific paynum
3075 my $error2 = $cust_refund->insert;
3077 # gah, even with transactions.
3078 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3079 "error inserting refund ($processor): $error2".
3080 " (previously tried insert with paynum #$options{'paynum'}" .
3093 Returns the total owed for this customer on all invoices
3094 (see L<FS::cust_bill/owed>).
3100 $self->total_owed_date(2145859200); #12/31/2037
3103 =item total_owed_date TIME
3105 Returns the total owed for this customer on all invoices with date earlier than
3106 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3107 see L<Time::Local> and L<Date::Parse> for conversion functions.
3111 sub total_owed_date {
3115 foreach my $cust_bill (
3116 grep { $_->_date <= $time }
3117 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3119 $total_bill += $cust_bill->owed;
3121 sprintf( "%.2f", $total_bill );
3124 =item apply_credits OPTION => VALUE ...
3126 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3127 to outstanding invoice balances in chronological order (or reverse
3128 chronological order if the I<order> option is set to B<newest>) and returns the
3129 value of any remaining unapplied credits available for refund (see
3130 L<FS::cust_refund>).
3138 return 0 unless $self->total_credited;
3140 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3141 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3143 my @invoices = $self->open_cust_bill;
3144 @invoices = sort { $b->_date <=> $a->_date } @invoices
3145 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3148 foreach my $cust_bill ( @invoices ) {
3151 if ( !defined($credit) || $credit->credited == 0) {
3152 $credit = pop @credits or last;
3155 if ($cust_bill->owed >= $credit->credited) {
3156 $amount=$credit->credited;
3158 $amount=$cust_bill->owed;
3161 my $cust_credit_bill = new FS::cust_credit_bill ( {
3162 'crednum' => $credit->crednum,
3163 'invnum' => $cust_bill->invnum,
3164 'amount' => $amount,
3166 my $error = $cust_credit_bill->insert;
3167 die $error if $error;
3169 redo if ($cust_bill->owed > 0);
3173 return $self->total_credited;
3176 =item apply_payments
3178 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3179 to outstanding invoice balances in chronological order.
3181 #and returns the value of any remaining unapplied payments.
3185 sub apply_payments {
3190 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3191 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3193 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3194 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3198 foreach my $cust_bill ( @invoices ) {
3201 if ( !defined($payment) || $payment->unapplied == 0 ) {
3202 $payment = pop @payments or last;
3205 if ( $cust_bill->owed >= $payment->unapplied ) {
3206 $amount = $payment->unapplied;
3208 $amount = $cust_bill->owed;
3211 my $cust_bill_pay = new FS::cust_bill_pay ( {
3212 'paynum' => $payment->paynum,
3213 'invnum' => $cust_bill->invnum,
3214 'amount' => $amount,
3216 my $error = $cust_bill_pay->insert;
3217 die $error if $error;
3219 redo if ( $cust_bill->owed > 0);
3223 return $self->total_unapplied_payments;
3226 =item total_credited
3228 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3229 customer. See L<FS::cust_credit/credited>.
3233 sub total_credited {
3235 my $total_credit = 0;
3236 foreach my $cust_credit ( qsearch('cust_credit', {
3237 'custnum' => $self->custnum,
3239 $total_credit += $cust_credit->credited;
3241 sprintf( "%.2f", $total_credit );
3244 =item total_unapplied_payments
3246 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3247 See L<FS::cust_pay/unapplied>.
3251 sub total_unapplied_payments {
3253 my $total_unapplied = 0;
3254 foreach my $cust_pay ( qsearch('cust_pay', {
3255 'custnum' => $self->custnum,
3257 $total_unapplied += $cust_pay->unapplied;
3259 sprintf( "%.2f", $total_unapplied );
3264 Returns the balance for this customer (total_owed minus total_credited
3265 minus total_unapplied_payments).
3272 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
3276 =item balance_date TIME
3278 Returns the balance for this customer, only considering invoices with date
3279 earlier than TIME (total_owed_date minus total_credited minus
3280 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3281 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3290 $self->total_owed_date($time)
3291 - $self->total_credited
3292 - $self->total_unapplied_payments
3296 =item in_transit_payments
3298 Returns the total of requests for payments for this customer pending in
3299 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3303 sub in_transit_payments {
3305 my $in_transit_payments = 0;
3306 foreach my $pay_batch ( qsearch('pay_batch', {
3309 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3310 'batchnum' => $pay_batch->batchnum,
3311 'custnum' => $self->custnum,
3313 $in_transit_payments += $cust_pay_batch->amount;
3316 sprintf( "%.2f", $in_transit_payments );
3319 =item paydate_monthyear
3321 Returns a two-element list consisting of the month and year of this customer's
3322 paydate (credit card expiration date for CARD customers)
3326 sub paydate_monthyear {
3328 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3330 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3337 =item payinfo_masked
3339 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.
3341 Credit Cards - Mask all but the last four characters.
3342 Checks - Mask all but last 2 of account number and bank routing number.
3343 Others - Do nothing, return the unmasked string.
3347 sub payinfo_masked {
3349 return $self->paymask;
3352 =item invoicing_list [ ARRAYREF ]
3354 If an arguement is given, sets these email addresses as invoice recipients
3355 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3356 (except as warnings), so use check_invoicing_list first.
3358 Returns a list of email addresses (with svcnum entries expanded).
3360 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3361 check it without disturbing anything by passing nothing.
3363 This interface may change in the future.
3367 sub invoicing_list {
3368 my( $self, $arrayref ) = @_;
3371 my @cust_main_invoice;
3372 if ( $self->custnum ) {
3373 @cust_main_invoice =
3374 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3376 @cust_main_invoice = ();
3378 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3379 #warn $cust_main_invoice->destnum;
3380 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3381 #warn $cust_main_invoice->destnum;
3382 my $error = $cust_main_invoice->delete;
3383 warn $error if $error;
3386 if ( $self->custnum ) {
3387 @cust_main_invoice =
3388 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3390 @cust_main_invoice = ();
3392 my %seen = map { $_->address => 1 } @cust_main_invoice;
3393 foreach my $address ( @{$arrayref} ) {
3394 next if exists $seen{$address} && $seen{$address};
3395 $seen{$address} = 1;
3396 my $cust_main_invoice = new FS::cust_main_invoice ( {
3397 'custnum' => $self->custnum,
3400 my $error = $cust_main_invoice->insert;
3401 warn $error if $error;
3405 if ( $self->custnum ) {
3407 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3414 =item check_invoicing_list ARRAYREF
3416 Checks these arguements as valid input for the invoicing_list method. If there
3417 is an error, returns the error, otherwise returns false.
3421 sub check_invoicing_list {
3422 my( $self, $arrayref ) = @_;
3423 foreach my $address ( @{$arrayref} ) {
3425 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3426 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3429 my $cust_main_invoice = new FS::cust_main_invoice ( {
3430 'custnum' => $self->custnum,
3433 my $error = $self->custnum
3434 ? $cust_main_invoice->check
3435 : $cust_main_invoice->checkdest
3437 return $error if $error;
3442 =item set_default_invoicing_list
3444 Sets the invoicing list to all accounts associated with this customer,
3445 overwriting any previous invoicing list.
3449 sub set_default_invoicing_list {
3451 $self->invoicing_list($self->all_emails);
3456 Returns the email addresses of all accounts provisioned for this customer.
3463 foreach my $cust_pkg ( $self->all_pkgs ) {
3464 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3466 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3467 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3469 $list{$_}=1 foreach map { $_->email } @svc_acct;
3474 =item invoicing_list_addpost
3476 Adds postal invoicing to this customer. If this customer is already configured
3477 to receive postal invoices, does nothing.
3481 sub invoicing_list_addpost {
3483 return if grep { $_ eq 'POST' } $self->invoicing_list;
3484 my @invoicing_list = $self->invoicing_list;
3485 push @invoicing_list, 'POST';
3486 $self->invoicing_list(\@invoicing_list);
3489 =item invoicing_list_emailonly
3491 Returns the list of email invoice recipients (invoicing_list without non-email
3492 destinations such as POST and FAX).
3496 sub invoicing_list_emailonly {
3498 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3501 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3503 Returns an array of customers referred by this customer (referral_custnum set
3504 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3505 customers referred by customers referred by this customer and so on, inclusive.
3506 The default behavior is DEPTH 1 (no recursion).
3510 sub referral_cust_main {
3512 my $depth = @_ ? shift : 1;
3513 my $exclude = @_ ? shift : {};
3516 map { $exclude->{$_->custnum}++; $_; }
3517 grep { ! $exclude->{ $_->custnum } }
3518 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3522 map { $_->referral_cust_main($depth-1, $exclude) }
3529 =item referral_cust_main_ncancelled
3531 Same as referral_cust_main, except only returns customers with uncancelled
3536 sub referral_cust_main_ncancelled {
3538 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3541 =item referral_cust_pkg [ DEPTH ]
3543 Like referral_cust_main, except returns a flat list of all unsuspended (and
3544 uncancelled) packages for each customer. The number of items in this list may
3545 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3549 sub referral_cust_pkg {
3551 my $depth = @_ ? shift : 1;
3553 map { $_->unsuspended_pkgs }
3554 grep { $_->unsuspended_pkgs }
3555 $self->referral_cust_main($depth);
3558 =item referring_cust_main
3560 Returns the single cust_main record for the customer who referred this customer
3561 (referral_custnum), or false.
3565 sub referring_cust_main {
3567 return '' unless $self->referral_custnum;
3568 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3571 =item credit AMOUNT, REASON
3573 Applies a credit to this customer. If there is an error, returns the error,
3574 otherwise returns false.
3579 my( $self, $amount, $reason ) = @_;
3580 my $cust_credit = new FS::cust_credit {
3581 'custnum' => $self->custnum,
3582 'amount' => $amount,
3583 'reason' => $reason,
3585 $cust_credit->insert;
3588 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3590 Creates a one-time charge for this customer. If there is an error, returns
3591 the error, otherwise returns false.
3596 my ( $self, $amount ) = ( shift, shift );
3597 my $pkg = @_ ? shift : 'One-time charge';
3598 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3599 my $taxclass = @_ ? shift : '';
3601 local $SIG{HUP} = 'IGNORE';
3602 local $SIG{INT} = 'IGNORE';
3603 local $SIG{QUIT} = 'IGNORE';
3604 local $SIG{TERM} = 'IGNORE';
3605 local $SIG{TSTP} = 'IGNORE';
3606 local $SIG{PIPE} = 'IGNORE';
3608 my $oldAutoCommit = $FS::UID::AutoCommit;
3609 local $FS::UID::AutoCommit = 0;
3612 my $part_pkg = new FS::part_pkg ( {
3614 'comment' => $comment,
3615 #'setup' => $amount,
3618 'plandata' => "setup_fee=$amount",
3621 'taxclass' => $taxclass,
3624 my $error = $part_pkg->insert;
3626 $dbh->rollback if $oldAutoCommit;
3630 my $pkgpart = $part_pkg->pkgpart;
3631 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3632 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3633 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3634 $error = $type_pkgs->insert;
3636 $dbh->rollback if $oldAutoCommit;
3641 my $cust_pkg = new FS::cust_pkg ( {
3642 'custnum' => $self->custnum,
3643 'pkgpart' => $pkgpart,
3646 $error = $cust_pkg->insert;
3648 $dbh->rollback if $oldAutoCommit;
3652 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3659 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3665 sort { $a->_date <=> $b->_date }
3666 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3669 =item open_cust_bill
3671 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3676 sub open_cust_bill {
3678 grep { $_->owed > 0 } $self->cust_bill;
3683 Returns all the credits (see L<FS::cust_credit>) for this customer.
3689 sort { $a->_date <=> $b->_date }
3690 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3695 Returns all the payments (see L<FS::cust_pay>) for this customer.
3701 sort { $a->_date <=> $b->_date }
3702 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3707 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3713 sort { $a->_date <=> $b->_date }
3714 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3720 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3726 sort { $a->_date <=> $b->_date }
3727 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3730 =item select_for_update
3732 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3737 sub select_for_update {
3739 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3744 Returns a name string for this customer, either "Company (Last, First)" or
3751 my $name = $self->contact;
3752 $name = $self->company. " ($name)" if $self->company;
3758 Returns a name string for this (service/shipping) contact, either
3759 "Company (Last, First)" or "Last, First".
3765 if ( $self->get('ship_last') ) {
3766 my $name = $self->ship_contact;
3767 $name = $self->ship_company. " ($name)" if $self->ship_company;
3776 Returns this customer's full (billing) contact name only, "Last, First"
3782 $self->get('last'). ', '. $self->first;
3787 Returns this customer's full (shipping) contact name only, "Last, First"
3793 $self->get('ship_last')
3794 ? $self->get('ship_last'). ', '. $self->ship_first
3800 Returns this customer's full country name
3806 code2country($self->country);
3811 Returns a status string for this customer, currently:
3815 =item prospect - No packages have ever been ordered
3817 =item active - One or more recurring packages is active
3819 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3821 =item suspended - All non-cancelled recurring packages are suspended
3823 =item cancelled - All recurring packages are cancelled
3831 for my $status (qw( prospect active inactive suspended cancelled )) {
3832 my $method = $status.'_sql';
3833 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3834 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3835 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3836 return $status if $sth->fetchrow_arrayref->[0];
3842 Returns a hex triplet color string for this customer's status.
3846 use vars qw(%statuscolor);
3848 'prospect' => '7e0079', #'000000', #black? naw, purple
3849 'active' => '00CC00', #green
3850 'inactive' => '0000CC', #blue
3851 'suspended' => 'FF9900', #yellow
3852 'cancelled' => 'FF0000', #red
3857 $statuscolor{$self->status};
3862 =head1 CLASS METHODS
3868 Returns an SQL expression identifying prospective cust_main records (customers
3869 with no packages ever ordered)
3873 use vars qw($select_count_pkgs);
3874 $select_count_pkgs =
3875 "SELECT COUNT(*) FROM cust_pkg
3876 WHERE cust_pkg.custnum = cust_main.custnum";
3878 sub select_count_pkgs_sql {
3882 sub prospect_sql { "
3883 0 = ( $select_count_pkgs )
3888 Returns an SQL expression identifying active cust_main records (customers with
3889 no active recurring packages, but otherwise unsuspended/uncancelled).
3894 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
3900 Returns an SQL expression identifying inactive cust_main records (customers with
3901 active recurring packages).
3905 sub inactive_sql { "
3906 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3908 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
3914 Returns an SQL expression identifying suspended cust_main records.
3919 sub suspended_sql { susp_sql(@_); }
3921 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
3923 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3929 Returns an SQL expression identifying cancelled cust_main records.
3933 sub cancelled_sql { cancel_sql(@_); }
3936 my $recurring_sql = FS::cust_pkg->recurring_sql;
3937 #my $recurring_sql = "
3938 # '0' != ( select freq from part_pkg
3939 # where cust_pkg.pkgpart = part_pkg.pkgpart )
3943 0 < ( $select_count_pkgs )
3944 AND 0 = ( $select_count_pkgs AND $recurring_sql
3945 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3951 =item uncancelled_sql
3953 Returns an SQL expression identifying un-cancelled cust_main records.
3957 sub uncancelled_sql { uncancel_sql(@_); }
3958 sub uncancel_sql { "
3959 ( 0 < ( $select_count_pkgs
3960 AND ( cust_pkg.cancel IS NULL
3961 OR cust_pkg.cancel = 0
3964 OR 0 = ( $select_count_pkgs )
3968 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3970 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3971 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
3972 appropriate ship_ field is also searched).
3974 Additional options are the same as FS::Record::qsearch
3979 my( $self, $fuzzy, $hash, @opt) = @_;
3984 check_and_rebuild_fuzzyfiles();
3985 foreach my $field ( keys %$fuzzy ) {
3987 $match{$_}=1 foreach ( amatch( $fuzzy->{$field},
3989 @{ $self->all_X($field) }
3994 foreach ( keys %match ) {
3995 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3996 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
3999 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
4002 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
4004 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
4016 =item smart_search OPTION => VALUE ...
4018 Accepts the following options: I<search>, the string to search for. The string
4019 will be searched for as a customer number, phone number, name or company name,
4020 first searching for an exact match then fuzzy and substring matches (in some
4021 cases - see the source code for the exact heuristics used).
4023 Any additional options treated as an additional qualifier on the search
4026 Returns a (possibly empty) array of FS::cust_main objects.
4033 #here is the agent virtualization
4034 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
4038 my $search = delete $options{'search'};
4039 ( my $alphanum_search = $search ) =~ s/\W//g;
4041 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
4043 #false laziness w/Record::ut_phone
4044 my $phonen = "$1-$2-$3";
4045 $phonen .= " x$4" if $4;
4047 push @cust_main, qsearch( {
4048 'table' => 'cust_main',
4049 'hashref' => { %options },
4050 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4052 join(' OR ', map "$_ = '$phonen'",
4053 qw( daytime night fax
4054 ship_daytime ship_night ship_fax )
4057 " AND $agentnums_sql", #agent virtualization
4060 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
4061 #try looking for matches with extensions unless one was specified
4063 push @cust_main, qsearch( {
4064 'table' => 'cust_main',
4065 'hashref' => { %options },
4066 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4068 join(' OR ', map "$_ LIKE '$phonen\%'",
4070 ship_daytime ship_night )
4073 " AND $agentnums_sql", #agent virtualization
4078 } elsif ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
4080 push @cust_main, qsearch( {
4081 'table' => 'cust_main',
4082 'hashref' => { 'custnum' => $1, %options },
4083 'extra_sql' => " AND $agentnums_sql", #agent virtualization
4086 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
4088 my($company, $last, $first) = ( $1, $2, $3 );
4090 # "Company (Last, First)"
4091 #this is probably something a browser remembered,
4092 #so just do an exact search
4094 foreach my $prefix ( '', 'ship_' ) {
4095 push @cust_main, qsearch( {
4096 'table' => 'cust_main',
4097 'hashref' => { $prefix.'first' => $first,
4098 $prefix.'last' => $last,
4099 $prefix.'company' => $company,
4102 'extra_sql' => " AND $agentnums_sql",
4106 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
4107 # try (ship_){last,company}
4111 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
4112 # # full strings the browser remembers won't work
4113 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
4115 use Lingua::EN::NameParse;
4116 my $NameParse = new Lingua::EN::NameParse(
4118 allow_reversed => 1,
4121 my($last, $first) = ( '', '' );
4122 #maybe disable this too and just rely on NameParse?
4123 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
4125 ($last, $first) = ( $1, $2 );
4127 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
4128 } elsif ( ! $NameParse->parse($value) ) {
4130 my %name = $NameParse->components;
4131 $first = $name{'given_name_1'};
4132 $last = $name{'surname_1'};
4136 if ( $first && $last ) {
4138 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
4141 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4143 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
4144 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
4147 push @cust_main, qsearch( {
4148 'table' => 'cust_main',
4149 'hashref' => \%options,
4150 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4153 # or it just be something that was typed in... (try that in a sec)
4157 my $q_value = dbh->quote($value);
4160 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4161 $sql .= " ( LOWER(last) = $q_value
4162 OR LOWER(company) = $q_value
4163 OR LOWER(ship_last) = $q_value
4164 OR LOWER(ship_company) = $q_value
4167 push @cust_main, qsearch( {
4168 'table' => 'cust_main',
4169 'hashref' => \%options,
4170 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4173 unless ( @cust_main ) { #no exact match, trying substring/fuzzy
4175 #still some false laziness w/ search/cust_main.cgi
4180 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
4181 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
4184 if ( $first && $last ) {
4187 { 'first' => { op=>'ILIKE', value=>"%$first%" },
4188 'last' => { op=>'ILIKE', value=>"%$last%" },
4190 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
4191 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
4198 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
4199 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
4203 foreach my $hashref ( @hashrefs ) {
4205 push @cust_main, qsearch( {
4206 'table' => 'cust_main',
4207 'hashref' => { %$hashref,
4210 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
4219 " AND $agentnums_sql", #extra_sql #agent virtualization
4222 if ( $first && $last ) {
4223 push @cust_main, FS::cust_main->fuzzy_search(
4224 { 'last' => $last, #fuzzy hashref
4225 'first' => $first }, #
4229 foreach my $field ( 'last', 'company' ) {
4231 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
4236 #eliminate duplicates
4238 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
4246 =item check_and_rebuild_fuzzyfiles
4250 use vars qw(@fuzzyfields);
4251 @fuzzyfields = ( 'last', 'first', 'company' );
4253 sub check_and_rebuild_fuzzyfiles {
4254 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4255 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
4258 =item rebuild_fuzzyfiles
4262 sub rebuild_fuzzyfiles {
4264 use Fcntl qw(:flock);
4266 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4267 mkdir $dir, 0700 unless -d $dir;
4269 foreach my $fuzzy ( @fuzzyfields ) {
4271 open(LOCK,">>$dir/cust_main.$fuzzy")
4272 or die "can't open $dir/cust_main.$fuzzy: $!";
4274 or die "can't lock $dir/cust_main.$fuzzy: $!";
4276 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
4277 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
4279 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
4280 my $sth = dbh->prepare("SELECT $field FROM cust_main".
4281 " WHERE $field != '' AND $field IS NOT NULL");
4282 $sth->execute or die $sth->errstr;
4284 while ( my $row = $sth->fetchrow_arrayref ) {
4285 print CACHE $row->[0]. "\n";
4290 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
4292 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
4303 my( $self, $field ) = @_;
4304 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4305 open(CACHE,"<$dir/cust_main.$field")
4306 or die "can't open $dir/cust_main.$field: $!";
4307 my @array = map { chomp; $_; } <CACHE>;
4312 =item append_fuzzyfiles LASTNAME COMPANY
4316 sub append_fuzzyfiles {
4317 #my( $first, $last, $company ) = @_;
4319 &check_and_rebuild_fuzzyfiles;
4321 use Fcntl qw(:flock);
4323 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4325 foreach my $field (qw( first last company )) {
4330 open(CACHE,">>$dir/cust_main.$field")
4331 or die "can't open $dir/cust_main.$field: $!";
4332 flock(CACHE,LOCK_EX)
4333 or die "can't lock $dir/cust_main.$field: $!";
4335 print CACHE "$value\n";
4337 flock(CACHE,LOCK_UN)
4338 or die "can't unlock $dir/cust_main.$field: $!";
4353 #warn join('-',keys %$param);
4354 my $fh = $param->{filehandle};
4355 my $agentnum = $param->{agentnum};
4357 my $refnum = $param->{refnum};
4358 my $pkgpart = $param->{pkgpart};
4360 #my @fields = @{$param->{fields}};
4361 my $format = $param->{'format'};
4364 if ( $format eq 'simple' ) {
4365 @fields = qw( cust_pkg.setup dayphone first last
4366 address1 address2 city state zip comments );
4368 } elsif ( $format eq 'extended' ) {
4369 @fields = qw( agent_custid refnum
4370 last first address1 address2 city state zip country
4372 ship_last ship_first ship_address1 ship_address2
4373 ship_city ship_state ship_zip ship_country
4374 payinfo paycvv paydate
4377 svc_acct.username svc_acct._password
4381 die "unknown format $format";
4384 eval "use Text::CSV_XS;";
4387 my $csv = new Text::CSV_XS;
4394 local $SIG{HUP} = 'IGNORE';
4395 local $SIG{INT} = 'IGNORE';
4396 local $SIG{QUIT} = 'IGNORE';
4397 local $SIG{TERM} = 'IGNORE';
4398 local $SIG{TSTP} = 'IGNORE';
4399 local $SIG{PIPE} = 'IGNORE';
4401 my $oldAutoCommit = $FS::UID::AutoCommit;
4402 local $FS::UID::AutoCommit = 0;
4405 #while ( $columns = $csv->getline($fh) ) {
4407 while ( defined($line=<$fh>) ) {
4409 $csv->parse($line) or do {
4410 $dbh->rollback if $oldAutoCommit;
4411 return "can't parse: ". $csv->error_input();
4414 my @columns = $csv->fields();
4415 #warn join('-',@columns);
4418 agentnum => $agentnum,
4420 country => $conf->config('countrydefault') || 'US',
4421 payby => $payby, #default
4422 paydate => '12/2037', #default
4424 my $billtime = time;
4425 my %cust_pkg = ( pkgpart => $pkgpart );
4427 foreach my $field ( @fields ) {
4429 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|expire|cancel)$/ ) {
4431 #$cust_pkg{$1} = str2time( shift @$columns );
4432 if ( $1 eq 'pkgpart' ) {
4433 $cust_pkg{$1} = shift @columns;
4434 } elsif ( $1 eq 'setup' ) {
4435 $billtime = str2time(shift @columns);
4437 $cust_pkg{$1} = str2time( shift @columns );
4440 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
4442 $svc_acct{$1} = shift @columns;
4446 #refnum interception
4447 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
4449 my $referral = $columns[0];
4450 my $part_referral = new FS::part_referral {
4451 'referral' => $referral,
4452 'agentnum' => $agentnum,
4455 my $error = $part_referral->insert;
4457 $dbh->rollback if $oldAutoCommit;
4458 return "can't auto-insert advertising source: $referral: $error";
4460 $columns[0] = $part_referral->refnum;
4463 #$cust_main{$field} = shift @$columns;
4464 $cust_main{$field} = shift @columns;
4468 my $invoicing_list = $cust_main{'invoicing_list'}
4469 ? [ delete $cust_main{'invoicing_list'} ]
4472 my $cust_main = new FS::cust_main ( \%cust_main );
4475 tie my %hash, 'Tie::RefHash'; #this part is important
4477 if ( $cust_pkg{'pkgpart'} ) {
4478 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
4481 if ( $svc_acct{'username'} ) {
4482 $svc_acct{svcpart} = $cust_pkg->part_pkg->svcpart( 'svc_acct' );
4483 push @svc_acct, new FS::svc_acct ( \%svc_acct )
4486 $hash{$cust_pkg} = \@svc_acct;
4489 my $error = $cust_main->insert( \%hash, $invoicing_list );
4492 $dbh->rollback if $oldAutoCommit;
4493 return "can't insert customer for $line: $error";
4496 if ( $format eq 'simple' ) {
4498 #false laziness w/bill.cgi
4499 $error = $cust_main->bill( 'time' => $billtime );
4501 $dbh->rollback if $oldAutoCommit;
4502 return "can't bill customer for $line: $error";
4505 $cust_main->apply_payments;
4506 $cust_main->apply_credits;
4508 $error = $cust_main->collect();
4510 $dbh->rollback if $oldAutoCommit;
4511 return "can't collect customer for $line: $error";
4519 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4521 return "Empty file!" unless $imported;
4533 #warn join('-',keys %$param);
4534 my $fh = $param->{filehandle};
4535 my @fields = @{$param->{fields}};
4537 eval "use Text::CSV_XS;";
4540 my $csv = new Text::CSV_XS;
4547 local $SIG{HUP} = 'IGNORE';
4548 local $SIG{INT} = 'IGNORE';
4549 local $SIG{QUIT} = 'IGNORE';
4550 local $SIG{TERM} = 'IGNORE';
4551 local $SIG{TSTP} = 'IGNORE';
4552 local $SIG{PIPE} = 'IGNORE';
4554 my $oldAutoCommit = $FS::UID::AutoCommit;
4555 local $FS::UID::AutoCommit = 0;
4558 #while ( $columns = $csv->getline($fh) ) {
4560 while ( defined($line=<$fh>) ) {
4562 $csv->parse($line) or do {
4563 $dbh->rollback if $oldAutoCommit;
4564 return "can't parse: ". $csv->error_input();
4567 my @columns = $csv->fields();
4568 #warn join('-',@columns);
4571 foreach my $field ( @fields ) {
4572 $row{$field} = shift @columns;
4575 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4576 unless ( $cust_main ) {
4577 $dbh->rollback if $oldAutoCommit;
4578 return "unknown custnum $row{'custnum'}";
4581 if ( $row{'amount'} > 0 ) {
4582 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4584 $dbh->rollback if $oldAutoCommit;
4588 } elsif ( $row{'amount'} < 0 ) {
4589 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4592 $dbh->rollback if $oldAutoCommit;
4602 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4604 return "Empty file!" unless $imported;
4616 The delete method should possibly take an FS::cust_main object reference
4617 instead of a scalar customer number.
4619 Bill and collect options should probably be passed as references instead of a
4622 There should probably be a configuration file with a list of allowed credit
4625 No multiple currency support (probably a larger project than just this module).
4627 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4631 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4632 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4633 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.