4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5 $import $skip_fuzzyfiles $ignore_expired_card );
6 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 eval "use Time::Local;";
12 die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
13 if $] < 5.006 && !defined($Time::Local::VERSION);
14 #eval "use Time::Local qw(timelocal timelocal_nocheck);";
15 eval "use Time::Local qw(timelocal_nocheck);";
17 use Digest::MD5 qw(md5_base64);
21 use String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
24 use FS::UID qw( getotaker dbh );
25 use FS::Record qw( qsearchs qsearch dbdef );
26 use FS::Misc qw( send_email );
27 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
33 use FS::cust_pay_void;
36 use FS::part_referral;
37 use FS::cust_main_county;
39 use FS::cust_main_invoice;
40 use FS::cust_credit_bill;
41 use FS::cust_bill_pay;
42 use FS::prepay_credit;
45 use FS::part_bill_event qw(due_events);
46 use FS::cust_bill_event;
47 use FS::cust_tax_exempt;
48 use FS::cust_tax_exempt_pkg;
50 use FS::payment_gateway;
51 use FS::agent_payment_gateway;
53 use FS::payinfo_Mixin;
55 @ISA = qw( FS::Record FS::payinfo_Mixin );
57 @EXPORT_OK = qw( smart_search );
59 $realtime_bop_decline_quiet = 0;
61 # 1 is mostly method/subroutine entry and options
62 # 2 traces progress of some operations
63 # 3 is even more information including possibly sensitive data
65 $me = '[FS::cust_main]';
69 $ignore_expired_card = 0;
71 @encrypted_fields = ('payinfo', 'paycvv');
73 #ask FS::UID to run this stuff for us later
74 #$FS::UID::callback{'FS::cust_main'} = sub {
75 install_callback FS::UID sub {
77 #yes, need it for stuff below (prolly should be cached)
82 my ( $hashref, $cache ) = @_;
83 if ( exists $hashref->{'pkgnum'} ) {
84 #@{ $self->{'_pkgnum'} } = ();
85 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
86 $self->{'_pkgnum'} = $subcache;
87 #push @{ $self->{'_pkgnum'} },
88 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
94 FS::cust_main - Object methods for cust_main records
100 $record = new FS::cust_main \%hash;
101 $record = new FS::cust_main { 'column' => 'value' };
103 $error = $record->insert;
105 $error = $new_record->replace($old_record);
107 $error = $record->delete;
109 $error = $record->check;
111 @cust_pkg = $record->all_pkgs;
113 @cust_pkg = $record->ncancelled_pkgs;
115 @cust_pkg = $record->suspended_pkgs;
117 $error = $record->bill;
118 $error = $record->bill %options;
119 $error = $record->bill 'time' => $time;
121 $error = $record->collect;
122 $error = $record->collect %options;
123 $error = $record->collect 'invoice_time' => $time,
128 An FS::cust_main object represents a customer. FS::cust_main inherits from
129 FS::Record. The following fields are currently supported:
133 =item custnum - primary key (assigned automatically for new customers)
135 =item agentnum - agent (see L<FS::agent>)
137 =item refnum - Advertising source (see L<FS::part_referral>)
143 =item ss - social security number (optional)
145 =item company - (optional)
149 =item address2 - (optional)
153 =item county - (optional, see L<FS::cust_main_county>)
155 =item state - (see L<FS::cust_main_county>)
159 =item country - (see L<FS::cust_main_county>)
161 =item daytime - phone (optional)
163 =item night - phone (optional)
165 =item fax - phone (optional)
167 =item ship_first - name
169 =item ship_last - name
171 =item ship_company - (optional)
175 =item ship_address2 - (optional)
179 =item ship_county - (optional, see L<FS::cust_main_county>)
181 =item ship_state - (see L<FS::cust_main_county>)
185 =item ship_country - (see L<FS::cust_main_county>)
187 =item ship_daytime - phone (optional)
189 =item ship_night - phone (optional)
191 =item ship_fax - phone (optional)
193 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
195 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
197 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
201 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
203 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
205 =item paystart_month - start date month (maestro/solo cards only)
207 =item paystart_year - start date year (maestro/solo cards only)
209 =item payissue - issue number (maestro/solo cards only)
211 =item payname - name on card or billing name
213 =item payip - IP address from which payment information was received
215 =item tax - tax exempt, empty or `Y'
217 =item otaker - order taker (assigned automatically, see L<FS::UID>)
219 =item comments - comments (optional)
221 =item referral_custnum - referring customer number
223 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
233 Creates a new customer. To add the customer to the database, see L<"insert">.
235 Note that this stores the hash reference, not a distinct copy of the hash it
236 points to. You can ask the object for a copy with the I<hash> method.
240 sub table { 'cust_main'; }
242 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
244 Adds this customer to the database. If there is an error, returns the error,
245 otherwise returns false.
247 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
248 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
249 are inserted atomicly, or the transaction is rolled back. Passing an empty
250 hash reference is equivalent to not supplying this parameter. There should be
251 a better explanation of this, but until then, here's an example:
254 tie %hash, 'Tie::RefHash'; #this part is important
256 $cust_pkg => [ $svc_acct ],
259 $cust_main->insert( \%hash );
261 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
262 be set as the invoicing list (see L<"invoicing_list">). Errors return as
263 expected and rollback the entire transaction; it is not necessary to call
264 check_invoicing_list first. The invoicing_list is set after the records in the
265 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
266 invoicing_list destination to the newly-created svc_acct. Here's an example:
268 $cust_main->insert( {}, [ $email, 'POST' ] );
270 Currently available options are: I<depend_jobnum> and I<noexport>.
272 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
273 on the supplied jobnum (they will not run until the specific job completes).
274 This can be used to defer provisioning until some action completes (such
275 as running the customer's credit card successfully).
277 The I<noexport> option is deprecated. If I<noexport> is set true, no
278 provisioning jobs (exports) are scheduled. (You can schedule them later with
279 the B<reexport> method.)
285 my $cust_pkgs = @_ ? shift : {};
286 my $invoicing_list = @_ ? shift : '';
288 warn "$me insert called with options ".
289 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
292 local $SIG{HUP} = 'IGNORE';
293 local $SIG{INT} = 'IGNORE';
294 local $SIG{QUIT} = 'IGNORE';
295 local $SIG{TERM} = 'IGNORE';
296 local $SIG{TSTP} = 'IGNORE';
297 local $SIG{PIPE} = 'IGNORE';
299 my $oldAutoCommit = $FS::UID::AutoCommit;
300 local $FS::UID::AutoCommit = 0;
303 my $prepay_identifier = '';
304 my( $amount, $seconds ) = ( 0, 0 );
306 if ( $self->payby eq 'PREPAY' ) {
308 $self->payby('BILL');
309 $prepay_identifier = $self->payinfo;
312 warn " looking up prepaid card $prepay_identifier\n"
315 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
317 $dbh->rollback if $oldAutoCommit;
318 #return "error applying prepaid card (transaction rolled back): $error";
322 $payby = 'PREP' if $amount;
324 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
327 $self->payby('BILL');
328 $amount = $self->paid;
332 warn " inserting $self\n"
335 $self->signupdate(time) unless $self->signupdate;
337 my $error = $self->SUPER::insert;
339 $dbh->rollback if $oldAutoCommit;
340 #return "inserting cust_main record (transaction rolled back): $error";
344 warn " setting invoicing list\n"
347 if ( $invoicing_list ) {
348 $error = $self->check_invoicing_list( $invoicing_list );
350 $dbh->rollback if $oldAutoCommit;
351 return "checking invoicing_list (transaction rolled back): $error";
353 $self->invoicing_list( $invoicing_list );
356 if ( $conf->config('cust_main-skeleton_tables')
357 && $conf->config('cust_main-skeleton_custnum') ) {
359 warn " inserting skeleton records\n"
362 my $error = $self->start_copy_skel;
364 $dbh->rollback if $oldAutoCommit;
370 warn " ordering packages\n"
373 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
375 $dbh->rollback if $oldAutoCommit;
380 $dbh->rollback if $oldAutoCommit;
381 return "No svc_acct record to apply pre-paid time";
385 warn " inserting initial $payby payment of $amount\n"
387 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
389 $dbh->rollback if $oldAutoCommit;
390 return "inserting payment (transaction rolled back): $error";
394 unless ( $import || $skip_fuzzyfiles ) {
395 warn " queueing fuzzyfiles update\n"
397 $error = $self->queue_fuzzyfiles_update;
399 $dbh->rollback if $oldAutoCommit;
400 return "updating fuzzy search cache: $error";
404 warn " insert complete; committing transaction\n"
407 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
412 sub start_copy_skel {
415 #'mg_user_preference' => {},
416 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
417 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
418 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
419 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
420 my @tables = eval($conf->config_binary('cust_main-skeleton_tables'));
423 _copy_skel( 'cust_main', #tablename
424 $conf->config('cust_main-skeleton_custnum'), #sourceid
425 $self->custnum, #destid
426 @tables, #child tables
430 #recursive subroutine, not a method
432 my( $table, $sourceid, $destid, %child_tables ) = @_;
435 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
436 ( $table, $primary_key ) = ( $1, $2 );
438 my $dbdef_table = dbdef->table($table);
439 $primary_key = $dbdef_table->primary_key
440 or return "$table has no primary key".
441 " (or do you need to run dbdef-create?)";
444 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
445 join (', ', keys %child_tables). "\n"
448 foreach my $child_table_def ( keys %child_tables ) {
452 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
453 ( $child_table, $child_pkey ) = ( $1, $2 );
455 $child_table = $child_table_def;
457 $child_pkey = dbdef->table($child_table)->primary_key;
458 # or return "$table has no primary key".
459 # " (or do you need to run dbdef-create?)\n";
463 if ( keys %{ $child_tables{$child_table_def} } ) {
465 return "$child_table has no primary key".
466 " (run dbdef-create or try specifying it?)\n"
469 #false laziness w/Record::insert and only works on Pg
470 #refactor the proper last-inserted-id stuff out of Record::insert if this
471 # ever gets use for anything besides a quick kludge for one customer
472 my $default = dbdef->table($child_table)->column($child_pkey)->default;
473 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
474 or return "can't parse $child_table.$child_pkey default value ".
475 " for sequence name: $default";
480 my @sel_columns = grep { $_ ne $primary_key }
481 dbdef->table($child_table)->columns;
482 my $sel_columns = join(', ', @sel_columns );
484 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
485 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
486 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
488 my $sel_st = "SELECT $sel_columns FROM $child_table".
489 " WHERE $primary_key = $sourceid";
492 my $sel_sth = dbh->prepare( $sel_st )
493 or return dbh->errstr;
495 $sel_sth->execute or return $sel_sth->errstr;
497 while ( my $row = $sel_sth->fetchrow_hashref ) {
499 warn " selected row: ".
500 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
504 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
505 my $ins_sth =dbh->prepare($statement)
506 or return dbh->errstr;
507 my @param = ( $destid, map $row->{$_}, @ins_columns );
508 warn " $statement: [ ". join(', ', @param). " ]\n"
510 $ins_sth->execute( @param )
511 or return $ins_sth->errstr;
513 #next unless keys %{ $child_tables{$child_table} };
514 next unless $sequence;
516 #another section of that laziness
517 my $seq_sql = "SELECT currval('$sequence')";
518 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
519 $seq_sth->execute or return $seq_sth->errstr;
520 my $insertid = $seq_sth->fetchrow_arrayref->[0];
522 # don't drink soap! recurse! recurse! okay!
524 _copy_skel( $child_table_def,
525 $row->{$child_pkey}, #sourceid
527 %{ $child_tables{$child_table_def} },
529 return $error if $error;
539 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
541 Like the insert method on an existing record, this method orders a package
542 and included services atomicaly. Pass a Tie::RefHash data structure to this
543 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
544 be a better explanation of this, but until then, here's an example:
547 tie %hash, 'Tie::RefHash'; #this part is important
549 $cust_pkg => [ $svc_acct ],
552 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
554 Services can be new, in which case they are inserted, or existing unaudited
555 services, in which case they are linked to the newly-created package.
557 Currently available options are: I<depend_jobnum> and I<noexport>.
559 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
560 on the supplied jobnum (they will not run until the specific job completes).
561 This can be used to defer provisioning until some action completes (such
562 as running the customer's credit card successfully).
564 The I<noexport> option is deprecated. If I<noexport> is set true, no
565 provisioning jobs (exports) are scheduled. (You can schedule them later with
566 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
567 on the cust_main object is not recommended, as existing services will also be
574 my $cust_pkgs = shift;
577 my %svc_options = ();
578 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
579 if exists $options{'depend_jobnum'};
580 warn "$me order_pkgs called with options ".
581 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
584 local $SIG{HUP} = 'IGNORE';
585 local $SIG{INT} = 'IGNORE';
586 local $SIG{QUIT} = 'IGNORE';
587 local $SIG{TERM} = 'IGNORE';
588 local $SIG{TSTP} = 'IGNORE';
589 local $SIG{PIPE} = 'IGNORE';
591 my $oldAutoCommit = $FS::UID::AutoCommit;
592 local $FS::UID::AutoCommit = 0;
595 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
597 foreach my $cust_pkg ( keys %$cust_pkgs ) {
598 $cust_pkg->custnum( $self->custnum );
599 my $error = $cust_pkg->insert;
601 $dbh->rollback if $oldAutoCommit;
602 return "inserting cust_pkg (transaction rolled back): $error";
604 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
605 if ( $svc_something->svcnum ) {
606 my $old_cust_svc = $svc_something->cust_svc;
607 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
608 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
609 $error = $new_cust_svc->replace($old_cust_svc);
611 $svc_something->pkgnum( $cust_pkg->pkgnum );
612 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
613 $svc_something->seconds( $svc_something->seconds + $$seconds );
616 $error = $svc_something->insert(%svc_options);
619 $dbh->rollback if $oldAutoCommit;
620 #return "inserting svc_ (transaction rolled back): $error";
626 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
630 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
632 Recharges this (existing) customer with the specified prepaid card (see
633 L<FS::prepay_credit>), specified either by I<identifier> or as an
634 FS::prepay_credit object. If there is an error, returns the error, otherwise
637 Optionally, four scalar references can be passed as well. They will have their
638 values filled in with the amount, number of seconds, and number of upload and
639 download bytes applied by this prepaid
644 sub recharge_prepay {
645 my( $self, $prepay_credit, $amountref, $secondsref,
646 $upbytesref, $downbytesref, $totalbytesref ) = @_;
648 local $SIG{HUP} = 'IGNORE';
649 local $SIG{INT} = 'IGNORE';
650 local $SIG{QUIT} = 'IGNORE';
651 local $SIG{TERM} = 'IGNORE';
652 local $SIG{TSTP} = 'IGNORE';
653 local $SIG{PIPE} = 'IGNORE';
655 my $oldAutoCommit = $FS::UID::AutoCommit;
656 local $FS::UID::AutoCommit = 0;
659 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
661 my $error = $self->get_prepay($prepay_credit, \$amount,
662 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
663 || $self->increment_seconds($seconds)
664 || $self->increment_upbytes($upbytes)
665 || $self->increment_downbytes($downbytes)
666 || $self->increment_totalbytes($totalbytes)
667 || $self->insert_cust_pay_prepay( $amount,
669 ? $prepay_credit->identifier
674 $dbh->rollback if $oldAutoCommit;
678 if ( defined($amountref) ) { $$amountref = $amount; }
679 if ( defined($secondsref) ) { $$secondsref = $seconds; }
680 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
681 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
682 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
684 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
689 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
691 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
692 specified either by I<identifier> or as an FS::prepay_credit object.
694 References to I<amount> and I<seconds> scalars should be passed as arguments
695 and will be incremented by the values of the prepaid card.
697 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
698 check or set this customer's I<agentnum>.
700 If there is an error, returns the error, otherwise returns false.
706 my( $self, $prepay_credit, $amountref, $secondsref,
707 $upref, $downref, $totalref) = @_;
709 local $SIG{HUP} = 'IGNORE';
710 local $SIG{INT} = 'IGNORE';
711 local $SIG{QUIT} = 'IGNORE';
712 local $SIG{TERM} = 'IGNORE';
713 local $SIG{TSTP} = 'IGNORE';
714 local $SIG{PIPE} = 'IGNORE';
716 my $oldAutoCommit = $FS::UID::AutoCommit;
717 local $FS::UID::AutoCommit = 0;
720 unless ( ref($prepay_credit) ) {
722 my $identifier = $prepay_credit;
724 $prepay_credit = qsearchs(
726 { 'identifier' => $prepay_credit },
731 unless ( $prepay_credit ) {
732 $dbh->rollback if $oldAutoCommit;
733 return "Invalid prepaid card: ". $identifier;
738 if ( $prepay_credit->agentnum ) {
739 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
740 $dbh->rollback if $oldAutoCommit;
741 return "prepaid card not valid for agent ". $self->agentnum;
743 $self->agentnum($prepay_credit->agentnum);
746 my $error = $prepay_credit->delete;
748 $dbh->rollback if $oldAutoCommit;
749 return "removing prepay_credit (transaction rolled back): $error";
752 $$amountref += $prepay_credit->amount;
753 $$secondsref += $prepay_credit->seconds;
754 $$upref += $prepay_credit->upbytes;
755 $$downref += $prepay_credit->downbytes;
756 $$totalref += $prepay_credit->totalbytes;
758 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
763 =item increment_upbytes SECONDS
765 Updates this customer's single or primary account (see L<FS::svc_acct>) by
766 the specified number of upbytes. If there is an error, returns the error,
767 otherwise returns false.
771 sub increment_upbytes {
772 _increment_column( shift, 'upbytes', @_);
775 =item increment_downbytes SECONDS
777 Updates this customer's single or primary account (see L<FS::svc_acct>) by
778 the specified number of downbytes. If there is an error, returns the error,
779 otherwise returns false.
783 sub increment_downbytes {
784 _increment_column( shift, 'downbytes', @_);
787 =item increment_totalbytes SECONDS
789 Updates this customer's single or primary account (see L<FS::svc_acct>) by
790 the specified number of totalbytes. If there is an error, returns the error,
791 otherwise returns false.
795 sub increment_totalbytes {
796 _increment_column( shift, 'totalbytes', @_);
799 =item increment_seconds SECONDS
801 Updates this customer's single or primary account (see L<FS::svc_acct>) by
802 the specified number of seconds. If there is an error, returns the error,
803 otherwise returns false.
807 sub increment_seconds {
808 _increment_column( shift, 'seconds', @_);
811 =item _increment_column AMOUNT
813 Updates this customer's single or primary account (see L<FS::svc_acct>) by
814 the specified number of seconds or bytes. If there is an error, returns
815 the error, otherwise returns false.
819 sub _increment_column {
820 my( $self, $column, $amount ) = @_;
821 warn "$me increment_column called: $column, $amount\n"
824 return '' unless $amount;
826 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
827 $self->ncancelled_pkgs;
830 return 'No packages with primary or single services found'.
831 ' to apply pre-paid time';
832 } elsif ( scalar(@cust_pkg) > 1 ) {
833 #maybe have a way to specify the package/account?
834 return 'Multiple packages found to apply pre-paid time';
837 my $cust_pkg = $cust_pkg[0];
838 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
842 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
845 return 'No account found to apply pre-paid time';
846 } elsif ( scalar(@cust_svc) > 1 ) {
847 return 'Multiple accounts found to apply pre-paid time';
850 my $svc_acct = $cust_svc[0]->svc_x;
851 warn " found service svcnum ". $svc_acct->pkgnum.
852 ' ('. $svc_acct->email. ")\n"
855 $column = "increment_$column";
856 $svc_acct->$column($amount);
860 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
862 Inserts a prepayment in the specified amount for this customer. An optional
863 second argument can specify the prepayment identifier for tracking purposes.
864 If there is an error, returns the error, otherwise returns false.
868 sub insert_cust_pay_prepay {
869 shift->insert_cust_pay('PREP', @_);
872 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
874 Inserts a cash payment in the specified amount for this customer. An optional
875 second argument can specify the payment identifier for tracking purposes.
876 If there is an error, returns the error, otherwise returns false.
880 sub insert_cust_pay_cash {
881 shift->insert_cust_pay('CASH', @_);
884 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
886 Inserts a Western Union payment in the specified amount for this customer. An
887 optional second argument can specify the prepayment identifier for tracking
888 purposes. If there is an error, returns the error, otherwise returns false.
892 sub insert_cust_pay_west {
893 shift->insert_cust_pay('WEST', @_);
896 sub insert_cust_pay {
897 my( $self, $payby, $amount ) = splice(@_, 0, 3);
898 my $payinfo = scalar(@_) ? shift : '';
900 my $cust_pay = new FS::cust_pay {
901 'custnum' => $self->custnum,
902 'paid' => sprintf('%.2f', $amount),
903 #'_date' => #date the prepaid card was purchased???
905 'payinfo' => $payinfo,
913 This method is deprecated. See the I<depend_jobnum> option to the insert and
914 order_pkgs methods for a better way to defer provisioning.
916 Re-schedules all exports by calling the B<reexport> method of all associated
917 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
918 otherwise returns false.
925 carp "WARNING: FS::cust_main::reexport is deprectated; ".
926 "use the depend_jobnum option to insert or order_pkgs to delay export";
928 local $SIG{HUP} = 'IGNORE';
929 local $SIG{INT} = 'IGNORE';
930 local $SIG{QUIT} = 'IGNORE';
931 local $SIG{TERM} = 'IGNORE';
932 local $SIG{TSTP} = 'IGNORE';
933 local $SIG{PIPE} = 'IGNORE';
935 my $oldAutoCommit = $FS::UID::AutoCommit;
936 local $FS::UID::AutoCommit = 0;
939 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
940 my $error = $cust_pkg->reexport;
942 $dbh->rollback if $oldAutoCommit;
947 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
952 =item delete NEW_CUSTNUM
954 This deletes the customer. If there is an error, returns the error, otherwise
957 This will completely remove all traces of the customer record. This is not
958 what you want when a customer cancels service; for that, cancel all of the
959 customer's packages (see L</cancel>).
961 If the customer has any uncancelled packages, you need to pass a new (valid)
962 customer number for those packages to be transferred to. Cancelled packages
963 will be deleted. Did I mention that this is NOT what you want when a customer
964 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
966 You can't delete a customer with invoices (see L<FS::cust_bill>),
967 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
968 refunds (see L<FS::cust_refund>).
975 local $SIG{HUP} = 'IGNORE';
976 local $SIG{INT} = 'IGNORE';
977 local $SIG{QUIT} = 'IGNORE';
978 local $SIG{TERM} = 'IGNORE';
979 local $SIG{TSTP} = 'IGNORE';
980 local $SIG{PIPE} = 'IGNORE';
982 my $oldAutoCommit = $FS::UID::AutoCommit;
983 local $FS::UID::AutoCommit = 0;
986 if ( $self->cust_bill ) {
987 $dbh->rollback if $oldAutoCommit;
988 return "Can't delete a customer with invoices";
990 if ( $self->cust_credit ) {
991 $dbh->rollback if $oldAutoCommit;
992 return "Can't delete a customer with credits";
994 if ( $self->cust_pay ) {
995 $dbh->rollback if $oldAutoCommit;
996 return "Can't delete a customer with payments";
998 if ( $self->cust_refund ) {
999 $dbh->rollback if $oldAutoCommit;
1000 return "Can't delete a customer with refunds";
1003 my @cust_pkg = $self->ncancelled_pkgs;
1005 my $new_custnum = shift;
1006 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1007 $dbh->rollback if $oldAutoCommit;
1008 return "Invalid new customer number: $new_custnum";
1010 foreach my $cust_pkg ( @cust_pkg ) {
1011 my %hash = $cust_pkg->hash;
1012 $hash{'custnum'} = $new_custnum;
1013 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1014 my $error = $new_cust_pkg->replace($cust_pkg);
1016 $dbh->rollback if $oldAutoCommit;
1021 my @cancelled_cust_pkg = $self->all_pkgs;
1022 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1023 my $error = $cust_pkg->delete;
1025 $dbh->rollback if $oldAutoCommit;
1030 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1031 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1033 my $error = $cust_main_invoice->delete;
1035 $dbh->rollback if $oldAutoCommit;
1040 my $error = $self->SUPER::delete;
1042 $dbh->rollback if $oldAutoCommit;
1046 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1051 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1053 Replaces the OLD_RECORD with this one in the database. If there is an error,
1054 returns the error, otherwise returns false.
1056 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1057 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1058 expected and rollback the entire transaction; it is not necessary to call
1059 check_invoicing_list first. Here's an example:
1061 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1069 warn "$me replace called\n"
1072 local $SIG{HUP} = 'IGNORE';
1073 local $SIG{INT} = 'IGNORE';
1074 local $SIG{QUIT} = 'IGNORE';
1075 local $SIG{TERM} = 'IGNORE';
1076 local $SIG{TSTP} = 'IGNORE';
1077 local $SIG{PIPE} = 'IGNORE';
1079 # We absolutely have to have an old vs. new record to make this work.
1080 if (!defined($old)) {
1081 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1084 my $curuser = $FS::CurrentUser::CurrentUser;
1085 if ( $self->payby eq 'COMP'
1086 && $self->payby ne $old->payby
1087 && ! $curuser->access_right('Complimentary customer')
1090 return "You are not permitted to create complimentary accounts.";
1093 local($ignore_expired_card) = 1
1094 if $old->payby =~ /^(CARD|DCRD)$/
1095 && $self->payby =~ /^(CARD|DCRD)$/
1096 && $old->payinfo eq $self->payinfo;
1098 my $oldAutoCommit = $FS::UID::AutoCommit;
1099 local $FS::UID::AutoCommit = 0;
1102 my $error = $self->SUPER::replace($old);
1105 $dbh->rollback if $oldAutoCommit;
1109 if ( @param ) { # INVOICING_LIST_ARYREF
1110 my $invoicing_list = shift @param;
1111 $error = $self->check_invoicing_list( $invoicing_list );
1113 $dbh->rollback if $oldAutoCommit;
1116 $self->invoicing_list( $invoicing_list );
1119 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1120 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1121 # card/check/lec info has changed, want to retry realtime_ invoice events
1122 my $error = $self->retry_realtime;
1124 $dbh->rollback if $oldAutoCommit;
1129 unless ( $import || $skip_fuzzyfiles ) {
1130 $error = $self->queue_fuzzyfiles_update;
1132 $dbh->rollback if $oldAutoCommit;
1133 return "updating fuzzy search cache: $error";
1137 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1142 =item queue_fuzzyfiles_update
1144 Used by insert & replace to update the fuzzy search cache
1148 sub queue_fuzzyfiles_update {
1151 local $SIG{HUP} = 'IGNORE';
1152 local $SIG{INT} = 'IGNORE';
1153 local $SIG{QUIT} = 'IGNORE';
1154 local $SIG{TERM} = 'IGNORE';
1155 local $SIG{TSTP} = 'IGNORE';
1156 local $SIG{PIPE} = 'IGNORE';
1158 my $oldAutoCommit = $FS::UID::AutoCommit;
1159 local $FS::UID::AutoCommit = 0;
1162 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1163 my $error = $queue->insert( map $self->getfield($_),
1164 qw(first last company)
1167 $dbh->rollback if $oldAutoCommit;
1168 return "queueing job (transaction rolled back): $error";
1171 if ( $self->ship_last ) {
1172 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1173 $error = $queue->insert( map $self->getfield("ship_$_"),
1174 qw(first last company)
1177 $dbh->rollback if $oldAutoCommit;
1178 return "queueing job (transaction rolled back): $error";
1182 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1189 Checks all fields to make sure this is a valid customer record. If there is
1190 an error, returns the error, otherwise returns false. Called by the insert
1191 and replace methods.
1198 warn "$me check BEFORE: \n". $self->_dump
1202 $self->ut_numbern('custnum')
1203 || $self->ut_number('agentnum')
1204 || $self->ut_textn('agent_custid')
1205 || $self->ut_number('refnum')
1206 || $self->ut_name('last')
1207 || $self->ut_name('first')
1208 || $self->ut_snumbern('birthdate')
1209 || $self->ut_snumbern('signupdate')
1210 || $self->ut_textn('company')
1211 || $self->ut_text('address1')
1212 || $self->ut_textn('address2')
1213 || $self->ut_text('city')
1214 || $self->ut_textn('county')
1215 || $self->ut_textn('state')
1216 || $self->ut_country('country')
1217 || $self->ut_anything('comments')
1218 || $self->ut_numbern('referral_custnum')
1220 #barf. need message catalogs. i18n. etc.
1221 $error .= "Please select an advertising source."
1222 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1223 return $error if $error;
1225 return "Unknown agent"
1226 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1228 return "Unknown refnum"
1229 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1231 return "Unknown referring custnum: ". $self->referral_custnum
1232 unless ! $self->referral_custnum
1233 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1235 if ( $self->ss eq '' ) {
1240 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1241 or return "Illegal social security number: ". $self->ss;
1242 $self->ss("$1-$2-$3");
1246 # bad idea to disable, causes billing to fail because of no tax rates later
1247 # unless ( $import ) {
1248 unless ( qsearch('cust_main_county', {
1249 'country' => $self->country,
1252 return "Unknown state/county/country: ".
1253 $self->state. "/". $self->county. "/". $self->country
1254 unless qsearch('cust_main_county',{
1255 'state' => $self->state,
1256 'county' => $self->county,
1257 'country' => $self->country,
1263 $self->ut_phonen('daytime', $self->country)
1264 || $self->ut_phonen('night', $self->country)
1265 || $self->ut_phonen('fax', $self->country)
1266 || $self->ut_zip('zip', $self->country)
1268 return $error if $error;
1271 last first company address1 address2 city county state zip
1272 country daytime night fax
1275 if ( defined $self->dbdef_table->column('ship_last') ) {
1276 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1278 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1282 $self->ut_name('ship_last')
1283 || $self->ut_name('ship_first')
1284 || $self->ut_textn('ship_company')
1285 || $self->ut_text('ship_address1')
1286 || $self->ut_textn('ship_address2')
1287 || $self->ut_text('ship_city')
1288 || $self->ut_textn('ship_county')
1289 || $self->ut_textn('ship_state')
1290 || $self->ut_country('ship_country')
1292 return $error if $error;
1294 #false laziness with above
1295 unless ( qsearchs('cust_main_county', {
1296 'country' => $self->ship_country,
1299 return "Unknown ship_state/ship_county/ship_country: ".
1300 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1301 unless qsearch('cust_main_county',{
1302 'state' => $self->ship_state,
1303 'county' => $self->ship_county,
1304 'country' => $self->ship_country,
1310 $self->ut_phonen('ship_daytime', $self->ship_country)
1311 || $self->ut_phonen('ship_night', $self->ship_country)
1312 || $self->ut_phonen('ship_fax', $self->ship_country)
1313 || $self->ut_zip('ship_zip', $self->ship_country)
1315 return $error if $error;
1317 } else { # ship_ info eq billing info, so don't store dup info in database
1318 $self->setfield("ship_$_", '')
1319 foreach qw( last first company address1 address2 city county state zip
1320 country daytime night fax );
1324 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1325 or return "Illegal payby: ". $self->payby;
1327 $error = $self->ut_numbern('paystart_month')
1328 || $self->ut_numbern('paystart_year')
1329 || $self->ut_numbern('payissue')
1331 return $error if $error;
1333 if ( $self->payip eq '' ) {
1336 $error = $self->ut_ip('payip');
1337 return $error if $error;
1340 # If it is encrypted and the private key is not availaible then we can't
1341 # check the credit card.
1343 my $check_payinfo = 1;
1345 if ($self->is_encrypted($self->payinfo)) {
1351 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1353 my $payinfo = $self->payinfo;
1354 $payinfo =~ s/\D//g;
1355 $payinfo =~ /^(\d{13,16})$/
1356 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1358 $self->payinfo($payinfo);
1360 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1362 return gettext('unknown_card_type')
1363 if cardtype($self->payinfo) eq "Unknown";
1365 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1367 return 'Banned credit card: banned on '.
1368 time2str('%a %h %o at %r', $ban->_date).
1369 ' by '. $ban->otaker.
1370 ' (ban# '. $ban->bannum. ')';
1373 if ( defined $self->dbdef_table->column('paycvv') ) {
1374 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1375 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1376 $self->paycvv =~ /^(\d{4})$/
1377 or return "CVV2 (CID) for American Express cards is four digits.";
1380 $self->paycvv =~ /^(\d{3})$/
1381 or return "CVV2 (CVC2/CID) is three digits.";
1389 my $cardtype = cardtype($payinfo);
1390 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1392 return "Start date or issue number is required for $cardtype cards"
1393 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1395 return "Start month must be between 1 and 12"
1396 if $self->paystart_month
1397 and $self->paystart_month < 1 || $self->paystart_month > 12;
1399 return "Start year must be 1990 or later"
1400 if $self->paystart_year
1401 and $self->paystart_year < 1990;
1403 return "Issue number must be beween 1 and 99"
1405 and $self->payissue < 1 || $self->payissue > 99;
1408 $self->paystart_month('');
1409 $self->paystart_year('');
1410 $self->payissue('');
1413 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1415 my $payinfo = $self->payinfo;
1416 $payinfo =~ s/[^\d\@]//g;
1417 if ( $conf->exists('echeck-nonus') ) {
1418 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1420 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1422 $payinfo = "$1\@$2";
1423 $self->payinfo($payinfo);
1424 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1426 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1428 return 'Banned ACH account: banned on '.
1429 time2str('%a %h %o at %r', $ban->_date).
1430 ' by '. $ban->otaker.
1431 ' (ban# '. $ban->bannum. ')';
1434 } elsif ( $self->payby eq 'LECB' ) {
1436 my $payinfo = $self->payinfo;
1437 $payinfo =~ s/\D//g;
1438 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1440 $self->payinfo($payinfo);
1441 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1443 } elsif ( $self->payby eq 'BILL' ) {
1445 $error = $self->ut_textn('payinfo');
1446 return "Illegal P.O. number: ". $self->payinfo if $error;
1447 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1449 } elsif ( $self->payby eq 'COMP' ) {
1451 my $curuser = $FS::CurrentUser::CurrentUser;
1452 if ( ! $self->custnum
1453 && ! $curuser->access_right('Complimentary customer')
1456 return "You are not permitted to create complimentary accounts."
1459 $error = $self->ut_textn('payinfo');
1460 return "Illegal comp account issuer: ". $self->payinfo if $error;
1461 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1463 } elsif ( $self->payby eq 'PREPAY' ) {
1465 my $payinfo = $self->payinfo;
1466 $payinfo =~ s/\W//g; #anything else would just confuse things
1467 $self->payinfo($payinfo);
1468 $error = $self->ut_alpha('payinfo');
1469 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1470 return "Unknown prepayment identifier"
1471 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1472 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1476 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1477 return "Expiration date required"
1478 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1482 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1483 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1484 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1485 ( $m, $y ) = ( $3, "20$2" );
1487 return "Illegal expiration date: ". $self->paydate;
1489 $self->paydate("$y-$m-01");
1490 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1491 return gettext('expired_card')
1493 && !$ignore_expired_card
1494 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1497 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1498 ( ! $conf->exists('require_cardname')
1499 || $self->payby !~ /^(CARD|DCRD)$/ )
1501 $self->payname( $self->first. " ". $self->getfield('last') );
1503 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1504 or return gettext('illegal_name'). " payname: ". $self->payname;
1508 foreach my $flag (qw( tax spool_cdr )) {
1509 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1513 $self->otaker(getotaker) unless $self->otaker;
1515 warn "$me check AFTER: \n". $self->_dump
1518 $self->SUPER::check;
1523 Returns all packages (see L<FS::cust_pkg>) for this customer.
1529 if ( $self->{'_pkgnum'} ) {
1530 values %{ $self->{'_pkgnum'}->cache };
1532 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1536 =item ncancelled_pkgs
1538 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1542 sub ncancelled_pkgs {
1544 if ( $self->{'_pkgnum'} ) {
1545 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1547 @{ [ # force list context
1548 qsearch( 'cust_pkg', {
1549 'custnum' => $self->custnum,
1552 qsearch( 'cust_pkg', {
1553 'custnum' => $self->custnum,
1560 =item suspended_pkgs
1562 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1566 sub suspended_pkgs {
1568 grep { $_->susp } $self->ncancelled_pkgs;
1571 =item unflagged_suspended_pkgs
1573 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1574 customer (thouse packages without the `manual_flag' set).
1578 sub unflagged_suspended_pkgs {
1580 return $self->suspended_pkgs
1581 unless dbdef->table('cust_pkg')->column('manual_flag');
1582 grep { ! $_->manual_flag } $self->suspended_pkgs;
1585 =item unsuspended_pkgs
1587 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1592 sub unsuspended_pkgs {
1594 grep { ! $_->susp } $self->ncancelled_pkgs;
1597 =item num_cancelled_pkgs
1599 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1604 sub num_cancelled_pkgs {
1606 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1610 my( $self, $sql ) = @_;
1611 my $sth = dbh->prepare(
1612 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1613 ) or die dbh->errstr;
1614 $sth->execute($self->custnum) or die $sth->errstr;
1615 $sth->fetchrow_arrayref->[0];
1620 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1621 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1622 on success or a list of errors.
1628 grep { $_->unsuspend } $self->suspended_pkgs;
1633 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1635 Returns a list: an empty list on success or a list of errors.
1641 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1644 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1646 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1647 PKGPARTs (see L<FS::part_pkg>).
1649 Returns a list: an empty list on success or a list of errors.
1653 sub suspend_if_pkgpart {
1655 my (@pkgparts, %opt);
1656 if (ref($_[0]) eq 'HASH'){
1657 @pkgparts = @{$_[0]{pkgparts}};
1662 grep { $_->suspend(%opt) }
1663 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1664 $self->unsuspended_pkgs;
1667 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1669 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1670 listed PKGPARTs (see L<FS::part_pkg>).
1672 Returns a list: an empty list on success or a list of errors.
1676 sub suspend_unless_pkgpart {
1678 my (@pkgparts, %opt);
1679 if (ref($_[0]) eq 'HASH'){
1680 @pkgparts = @{$_[0]{pkgparts}};
1685 grep { $_->suspend(%opt) }
1686 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1687 $self->unsuspended_pkgs;
1690 =item cancel [ OPTION => VALUE ... ]
1692 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1694 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1696 I<quiet> can be set true to supress email cancellation notices.
1698 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1700 I<ban> can be set true to ban this customer's credit card or ACH information,
1703 Always returns a list: an empty list on success or a list of errors.
1711 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1713 #should try decryption (we might have the private key)
1714 # and if not maybe queue a job for the server that does?
1715 return ( "Can't (yet) ban encrypted credit cards" )
1716 if $self->is_encrypted($self->payinfo);
1718 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1719 my $error = $ban->insert;
1720 return ( $error ) if $error;
1724 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1727 sub _banned_pay_hashref {
1738 'payby' => $payby2ban{$self->payby},
1739 'payinfo' => md5_base64($self->payinfo),
1746 Returns all notes (see L<FS::cust_main_note>) for this customer.
1753 qsearch( 'cust_main_note',
1754 { 'custnum' => $self->custnum },
1756 'ORDER BY _DATE DESC'
1762 Returns the agent (see L<FS::agent>) for this customer.
1768 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1773 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1774 conjunction with the collect method.
1776 Options are passed as name-value pairs.
1778 Currently available options are:
1780 resetup - if set true, re-charges setup fees.
1782 time - bills the customer as if it were that time. Specified as a UNIX
1783 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1784 L<Date::Parse> for conversion functions. For example:
1788 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1791 If there is an error, returns the error, otherwise returns false.
1796 my( $self, %options ) = @_;
1797 return '' if $self->payby eq 'COMP';
1798 warn "$me bill customer ". $self->custnum. "\n"
1801 my $time = $options{'time'} || time;
1806 local $SIG{HUP} = 'IGNORE';
1807 local $SIG{INT} = 'IGNORE';
1808 local $SIG{QUIT} = 'IGNORE';
1809 local $SIG{TERM} = 'IGNORE';
1810 local $SIG{TSTP} = 'IGNORE';
1811 local $SIG{PIPE} = 'IGNORE';
1813 my $oldAutoCommit = $FS::UID::AutoCommit;
1814 local $FS::UID::AutoCommit = 0;
1817 $self->select_for_update; #mutex
1819 #create a new invoice
1820 #(we'll remove it later if it doesn't actually need to be generated [contains
1821 # no line items] and we're inside a transaciton so nothing else will see it)
1822 my $cust_bill = new FS::cust_bill ( {
1823 'custnum' => $self->custnum,
1825 #'charged' => $charged,
1828 $error = $cust_bill->insert;
1830 $dbh->rollback if $oldAutoCommit;
1831 return "can't create invoice for customer #". $self->custnum. ": $error";
1833 my $invnum = $cust_bill->invnum;
1836 # find the packages which are due for billing, find out how much they are
1837 # & generate invoice database.
1840 my( $total_setup, $total_recur ) = ( 0, 0 );
1842 my @precommit_hooks = ();
1844 foreach my $cust_pkg (
1845 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1848 #NO!! next if $cust_pkg->cancel;
1849 next if $cust_pkg->getfield('cancel');
1851 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1853 #? to avoid use of uninitialized value errors... ?
1854 $cust_pkg->setfield('bill', '')
1855 unless defined($cust_pkg->bill);
1857 my $part_pkg = $cust_pkg->part_pkg;
1859 my %hash = $cust_pkg->hash;
1860 my $old_cust_pkg = new FS::cust_pkg \%hash;
1869 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1871 warn " bill setup\n" if $DEBUG > 1;
1873 $setup = eval { $cust_pkg->calc_setup( $time ) };
1875 $dbh->rollback if $oldAutoCommit;
1876 return "$@ running calc_setup for $cust_pkg\n";
1879 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1883 # bill recurring fee
1888 if ( $part_pkg->getfield('freq') ne '0' &&
1889 ! $cust_pkg->getfield('susp') &&
1890 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1893 warn " bill recur\n" if $DEBUG > 1;
1895 # XXX shared with $recur_prog
1896 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1898 #over two params! lets at least switch to a hashref for the rest...
1899 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
1901 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
1903 $dbh->rollback if $oldAutoCommit;
1904 return "$@ running calc_recur for $cust_pkg\n";
1907 #change this bit to use Date::Manip? CAREFUL with timezones (see
1908 # mailing list archive)
1909 my ($sec,$min,$hour,$mday,$mon,$year) =
1910 (localtime($sdate) )[0,1,2,3,4,5];
1912 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1913 # only for figuring next bill date, nothing else, so, reset $sdate again
1915 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1916 $cust_pkg->last_bill($sdate)
1917 if $cust_pkg->dbdef_table->column('last_bill');
1919 if ( $part_pkg->freq =~ /^\d+$/ ) {
1920 $mon += $part_pkg->freq;
1921 until ( $mon < 12 ) { $mon -= 12; $year++; }
1922 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1924 $mday += $weeks * 7;
1925 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1928 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
1932 $dbh->rollback if $oldAutoCommit;
1933 return "unparsable frequency: ". $part_pkg->freq;
1935 $cust_pkg->setfield('bill',
1936 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1939 warn "\$setup is undefined" unless defined($setup);
1940 warn "\$recur is undefined" unless defined($recur);
1941 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1944 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
1947 if ( $cust_pkg->modified ) {
1949 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
1952 $error=$cust_pkg->replace($old_cust_pkg);
1953 if ( $error ) { #just in case
1954 $dbh->rollback if $oldAutoCommit;
1955 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1958 $setup = sprintf( "%.2f", $setup );
1959 $recur = sprintf( "%.2f", $recur );
1960 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1961 $dbh->rollback if $oldAutoCommit;
1962 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1964 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1965 $dbh->rollback if $oldAutoCommit;
1966 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1969 if ( $setup != 0 || $recur != 0 ) {
1971 warn " charges (setup=$setup, recur=$recur); adding line items\n"
1973 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1974 'invnum' => $invnum,
1975 'pkgnum' => $cust_pkg->pkgnum,
1979 'edate' => $cust_pkg->bill,
1980 'details' => \@details,
1982 $error = $cust_bill_pkg->insert;
1984 $dbh->rollback if $oldAutoCommit;
1985 return "can't create invoice line item for invoice #$invnum: $error";
1987 $total_setup += $setup;
1988 $total_recur += $recur;
1994 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1997 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2000 my %taxhash = map { $_ => $self->get("$prefix$_") }
2001 qw( state county country );
2003 $taxhash{'taxclass'} = $part_pkg->taxclass;
2005 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2008 $taxhash{'taxclass'} = '';
2009 @taxes = qsearch( 'cust_main_county', \%taxhash );
2012 #one more try at a whole-country tax rate
2014 $taxhash{$_} = '' foreach qw( state county );
2015 @taxes = qsearch( 'cust_main_county', \%taxhash );
2018 # maybe eliminate this entirely, along with all the 0% records
2020 $dbh->rollback if $oldAutoCommit;
2022 "fatal: can't find tax rate for state/county/country/taxclass ".
2023 join('/', ( map $self->get("$prefix$_"),
2024 qw(state county country)
2026 $part_pkg->taxclass ). "\n";
2029 foreach my $tax ( @taxes ) {
2031 my $taxable_charged = 0;
2032 $taxable_charged += $setup
2033 unless $part_pkg->setuptax =~ /^Y$/i
2034 || $tax->setuptax =~ /^Y$/i;
2035 $taxable_charged += $recur
2036 unless $part_pkg->recurtax =~ /^Y$/i
2037 || $tax->recurtax =~ /^Y$/i;
2038 next unless $taxable_charged;
2040 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2041 #my ($mon,$year) = (localtime($sdate) )[4,5];
2042 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2044 my $freq = $part_pkg->freq || 1;
2045 if ( $freq !~ /(\d+)$/ ) {
2046 $dbh->rollback if $oldAutoCommit;
2047 return "daily/weekly package definitions not (yet?)".
2048 " compatible with monthly tax exemptions";
2050 my $taxable_per_month =
2051 sprintf("%.2f", $taxable_charged / $freq );
2053 #call the whole thing off if this customer has any old
2054 #exemption records...
2055 my @cust_tax_exempt =
2056 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2057 if ( @cust_tax_exempt ) {
2058 $dbh->rollback if $oldAutoCommit;
2060 'this customer still has old-style tax exemption records; '.
2061 'run bin/fs-migrate-cust_tax_exempt?';
2064 foreach my $which_month ( 1 .. $freq ) {
2066 #maintain the new exemption table now
2069 FROM cust_tax_exempt_pkg
2070 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2071 LEFT JOIN cust_bill USING ( invnum )
2077 my $sth = dbh->prepare($sql) or do {
2078 $dbh->rollback if $oldAutoCommit;
2079 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2087 $dbh->rollback if $oldAutoCommit;
2088 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2090 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2092 my $remaining_exemption =
2093 $tax->exempt_amount - $existing_exemption;
2094 if ( $remaining_exemption > 0 ) {
2095 my $addl = $remaining_exemption > $taxable_per_month
2096 ? $taxable_per_month
2097 : $remaining_exemption;
2098 $taxable_charged -= $addl;
2100 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2101 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2102 'taxnum' => $tax->taxnum,
2103 'year' => 1900+$year,
2105 'amount' => sprintf("%.2f", $addl ),
2107 $error = $cust_tax_exempt_pkg->insert;
2109 $dbh->rollback if $oldAutoCommit;
2110 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2112 } # if $remaining_exemption > 0
2116 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2117 until ( $mon < 13 ) { $mon -= 12; $year++; }
2119 } #foreach $which_month
2121 } #if $tax->exempt_amount
2123 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2125 #$tax += $taxable_charged * $cust_main_county->tax / 100
2126 $tax{ $tax->taxname || 'Tax' } +=
2127 $taxable_charged * $tax->tax / 100
2129 } #foreach my $tax ( @taxes )
2131 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2133 } #if $setup != 0 || $recur != 0
2135 } #if $cust_pkg->modified
2137 } #foreach my $cust_pkg
2139 unless ( $cust_bill->cust_bill_pkg ) {
2140 $cust_bill->delete; #don't create an invoice w/o line items
2141 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2145 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2147 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2148 my $tax = sprintf("%.2f", $tax{$taxname} );
2149 $charged = sprintf( "%.2f", $charged+$tax );
2151 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2152 'invnum' => $invnum,
2158 'itemdesc' => $taxname,
2160 $error = $cust_bill_pkg->insert;
2162 $dbh->rollback if $oldAutoCommit;
2163 return "can't create invoice line item for invoice #$invnum: $error";
2165 $total_setup += $tax;
2169 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2170 $error = $cust_bill->replace;
2172 $dbh->rollback if $oldAutoCommit;
2173 return "can't update charged for invoice #$invnum: $error";
2176 foreach my $hook ( @precommit_hooks ) {
2178 &{$hook}; #($self) ?
2181 $dbh->rollback if $oldAutoCommit;
2182 return "$@ running precommit hook $hook\n";
2186 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2190 =item collect OPTIONS
2192 (Attempt to) collect money for this customer's outstanding invoices (see
2193 L<FS::cust_bill>). Usually used after the bill method.
2195 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2196 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2197 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2199 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2200 and the invoice events web interface.
2202 If there is an error, returns the error, otherwise returns false.
2204 Options are passed as name-value pairs.
2206 Currently available options are:
2208 invoice_time - Use this time when deciding when to print invoices and
2209 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>
2210 for conversion functions.
2212 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2215 quiet - set true to surpress email card/ACH decline notices.
2217 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2220 payby - allows for one time override of normal customer billing method
2225 my( $self, %options ) = @_;
2226 my $invoice_time = $options{'invoice_time'} || time;
2229 local $SIG{HUP} = 'IGNORE';
2230 local $SIG{INT} = 'IGNORE';
2231 local $SIG{QUIT} = 'IGNORE';
2232 local $SIG{TERM} = 'IGNORE';
2233 local $SIG{TSTP} = 'IGNORE';
2234 local $SIG{PIPE} = 'IGNORE';
2236 my $oldAutoCommit = $FS::UID::AutoCommit;
2237 local $FS::UID::AutoCommit = 0;
2240 $self->select_for_update; #mutex
2242 my $balance = $self->balance;
2243 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2245 unless ( $balance > 0 ) { #redundant?????
2246 $dbh->rollback if $oldAutoCommit; #hmm
2250 if ( exists($options{'retry_card'}) ) {
2251 carp 'retry_card option passed to collect is deprecated; use retry';
2252 $options{'retry'} ||= $options{'retry_card'};
2254 if ( exists($options{'retry'}) && $options{'retry'} ) {
2255 my $error = $self->retry_realtime;
2257 $dbh->rollback if $oldAutoCommit;
2263 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2264 $extra_sql = " AND freq = '1m' ";
2266 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2269 foreach my $cust_bill ( $self->open_cust_bill ) {
2271 # don't try to charge for the same invoice if it's already in a batch
2272 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2274 last if $self->balance <= 0;
2276 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2279 foreach my $part_bill_event ( due_events ( $cust_bill,
2280 exists($options{'payby'})
2286 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2287 || $self->balance <= 0; # or if balance<=0
2290 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2291 warn " do_event " . $cust_bill . " ". (%options) . "\n"
2294 if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2295 # gah, even with transactions.
2296 $dbh->commit if $oldAutoCommit; #well.
2305 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2310 =item retry_realtime
2312 Schedules realtime / batch credit card / electronic check / LEC billing
2313 events for for retry. Useful if card information has changed or manual
2314 retry is desired. The 'collect' method must be called to actually retry
2317 Implementation details: For each of this customer's open invoices, changes
2318 the status of the first "done" (with statustext error) realtime processing
2323 sub retry_realtime {
2326 local $SIG{HUP} = 'IGNORE';
2327 local $SIG{INT} = 'IGNORE';
2328 local $SIG{QUIT} = 'IGNORE';
2329 local $SIG{TERM} = 'IGNORE';
2330 local $SIG{TSTP} = 'IGNORE';
2331 local $SIG{PIPE} = 'IGNORE';
2333 my $oldAutoCommit = $FS::UID::AutoCommit;
2334 local $FS::UID::AutoCommit = 0;
2337 foreach my $cust_bill (
2338 grep { $_->cust_bill_event }
2339 $self->open_cust_bill
2341 my @cust_bill_event =
2342 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2344 #$_->part_bill_event->plan eq 'realtime-card'
2345 $_->part_bill_event->eventcode =~
2346 /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2347 && $_->status eq 'done'
2350 $cust_bill->cust_bill_event;
2351 next unless @cust_bill_event;
2352 my $error = $cust_bill_event[0]->retry;
2354 $dbh->rollback if $oldAutoCommit;
2355 return "error scheduling invoice event for retry: $error";
2360 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2365 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2367 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2368 via a Business::OnlinePayment realtime gateway. See
2369 L<http://420.am/business-onlinepayment> for supported gateways.
2371 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2373 Available options are: I<description>, I<invnum>, I<quiet>
2375 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2376 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2377 if set, will override the value from the customer record.
2379 I<description> is a free-text field passed to the gateway. It defaults to
2380 "Internet services".
2382 If an I<invnum> is specified, this payment (if successful) is applied to the
2383 specified invoice. If you don't specify an I<invnum> you might want to
2384 call the B<apply_payments> method.
2386 I<quiet> can be set true to surpress email decline notices.
2388 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2393 my( $self, $method, $amount, %options ) = @_;
2395 warn "$me realtime_bop: $method $amount\n";
2396 warn " $_ => $options{$_}\n" foreach keys %options;
2399 $options{'description'} ||= 'Internet services';
2401 eval "use Business::OnlinePayment";
2404 my $payinfo = exists($options{'payinfo'})
2405 ? $options{'payinfo'}
2413 if ( $options{'invnum'} ) {
2414 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2415 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2417 map { $_->part_pkg->taxclass }
2419 map { $_->cust_pkg }
2420 $cust_bill->cust_bill_pkg;
2421 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2422 #different taxclasses
2423 $taxclass = $taxclasses[0];
2427 #look for an agent gateway override first
2429 if ( $method eq 'CC' ) {
2430 $cardtype = cardtype($payinfo);
2431 } elsif ( $method eq 'ECHECK' ) {
2434 $cardtype = $method;
2438 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2439 cardtype => $cardtype,
2440 taxclass => $taxclass, } )
2441 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2443 taxclass => $taxclass, } )
2444 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2445 cardtype => $cardtype,
2447 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2449 taxclass => '', } );
2451 my $payment_gateway = '';
2452 my( $processor, $login, $password, $action, @bop_options );
2453 if ( $override ) { #use a payment gateway override
2455 $payment_gateway = $override->payment_gateway;
2457 $processor = $payment_gateway->gateway_module;
2458 $login = $payment_gateway->gateway_username;
2459 $password = $payment_gateway->gateway_password;
2460 $action = $payment_gateway->gateway_action;
2461 @bop_options = $payment_gateway->options;
2463 } else { #use the standard settings from the config
2465 ( $processor, $login, $password, $action, @bop_options ) =
2466 $self->default_payment_gateway($method);
2474 my $address = exists($options{'address1'})
2475 ? $options{'address1'}
2477 my $address2 = exists($options{'address2'})
2478 ? $options{'address2'}
2480 $address .= ", ". $address2 if length($address2);
2482 my $o_payname = exists($options{'payname'})
2483 ? $options{'payname'}
2485 my($payname, $payfirst, $paylast);
2486 if ( $o_payname && $method ne 'ECHECK' ) {
2487 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2488 or return "Illegal payname $payname";
2489 ($payfirst, $paylast) = ($1, $2);
2491 $payfirst = $self->getfield('first');
2492 $paylast = $self->getfield('last');
2493 $payname = "$payfirst $paylast";
2496 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2497 if ( $conf->exists('emailinvoiceauto')
2498 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2499 push @invoicing_list, $self->all_emails;
2502 my $email = ($conf->exists('business-onlinepayment-email-override'))
2503 ? $conf->config('business-onlinepayment-email-override')
2504 : $invoicing_list[0];
2508 my $payip = exists($options{'payip'})
2511 $content{customer_ip} = $payip
2514 $content{invoice_number} = $options{'invnum'}
2515 if exists($options{'invnum'}) && length($options{'invnum'});
2517 if ( $method eq 'CC' ) {
2519 $content{card_number} = $payinfo;
2520 my $paydate = exists($options{'paydate'})
2521 ? $options{'paydate'}
2523 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2524 $content{expiration} = "$2/$1";
2526 my $paycvv = exists($options{'paycvv'})
2527 ? $options{'paycvv'}
2529 $content{cvv2} = $self->paycvv
2532 my $paystart_month = exists($options{'paystart_month'})
2533 ? $options{'paystart_month'}
2534 : $self->paystart_month;
2536 my $paystart_year = exists($options{'paystart_year'})
2537 ? $options{'paystart_year'}
2538 : $self->paystart_year;
2540 $content{card_start} = "$paystart_month/$paystart_year"
2541 if $paystart_month && $paystart_year;
2543 my $payissue = exists($options{'payissue'})
2544 ? $options{'payissue'}
2546 $content{issue_number} = $payissue if $payissue;
2548 $content{recurring_billing} = 'YES'
2549 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2551 'payinfo' => $payinfo,
2554 } elsif ( $method eq 'ECHECK' ) {
2555 ( $content{account_number}, $content{routing_code} ) =
2556 split('@', $payinfo);
2557 $content{bank_name} = $o_payname;
2558 $content{account_type} = 'CHECKING';
2559 $content{account_name} = $payname;
2560 $content{customer_org} = $self->company ? 'B' : 'I';
2561 $content{customer_ssn} = exists($options{'ss'})
2564 } elsif ( $method eq 'LEC' ) {
2565 $content{phone} = $payinfo;
2569 # run transaction(s)
2572 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2574 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2575 $transaction->content(
2578 'password' => $password,
2579 'action' => $action1,
2580 'description' => $options{'description'},
2581 'amount' => $amount,
2582 #'invoice_number' => $options{'invnum'},
2583 'customer_id' => $self->custnum,
2584 'last_name' => $paylast,
2585 'first_name' => $payfirst,
2587 'address' => $address,
2588 'city' => ( exists($options{'city'})
2591 'state' => ( exists($options{'state'})
2594 'zip' => ( exists($options{'zip'})
2597 'country' => ( exists($options{'country'})
2598 ? $options{'country'}
2600 'referer' => 'http://cleanwhisker.420.am/',
2602 'phone' => $self->daytime || $self->night,
2605 $transaction->submit();
2607 if ( $transaction->is_success() && $action2 ) {
2608 my $auth = $transaction->authorization;
2609 my $ordernum = $transaction->can('order_number')
2610 ? $transaction->order_number
2614 new Business::OnlinePayment( $processor, @bop_options );
2621 password => $password,
2622 order_number => $ordernum,
2624 authorization => $auth,
2625 description => $options{'description'},
2628 foreach my $field (qw( authorization_source_code returned_ACI
2629 transaction_identifier validation_code
2630 transaction_sequence_num local_transaction_date
2631 local_transaction_time AVS_result_code )) {
2632 $capture{$field} = $transaction->$field() if $transaction->can($field);
2635 $capture->content( %capture );
2639 unless ( $capture->is_success ) {
2640 my $e = "Authorization successful but capture failed, custnum #".
2641 $self->custnum. ': '. $capture->result_code.
2642 ": ". $capture->error_message;
2650 # remove paycvv after initial transaction
2653 #false laziness w/misc/process/payment.cgi - check both to make sure working
2655 if ( defined $self->dbdef_table->column('paycvv')
2656 && length($self->paycvv)
2657 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2659 my $error = $self->remove_cvv;
2661 warn "WARNING: error removing cvv: $error\n";
2669 if ( $transaction->is_success() ) {
2671 my %method2payby = (
2678 if ( $payment_gateway ) { # agent override
2679 $paybatch = $payment_gateway->gatewaynum. '-';
2682 $paybatch .= "$processor:". $transaction->authorization;
2684 $paybatch .= ':'. $transaction->order_number
2685 if $transaction->can('order_number')
2686 && length($transaction->order_number);
2688 my $cust_pay = new FS::cust_pay ( {
2689 'custnum' => $self->custnum,
2690 'invnum' => $options{'invnum'},
2693 'payby' => $method2payby{$method},
2694 'payinfo' => $payinfo,
2695 'paybatch' => $paybatch,
2697 my $error = $cust_pay->insert;
2699 $cust_pay->invnum(''); #try again with no specific invnum
2700 my $error2 = $cust_pay->insert;
2702 # gah, even with transactions.
2703 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2704 "error inserting payment ($processor): $error2".
2705 " (previously tried insert with invnum #$options{'invnum'}" .
2711 return ''; #no error
2715 my $perror = "$processor error: ". $transaction->error_message;
2717 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2718 && $conf->exists('emaildecline')
2719 && grep { $_ ne 'POST' } $self->invoicing_list
2720 && ! grep { $transaction->error_message =~ /$_/ }
2721 $conf->config('emaildecline-exclude')
2723 my @templ = $conf->config('declinetemplate');
2724 my $template = new Text::Template (
2726 SOURCE => [ map "$_\n", @templ ],
2727 ) or return "($perror) can't create template: $Text::Template::ERROR";
2728 $template->compile()
2729 or return "($perror) can't compile template: $Text::Template::ERROR";
2731 my $templ_hash = { error => $transaction->error_message };
2733 my $error = send_email(
2734 'from' => $conf->config('invoice_from'),
2735 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2736 'subject' => 'Your payment could not be processed',
2737 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2740 $perror .= " (also received error sending decline notification: $error)"
2750 =item default_payment_gateway
2754 sub default_payment_gateway {
2755 my( $self, $method ) = @_;
2757 die "Real-time processing not enabled\n"
2758 unless $conf->exists('business-onlinepayment');
2761 my $bop_config = 'business-onlinepayment';
2762 $bop_config .= '-ach'
2763 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2764 my ( $processor, $login, $password, $action, @bop_options ) =
2765 $conf->config($bop_config);
2766 $action ||= 'normal authorization';
2767 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2768 die "No real-time processor is enabled - ".
2769 "did you set the business-onlinepayment configuration value?\n"
2772 ( $processor, $login, $password, $action, @bop_options )
2777 Removes the I<paycvv> field from the database directly.
2779 If there is an error, returns the error, otherwise returns false.
2785 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2786 or return dbh->errstr;
2787 $sth->execute($self->custnum)
2788 or return $sth->errstr;
2793 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2795 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2796 via a Business::OnlinePayment realtime gateway. See
2797 L<http://420.am/business-onlinepayment> for supported gateways.
2799 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2801 Available options are: I<amount>, I<reason>, I<paynum>
2803 Most gateways require a reference to an original payment transaction to refund,
2804 so you probably need to specify a I<paynum>.
2806 I<amount> defaults to the original amount of the payment if not specified.
2808 I<reason> specifies a reason for the refund.
2810 Implementation note: If I<amount> is unspecified or equal to the amount of the
2811 orignal payment, first an attempt is made to "void" the transaction via
2812 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2813 the normal attempt is made to "refund" ("credit") the transaction via the
2814 gateway is attempted.
2816 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2817 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2818 #if set, will override the value from the customer record.
2820 #If an I<invnum> is specified, this payment (if successful) is applied to the
2821 #specified invoice. If you don't specify an I<invnum> you might want to
2822 #call the B<apply_payments> method.
2826 #some false laziness w/realtime_bop, not enough to make it worth merging
2827 #but some useful small subs should be pulled out
2828 sub realtime_refund_bop {
2829 my( $self, $method, %options ) = @_;
2831 warn "$me realtime_refund_bop: $method refund\n";
2832 warn " $_ => $options{$_}\n" foreach keys %options;
2835 eval "use Business::OnlinePayment";
2839 # look up the original payment and optionally a gateway for that payment
2843 my $amount = $options{'amount'};
2845 my( $processor, $login, $password, @bop_options ) ;
2846 my( $auth, $order_number ) = ( '', '', '' );
2848 if ( $options{'paynum'} ) {
2850 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
2851 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2852 or return "Unknown paynum $options{'paynum'}";
2853 $amount ||= $cust_pay->paid;
2855 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2856 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2857 $cust_pay->paybatch;
2858 my $gatewaynum = '';
2859 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2861 if ( $gatewaynum ) { #gateway for the payment to be refunded
2863 my $payment_gateway =
2864 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2865 die "payment gateway $gatewaynum not found"
2866 unless $payment_gateway;
2868 $processor = $payment_gateway->gateway_module;
2869 $login = $payment_gateway->gateway_username;
2870 $password = $payment_gateway->gateway_password;
2871 @bop_options = $payment_gateway->options;
2873 } else { #try the default gateway
2875 my( $conf_processor, $unused_action );
2876 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2877 $self->default_payment_gateway($method);
2879 return "processor of payment $options{'paynum'} $processor does not".
2880 " match default processor $conf_processor"
2881 unless $processor eq $conf_processor;
2886 } else { # didn't specify a paynum, so look for agent gateway overrides
2887 # like a normal transaction
2890 if ( $method eq 'CC' ) {
2891 $cardtype = cardtype($self->payinfo);
2892 } elsif ( $method eq 'ECHECK' ) {
2895 $cardtype = $method;
2898 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2899 cardtype => $cardtype,
2901 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2903 taxclass => '', } );
2905 if ( $override ) { #use a payment gateway override
2907 my $payment_gateway = $override->payment_gateway;
2909 $processor = $payment_gateway->gateway_module;
2910 $login = $payment_gateway->gateway_username;
2911 $password = $payment_gateway->gateway_password;
2912 #$action = $payment_gateway->gateway_action;
2913 @bop_options = $payment_gateway->options;
2915 } else { #use the standard settings from the config
2918 ( $processor, $login, $password, $unused_action, @bop_options ) =
2919 $self->default_payment_gateway($method);
2924 return "neither amount nor paynum specified" unless $amount;
2929 'password' => $password,
2930 'order_number' => $order_number,
2931 'amount' => $amount,
2932 'referer' => 'http://cleanwhisker.420.am/',
2934 $content{authorization} = $auth
2935 if length($auth); #echeck/ACH transactions have an order # but no auth
2936 #(at least with authorize.net)
2938 #first try void if applicable
2939 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2940 warn " attempting void\n" if $DEBUG > 1;
2941 my $void = new Business::OnlinePayment( $processor, @bop_options );
2942 $void->content( 'action' => 'void', %content );
2944 if ( $void->is_success ) {
2945 my $error = $cust_pay->void($options{'reason'});
2947 # gah, even with transactions.
2948 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2949 "error voiding payment: $error";
2953 warn " void successful\n" if $DEBUG > 1;
2958 warn " void unsuccessful, trying refund\n"
2962 my $address = $self->address1;
2963 $address .= ", ". $self->address2 if $self->address2;
2965 my($payname, $payfirst, $paylast);
2966 if ( $self->payname && $method ne 'ECHECK' ) {
2967 $payname = $self->payname;
2968 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2969 or return "Illegal payname $payname";
2970 ($payfirst, $paylast) = ($1, $2);
2972 $payfirst = $self->getfield('first');
2973 $paylast = $self->getfield('last');
2974 $payname = "$payfirst $paylast";
2977 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2978 if ( $conf->exists('emailinvoiceauto')
2979 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2980 push @invoicing_list, $self->all_emails;
2983 my $email = ($conf->exists('business-onlinepayment-email-override'))
2984 ? $conf->config('business-onlinepayment-email-override')
2985 : $invoicing_list[0];
2987 my $payip = exists($options{'payip'})
2990 $content{customer_ip} = $payip
2994 if ( $method eq 'CC' ) {
2997 $content{card_number} = $payinfo = $cust_pay->payinfo;
2998 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2999 #$content{expiration} = "$2/$1";
3001 $content{card_number} = $payinfo = $self->payinfo;
3002 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3003 $content{expiration} = "$2/$1";
3006 } elsif ( $method eq 'ECHECK' ) {
3007 ( $content{account_number}, $content{routing_code} ) =
3008 split('@', $payinfo = $self->payinfo);
3009 $content{bank_name} = $self->payname;
3010 $content{account_type} = 'CHECKING';
3011 $content{account_name} = $payname;
3012 $content{customer_org} = $self->company ? 'B' : 'I';
3013 $content{customer_ssn} = $self->ss;
3014 } elsif ( $method eq 'LEC' ) {
3015 $content{phone} = $payinfo = $self->payinfo;
3019 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3020 my %sub_content = $refund->content(
3021 'action' => 'credit',
3022 'customer_id' => $self->custnum,
3023 'last_name' => $paylast,
3024 'first_name' => $payfirst,
3026 'address' => $address,
3027 'city' => $self->city,
3028 'state' => $self->state,
3029 'zip' => $self->zip,
3030 'country' => $self->country,
3032 'phone' => $self->daytime || $self->night,
3035 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3039 return "$processor error: ". $refund->error_message
3040 unless $refund->is_success();
3042 my %method2payby = (
3048 my $paybatch = "$processor:". $refund->authorization;
3049 $paybatch .= ':'. $refund->order_number
3050 if $refund->can('order_number') && $refund->order_number;
3052 while ( $cust_pay && $cust_pay->unappled < $amount ) {
3053 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3054 last unless @cust_bill_pay;
3055 my $cust_bill_pay = pop @cust_bill_pay;
3056 my $error = $cust_bill_pay->delete;
3060 my $cust_refund = new FS::cust_refund ( {
3061 'custnum' => $self->custnum,
3062 'paynum' => $options{'paynum'},
3063 'refund' => $amount,
3065 'payby' => $method2payby{$method},
3066 'payinfo' => $payinfo,
3067 'paybatch' => $paybatch,
3068 'reason' => $options{'reason'} || 'card or ACH refund',
3070 my $error = $cust_refund->insert;
3072 $cust_refund->paynum(''); #try again with no specific paynum
3073 my $error2 = $cust_refund->insert;
3075 # gah, even with transactions.
3076 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3077 "error inserting refund ($processor): $error2".
3078 " (previously tried insert with paynum #$options{'paynum'}" .
3091 Returns the total owed for this customer on all invoices
3092 (see L<FS::cust_bill/owed>).
3098 $self->total_owed_date(2145859200); #12/31/2037
3101 =item total_owed_date TIME
3103 Returns the total owed for this customer on all invoices with date earlier than
3104 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3105 see L<Time::Local> and L<Date::Parse> for conversion functions.
3109 sub total_owed_date {
3113 foreach my $cust_bill (
3114 grep { $_->_date <= $time }
3115 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3117 $total_bill += $cust_bill->owed;
3119 sprintf( "%.2f", $total_bill );
3122 =item apply_credits OPTION => VALUE ...
3124 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3125 to outstanding invoice balances in chronological order (or reverse
3126 chronological order if the I<order> option is set to B<newest>) and returns the
3127 value of any remaining unapplied credits available for refund (see
3128 L<FS::cust_refund>).
3136 return 0 unless $self->total_credited;
3138 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3139 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3141 my @invoices = $self->open_cust_bill;
3142 @invoices = sort { $b->_date <=> $a->_date } @invoices
3143 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3146 foreach my $cust_bill ( @invoices ) {
3149 if ( !defined($credit) || $credit->credited == 0) {
3150 $credit = pop @credits or last;
3153 if ($cust_bill->owed >= $credit->credited) {
3154 $amount=$credit->credited;
3156 $amount=$cust_bill->owed;
3159 my $cust_credit_bill = new FS::cust_credit_bill ( {
3160 'crednum' => $credit->crednum,
3161 'invnum' => $cust_bill->invnum,
3162 'amount' => $amount,
3164 my $error = $cust_credit_bill->insert;
3165 die $error if $error;
3167 redo if ($cust_bill->owed > 0);
3171 return $self->total_credited;
3174 =item apply_payments
3176 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3177 to outstanding invoice balances in chronological order.
3179 #and returns the value of any remaining unapplied payments.
3183 sub apply_payments {
3188 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3189 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3191 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3192 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3196 foreach my $cust_bill ( @invoices ) {
3199 if ( !defined($payment) || $payment->unapplied == 0 ) {
3200 $payment = pop @payments or last;
3203 if ( $cust_bill->owed >= $payment->unapplied ) {
3204 $amount = $payment->unapplied;
3206 $amount = $cust_bill->owed;
3209 my $cust_bill_pay = new FS::cust_bill_pay ( {
3210 'paynum' => $payment->paynum,
3211 'invnum' => $cust_bill->invnum,
3212 'amount' => $amount,
3214 my $error = $cust_bill_pay->insert;
3215 die $error if $error;
3217 redo if ( $cust_bill->owed > 0);
3221 return $self->total_unapplied_payments;
3224 =item total_credited
3226 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3227 customer. See L<FS::cust_credit/credited>.
3231 sub total_credited {
3233 my $total_credit = 0;
3234 foreach my $cust_credit ( qsearch('cust_credit', {
3235 'custnum' => $self->custnum,
3237 $total_credit += $cust_credit->credited;
3239 sprintf( "%.2f", $total_credit );
3242 =item total_unapplied_payments
3244 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3245 See L<FS::cust_pay/unapplied>.
3249 sub total_unapplied_payments {
3251 my $total_unapplied = 0;
3252 foreach my $cust_pay ( qsearch('cust_pay', {
3253 'custnum' => $self->custnum,
3255 $total_unapplied += $cust_pay->unapplied;
3257 sprintf( "%.2f", $total_unapplied );
3262 Returns the balance for this customer (total_owed minus total_credited
3263 minus total_unapplied_payments).
3270 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
3274 =item balance_date TIME
3276 Returns the balance for this customer, only considering invoices with date
3277 earlier than TIME (total_owed_date minus total_credited minus
3278 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3279 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3288 $self->total_owed_date($time)
3289 - $self->total_credited
3290 - $self->total_unapplied_payments
3294 =item in_transit_payments
3296 Returns the total of requests for payments for this customer pending in
3297 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3301 sub in_transit_payments {
3303 my $in_transit_payments = 0;
3304 foreach my $pay_batch ( qsearch('pay_batch', {
3307 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3308 'batchnum' => $pay_batch->batchnum,
3309 'custnum' => $self->custnum,
3311 $in_transit_payments += $cust_pay_batch->amount;
3314 sprintf( "%.2f", $in_transit_payments );
3317 =item paydate_monthyear
3319 Returns a two-element list consisting of the month and year of this customer's
3320 paydate (credit card expiration date for CARD customers)
3324 sub paydate_monthyear {
3326 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3328 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3335 =item payinfo_masked
3337 < DEPRICATED > Use $self->paymask
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 my $all = $self->all_X($field);
3988 next unless scalar(@$all);
3991 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
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 as an exact, or, in some cases, a substring or fuzzy match (see the source code
4021 for the exact heuristics used).
4023 Any additional options are 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 #always do substring & fuzzy,
4174 #getting complains searches are not returning enough
4175 #unless ( @cust_main ) { #no exact match, trying substring/fuzzy
4177 #still some false laziness w/ search/cust_main.cgi
4182 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
4183 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
4186 if ( $first && $last ) {
4189 { 'first' => { op=>'ILIKE', value=>"%$first%" },
4190 'last' => { op=>'ILIKE', value=>"%$last%" },
4192 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
4193 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
4200 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
4201 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
4205 foreach my $hashref ( @hashrefs ) {
4207 push @cust_main, qsearch( {
4208 'table' => 'cust_main',
4209 'hashref' => { %$hashref,
4212 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
4221 " AND $agentnums_sql", #extra_sql #agent virtualization
4224 if ( $first && $last ) {
4225 push @cust_main, FS::cust_main->fuzzy_search(
4226 { 'last' => $last, #fuzzy hashref
4227 'first' => $first }, #
4231 foreach my $field ( 'last', 'company' ) {
4233 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
4238 #eliminate duplicates
4240 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
4248 =item check_and_rebuild_fuzzyfiles
4252 use vars qw(@fuzzyfields);
4253 @fuzzyfields = ( 'last', 'first', 'company' );
4255 sub check_and_rebuild_fuzzyfiles {
4256 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4257 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
4260 =item rebuild_fuzzyfiles
4264 sub rebuild_fuzzyfiles {
4266 use Fcntl qw(:flock);
4268 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4269 mkdir $dir, 0700 unless -d $dir;
4271 foreach my $fuzzy ( @fuzzyfields ) {
4273 open(LOCK,">>$dir/cust_main.$fuzzy")
4274 or die "can't open $dir/cust_main.$fuzzy: $!";
4276 or die "can't lock $dir/cust_main.$fuzzy: $!";
4278 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
4279 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
4281 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
4282 my $sth = dbh->prepare("SELECT $field FROM cust_main".
4283 " WHERE $field != '' AND $field IS NOT NULL");
4284 $sth->execute or die $sth->errstr;
4286 while ( my $row = $sth->fetchrow_arrayref ) {
4287 print CACHE $row->[0]. "\n";
4292 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
4294 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
4305 my( $self, $field ) = @_;
4306 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4307 open(CACHE,"<$dir/cust_main.$field")
4308 or die "can't open $dir/cust_main.$field: $!";
4309 my @array = map { chomp; $_; } <CACHE>;
4314 =item append_fuzzyfiles LASTNAME COMPANY
4318 sub append_fuzzyfiles {
4319 #my( $first, $last, $company ) = @_;
4321 &check_and_rebuild_fuzzyfiles;
4323 use Fcntl qw(:flock);
4325 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4327 foreach my $field (qw( first last company )) {
4332 open(CACHE,">>$dir/cust_main.$field")
4333 or die "can't open $dir/cust_main.$field: $!";
4334 flock(CACHE,LOCK_EX)
4335 or die "can't lock $dir/cust_main.$field: $!";
4337 print CACHE "$value\n";
4339 flock(CACHE,LOCK_UN)
4340 or die "can't unlock $dir/cust_main.$field: $!";
4355 #warn join('-',keys %$param);
4356 my $fh = $param->{filehandle};
4357 my $agentnum = $param->{agentnum};
4359 my $refnum = $param->{refnum};
4360 my $pkgpart = $param->{pkgpart};
4362 #my @fields = @{$param->{fields}};
4363 my $format = $param->{'format'};
4366 if ( $format eq 'simple' ) {
4367 @fields = qw( cust_pkg.setup dayphone first last
4368 address1 address2 city state zip comments );
4370 } elsif ( $format eq 'extended' ) {
4371 @fields = qw( agent_custid refnum
4372 last first address1 address2 city state zip country
4374 ship_last ship_first ship_address1 ship_address2
4375 ship_city ship_state ship_zip ship_country
4376 payinfo paycvv paydate
4379 svc_acct.username svc_acct._password
4383 die "unknown format $format";
4386 eval "use Text::CSV_XS;";
4389 my $csv = new Text::CSV_XS;
4396 local $SIG{HUP} = 'IGNORE';
4397 local $SIG{INT} = 'IGNORE';
4398 local $SIG{QUIT} = 'IGNORE';
4399 local $SIG{TERM} = 'IGNORE';
4400 local $SIG{TSTP} = 'IGNORE';
4401 local $SIG{PIPE} = 'IGNORE';
4403 my $oldAutoCommit = $FS::UID::AutoCommit;
4404 local $FS::UID::AutoCommit = 0;
4407 #while ( $columns = $csv->getline($fh) ) {
4409 while ( defined($line=<$fh>) ) {
4411 $csv->parse($line) or do {
4412 $dbh->rollback if $oldAutoCommit;
4413 return "can't parse: ". $csv->error_input();
4416 my @columns = $csv->fields();
4417 #warn join('-',@columns);
4420 agentnum => $agentnum,
4422 country => $conf->config('countrydefault') || 'US',
4423 payby => $payby, #default
4424 paydate => '12/2037', #default
4426 my $billtime = time;
4427 my %cust_pkg = ( pkgpart => $pkgpart );
4429 foreach my $field ( @fields ) {
4431 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|expire|cancel)$/ ) {
4433 #$cust_pkg{$1} = str2time( shift @$columns );
4434 if ( $1 eq 'pkgpart' ) {
4435 $cust_pkg{$1} = shift @columns;
4436 } elsif ( $1 eq 'setup' ) {
4437 $billtime = str2time(shift @columns);
4439 $cust_pkg{$1} = str2time( shift @columns );
4442 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
4444 $svc_acct{$1} = shift @columns;
4448 #refnum interception
4449 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
4451 my $referral = $columns[0];
4452 my %hash = ( 'referral' => $referral,
4453 'agentnum' => $agentnum,
4457 my $part_referral = qsearchs('part_referral', \%hash )
4458 || new FS::part_referral \%hash;
4460 unless ( $part_referral->refnum ) {
4461 my $error = $part_referral->insert;
4463 $dbh->rollback if $oldAutoCommit;
4464 return "can't auto-insert advertising source: $referral: $error";
4468 $columns[0] = $part_referral->refnum;
4471 #$cust_main{$field} = shift @$columns;
4472 $cust_main{$field} = shift @columns;
4476 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
4478 my $invoicing_list = $cust_main{'invoicing_list'}
4479 ? [ delete $cust_main{'invoicing_list'} ]
4482 my $cust_main = new FS::cust_main ( \%cust_main );
4485 tie my %hash, 'Tie::RefHash'; #this part is important
4487 if ( $cust_pkg{'pkgpart'} ) {
4488 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
4491 if ( $svc_acct{'username'} ) {
4492 my $part_pkg = $cust_pkg->part_pkg;
4493 unless ( $part_pkg ) {
4494 $dbh->rollback if $oldAutoCommit;
4495 return "unknown pkgnum ". $cust_pkg{'pkgpart'};
4497 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
4498 push @svc_acct, new FS::svc_acct ( \%svc_acct )
4501 $hash{$cust_pkg} = \@svc_acct;
4504 my $error = $cust_main->insert( \%hash, $invoicing_list );
4507 $dbh->rollback if $oldAutoCommit;
4508 return "can't insert customer for $line: $error";
4511 if ( $format eq 'simple' ) {
4513 #false laziness w/bill.cgi
4514 $error = $cust_main->bill( 'time' => $billtime );
4516 $dbh->rollback if $oldAutoCommit;
4517 return "can't bill customer for $line: $error";
4520 $cust_main->apply_payments;
4521 $cust_main->apply_credits;
4523 $error = $cust_main->collect();
4525 $dbh->rollback if $oldAutoCommit;
4526 return "can't collect customer for $line: $error";
4534 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4536 return "Empty file!" unless $imported;
4548 #warn join('-',keys %$param);
4549 my $fh = $param->{filehandle};
4550 my @fields = @{$param->{fields}};
4552 eval "use Text::CSV_XS;";
4555 my $csv = new Text::CSV_XS;
4562 local $SIG{HUP} = 'IGNORE';
4563 local $SIG{INT} = 'IGNORE';
4564 local $SIG{QUIT} = 'IGNORE';
4565 local $SIG{TERM} = 'IGNORE';
4566 local $SIG{TSTP} = 'IGNORE';
4567 local $SIG{PIPE} = 'IGNORE';
4569 my $oldAutoCommit = $FS::UID::AutoCommit;
4570 local $FS::UID::AutoCommit = 0;
4573 #while ( $columns = $csv->getline($fh) ) {
4575 while ( defined($line=<$fh>) ) {
4577 $csv->parse($line) or do {
4578 $dbh->rollback if $oldAutoCommit;
4579 return "can't parse: ". $csv->error_input();
4582 my @columns = $csv->fields();
4583 #warn join('-',@columns);
4586 foreach my $field ( @fields ) {
4587 $row{$field} = shift @columns;
4590 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4591 unless ( $cust_main ) {
4592 $dbh->rollback if $oldAutoCommit;
4593 return "unknown custnum $row{'custnum'}";
4596 if ( $row{'amount'} > 0 ) {
4597 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4599 $dbh->rollback if $oldAutoCommit;
4603 } elsif ( $row{'amount'} < 0 ) {
4604 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4607 $dbh->rollback if $oldAutoCommit;
4617 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4619 return "Empty file!" unless $imported;
4631 The delete method should possibly take an FS::cust_main object reference
4632 instead of a scalar customer number.
4634 Bill and collect options should probably be passed as references instead of a
4637 There should probably be a configuration file with a list of allowed credit
4640 No multiple currency support (probably a larger project than just this module).
4642 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4644 Birthdates rely on negative epoch values.
4648 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4649 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4650 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.