4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
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 File::Slurp qw( slurp );
22 use File::Temp qw( tempfile );
23 use String::Approx qw(amatch);
24 use Business::CreditCard 0.28;
27 use FS::UID qw( getotaker dbh driver_name );
28 use FS::Record qw( qsearchs qsearch dbdef );
29 use FS::Misc qw( generate_email send_email generate_ps do_print );
30 use FS::Msgcat qw(gettext);
35 use FS::cust_bill_pkg;
37 use FS::cust_pay_pending;
38 use FS::cust_pay_void;
41 use FS::part_referral;
42 use FS::cust_main_county;
44 use FS::cust_main_invoice;
45 use FS::cust_credit_bill;
46 use FS::cust_bill_pay;
47 use FS::prepay_credit;
50 use FS::part_bill_event qw(due_events);
51 use FS::cust_bill_event;
52 use FS::cust_tax_exempt;
53 use FS::cust_tax_exempt_pkg;
55 use FS::payment_gateway;
56 use FS::agent_payment_gateway;
58 use FS::payinfo_Mixin;
60 @ISA = qw( FS::Record FS::payinfo_Mixin );
62 @EXPORT_OK = qw( smart_search );
64 $realtime_bop_decline_quiet = 0;
66 # 1 is mostly method/subroutine entry and options
67 # 2 traces progress of some operations
68 # 3 is even more information including possibly sensitive data
70 $me = '[FS::cust_main]';
74 $ignore_expired_card = 0;
76 @encrypted_fields = ('payinfo', 'paycvv');
77 sub nohistory_fields { ('paycvv'); }
79 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
81 #ask FS::UID to run this stuff for us later
82 #$FS::UID::callback{'FS::cust_main'} = sub {
83 install_callback FS::UID sub {
85 #yes, need it for stuff below (prolly should be cached)
90 my ( $hashref, $cache ) = @_;
91 if ( exists $hashref->{'pkgnum'} ) {
92 #@{ $self->{'_pkgnum'} } = ();
93 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
94 $self->{'_pkgnum'} = $subcache;
95 #push @{ $self->{'_pkgnum'} },
96 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
102 FS::cust_main - Object methods for cust_main records
108 $record = new FS::cust_main \%hash;
109 $record = new FS::cust_main { 'column' => 'value' };
111 $error = $record->insert;
113 $error = $new_record->replace($old_record);
115 $error = $record->delete;
117 $error = $record->check;
119 @cust_pkg = $record->all_pkgs;
121 @cust_pkg = $record->ncancelled_pkgs;
123 @cust_pkg = $record->suspended_pkgs;
125 $error = $record->bill;
126 $error = $record->bill %options;
127 $error = $record->bill 'time' => $time;
129 $error = $record->collect;
130 $error = $record->collect %options;
131 $error = $record->collect 'invoice_time' => $time,
136 An FS::cust_main object represents a customer. FS::cust_main inherits from
137 FS::Record. The following fields are currently supported:
141 =item custnum - primary key (assigned automatically for new customers)
143 =item agentnum - agent (see L<FS::agent>)
145 =item refnum - Advertising source (see L<FS::part_referral>)
151 =item ss - social security number (optional)
153 =item company - (optional)
157 =item address2 - (optional)
161 =item county - (optional, see L<FS::cust_main_county>)
163 =item state - (see L<FS::cust_main_county>)
167 =item country - (see L<FS::cust_main_county>)
169 =item daytime - phone (optional)
171 =item night - phone (optional)
173 =item fax - phone (optional)
175 =item ship_first - name
177 =item ship_last - name
179 =item ship_company - (optional)
183 =item ship_address2 - (optional)
187 =item ship_county - (optional, see L<FS::cust_main_county>)
189 =item ship_state - (see L<FS::cust_main_county>)
193 =item ship_country - (see L<FS::cust_main_county>)
195 =item ship_daytime - phone (optional)
197 =item ship_night - phone (optional)
199 =item ship_fax - phone (optional)
201 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
203 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
205 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
209 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
211 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
213 =item paystart_month - start date month (maestro/solo cards only)
215 =item paystart_year - start date year (maestro/solo cards only)
217 =item payissue - issue number (maestro/solo cards only)
219 =item payname - name on card or billing name
221 =item payip - IP address from which payment information was received
223 =item tax - tax exempt, empty or `Y'
225 =item otaker - order taker (assigned automatically, see L<FS::UID>)
227 =item comments - comments (optional)
229 =item referral_custnum - referring customer number
231 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
233 =item dundate - a suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
243 Creates a new customer. To add the customer to the database, see L<"insert">.
245 Note that this stores the hash reference, not a distinct copy of the hash it
246 points to. You can ask the object for a copy with the I<hash> method.
250 sub table { 'cust_main'; }
252 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
254 Adds this customer to the database. If there is an error, returns the error,
255 otherwise returns false.
257 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
258 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
259 are inserted atomicly, or the transaction is rolled back. Passing an empty
260 hash reference is equivalent to not supplying this parameter. There should be
261 a better explanation of this, but until then, here's an example:
264 tie %hash, 'Tie::RefHash'; #this part is important
266 $cust_pkg => [ $svc_acct ],
269 $cust_main->insert( \%hash );
271 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
272 be set as the invoicing list (see L<"invoicing_list">). Errors return as
273 expected and rollback the entire transaction; it is not necessary to call
274 check_invoicing_list first. The invoicing_list is set after the records in the
275 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
276 invoicing_list destination to the newly-created svc_acct. Here's an example:
278 $cust_main->insert( {}, [ $email, 'POST' ] );
280 Currently available options are: I<depend_jobnum> and I<noexport>.
282 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
283 on the supplied jobnum (they will not run until the specific job completes).
284 This can be used to defer provisioning until some action completes (such
285 as running the customer's credit card successfully).
287 The I<noexport> option is deprecated. If I<noexport> is set true, no
288 provisioning jobs (exports) are scheduled. (You can schedule them later with
289 the B<reexport> method.)
295 my $cust_pkgs = @_ ? shift : {};
296 my $invoicing_list = @_ ? shift : '';
298 warn "$me insert called with options ".
299 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
302 local $SIG{HUP} = 'IGNORE';
303 local $SIG{INT} = 'IGNORE';
304 local $SIG{QUIT} = 'IGNORE';
305 local $SIG{TERM} = 'IGNORE';
306 local $SIG{TSTP} = 'IGNORE';
307 local $SIG{PIPE} = 'IGNORE';
309 my $oldAutoCommit = $FS::UID::AutoCommit;
310 local $FS::UID::AutoCommit = 0;
313 my $prepay_identifier = '';
314 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
316 if ( $self->payby eq 'PREPAY' ) {
318 $self->payby('BILL');
319 $prepay_identifier = $self->payinfo;
322 warn " looking up prepaid card $prepay_identifier\n"
325 my $error = $self->get_prepay( $prepay_identifier,
326 'amount_ref' => \$amount,
327 'seconds_ref' => \$seconds,
328 'upbytes_ref' => \$upbytes,
329 'downbytes_ref' => \$downbytes,
330 'totalbytes_ref' => \$totalbytes,
333 $dbh->rollback if $oldAutoCommit;
334 #return "error applying prepaid card (transaction rolled back): $error";
338 $payby = 'PREP' if $amount;
340 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
343 $self->payby('BILL');
344 $amount = $self->paid;
348 warn " inserting $self\n"
351 $self->signupdate(time) unless $self->signupdate;
353 my $error = $self->SUPER::insert;
355 $dbh->rollback if $oldAutoCommit;
356 #return "inserting cust_main record (transaction rolled back): $error";
360 warn " setting invoicing list\n"
363 if ( $invoicing_list ) {
364 $error = $self->check_invoicing_list( $invoicing_list );
366 $dbh->rollback if $oldAutoCommit;
367 #return "checking invoicing_list (transaction rolled back): $error";
370 $self->invoicing_list( $invoicing_list );
373 if ( $conf->config('cust_main-skeleton_tables')
374 && $conf->config('cust_main-skeleton_custnum') ) {
376 warn " inserting skeleton records\n"
379 my $error = $self->start_copy_skel;
381 $dbh->rollback if $oldAutoCommit;
387 warn " ordering packages\n"
390 $error = $self->order_pkgs( $cust_pkgs,
392 'seconds_ref' => \$seconds,
393 'upbytes_ref' => \$upbytes,
394 'downbytes_ref' => \$downbytes,
395 'totalbytes_ref' => \$totalbytes,
398 $dbh->rollback if $oldAutoCommit;
403 $dbh->rollback if $oldAutoCommit;
404 return "No svc_acct record to apply pre-paid time";
406 if ( $upbytes || $downbytes || $totalbytes ) {
407 $dbh->rollback if $oldAutoCommit;
408 return "No svc_acct record to apply pre-paid data";
412 warn " inserting initial $payby payment of $amount\n"
414 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
416 $dbh->rollback if $oldAutoCommit;
417 return "inserting payment (transaction rolled back): $error";
421 unless ( $import || $skip_fuzzyfiles ) {
422 warn " queueing fuzzyfiles update\n"
424 $error = $self->queue_fuzzyfiles_update;
426 $dbh->rollback if $oldAutoCommit;
427 return "updating fuzzy search cache: $error";
431 warn " insert complete; committing transaction\n"
434 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
439 sub start_copy_skel {
442 #'mg_user_preference' => {},
443 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
444 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
445 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
446 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
447 my @tables = eval($conf->config_binary('cust_main-skeleton_tables'));
450 _copy_skel( 'cust_main', #tablename
451 $conf->config('cust_main-skeleton_custnum'), #sourceid
452 $self->custnum, #destid
453 @tables, #child tables
457 #recursive subroutine, not a method
459 my( $table, $sourceid, $destid, %child_tables ) = @_;
462 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
463 ( $table, $primary_key ) = ( $1, $2 );
465 my $dbdef_table = dbdef->table($table);
466 $primary_key = $dbdef_table->primary_key
467 or return "$table has no primary key".
468 " (or do you need to run dbdef-create?)";
471 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
472 join (', ', keys %child_tables). "\n"
475 foreach my $child_table_def ( keys %child_tables ) {
479 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
480 ( $child_table, $child_pkey ) = ( $1, $2 );
482 $child_table = $child_table_def;
484 $child_pkey = dbdef->table($child_table)->primary_key;
485 # or return "$table has no primary key".
486 # " (or do you need to run dbdef-create?)\n";
490 if ( keys %{ $child_tables{$child_table_def} } ) {
492 return "$child_table has no primary key".
493 " (run dbdef-create or try specifying it?)\n"
496 #false laziness w/Record::insert and only works on Pg
497 #refactor the proper last-inserted-id stuff out of Record::insert if this
498 # ever gets use for anything besides a quick kludge for one customer
499 my $default = dbdef->table($child_table)->column($child_pkey)->default;
500 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
501 or return "can't parse $child_table.$child_pkey default value ".
502 " for sequence name: $default";
507 my @sel_columns = grep { $_ ne $primary_key }
508 dbdef->table($child_table)->columns;
509 my $sel_columns = join(', ', @sel_columns );
511 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
512 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
513 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
515 my $sel_st = "SELECT $sel_columns FROM $child_table".
516 " WHERE $primary_key = $sourceid";
519 my $sel_sth = dbh->prepare( $sel_st )
520 or return dbh->errstr;
522 $sel_sth->execute or return $sel_sth->errstr;
524 while ( my $row = $sel_sth->fetchrow_hashref ) {
526 warn " selected row: ".
527 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
531 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
532 my $ins_sth =dbh->prepare($statement)
533 or return dbh->errstr;
534 my @param = ( $destid, map $row->{$_}, @ins_columns );
535 warn " $statement: [ ". join(', ', @param). " ]\n"
537 $ins_sth->execute( @param )
538 or return $ins_sth->errstr;
540 #next unless keys %{ $child_tables{$child_table} };
541 next unless $sequence;
543 #another section of that laziness
544 my $seq_sql = "SELECT currval('$sequence')";
545 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
546 $seq_sth->execute or return $seq_sth->errstr;
547 my $insertid = $seq_sth->fetchrow_arrayref->[0];
549 # don't drink soap! recurse! recurse! okay!
551 _copy_skel( $child_table_def,
552 $row->{$child_pkey}, #sourceid
554 %{ $child_tables{$child_table_def} },
556 return $error if $error;
566 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
567 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
569 Like the insert method on an existing record, this method orders a package
570 and included services atomicaly. Pass a Tie::RefHash data structure to this
571 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
572 be a better explanation of this, but until then, here's an example:
575 tie %hash, 'Tie::RefHash'; #this part is important
577 $cust_pkg => [ $svc_acct ],
580 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
582 Services can be new, in which case they are inserted, or existing unaudited
583 services, in which case they are linked to the newly-created package.
585 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
586 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
588 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
589 on the supplied jobnum (they will not run until the specific job completes).
590 This can be used to defer provisioning until some action completes (such
591 as running the customer's credit card successfully).
593 The I<noexport> option is deprecated. If I<noexport> is set true, no
594 provisioning jobs (exports) are scheduled. (You can schedule them later with
595 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
596 on the cust_main object is not recommended, as existing services will also be
599 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
600 provided, the scalars (provided by references) will be incremented by the
601 values of the prepaid card.`
607 my $cust_pkgs = shift;
608 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
610 $seconds_ref ||= $options{'seconds_ref'};
612 my %svc_options = ();
613 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
614 if exists $options{'depend_jobnum'};
615 warn "$me order_pkgs called with options ".
616 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
619 local $SIG{HUP} = 'IGNORE';
620 local $SIG{INT} = 'IGNORE';
621 local $SIG{QUIT} = 'IGNORE';
622 local $SIG{TERM} = 'IGNORE';
623 local $SIG{TSTP} = 'IGNORE';
624 local $SIG{PIPE} = 'IGNORE';
626 my $oldAutoCommit = $FS::UID::AutoCommit;
627 local $FS::UID::AutoCommit = 0;
630 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
632 foreach my $cust_pkg ( keys %$cust_pkgs ) {
633 $cust_pkg->custnum( $self->custnum );
634 my $error = $cust_pkg->insert;
636 $dbh->rollback if $oldAutoCommit;
637 return "inserting cust_pkg (transaction rolled back): $error";
639 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
640 if ( $svc_something->svcnum ) {
641 my $old_cust_svc = $svc_something->cust_svc;
642 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
643 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
644 $error = $new_cust_svc->replace($old_cust_svc);
646 $svc_something->pkgnum( $cust_pkg->pkgnum );
647 if ( $svc_something->isa('FS::svc_acct') ) {
648 foreach ( grep { $options{$_.'_ref'} && ${ $options{$_.'_ref'} } }
649 qw( seconds upbytes downbytes totalbytes )
651 $svc_something->$_( $svc_something->$_() + ${$options{$_.'_ref'}} );
652 ${ $options{$_.'_ref'} } = 0;
655 $error = $svc_something->insert(%svc_options);
658 $dbh->rollback if $oldAutoCommit;
659 #return "inserting svc_ (transaction rolled back): $error";
665 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
669 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
671 Recharges this (existing) customer with the specified prepaid card (see
672 L<FS::prepay_credit>), specified either by I<identifier> or as an
673 FS::prepay_credit object. If there is an error, returns the error, otherwise
676 Optionally, five scalar references can be passed as well. They will have their
677 values filled in with the amount, number of seconds, and number of upload,
678 download, and total bytes applied by this prepaid card.
682 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
683 #the only place that uses these args
684 sub recharge_prepay {
685 my( $self, $prepay_credit, $amountref, $secondsref,
686 $upbytesref, $downbytesref, $totalbytesref ) = @_;
688 local $SIG{HUP} = 'IGNORE';
689 local $SIG{INT} = 'IGNORE';
690 local $SIG{QUIT} = 'IGNORE';
691 local $SIG{TERM} = 'IGNORE';
692 local $SIG{TSTP} = 'IGNORE';
693 local $SIG{PIPE} = 'IGNORE';
695 my $oldAutoCommit = $FS::UID::AutoCommit;
696 local $FS::UID::AutoCommit = 0;
699 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
701 my $error = $self->get_prepay( $prepay_credit,
702 'amount_ref' => \$amount,
703 'seconds_ref' => \$seconds,
704 'upbytes_ref' => \$upbytes,
705 'downbytes_ref' => \$downbytes,
706 'totalbytes_ref' => \$totalbytes,
708 || $self->increment_seconds($seconds)
709 || $self->increment_upbytes($upbytes)
710 || $self->increment_downbytes($downbytes)
711 || $self->increment_totalbytes($totalbytes)
712 || $self->insert_cust_pay_prepay( $amount,
714 ? $prepay_credit->identifier
719 $dbh->rollback if $oldAutoCommit;
723 if ( defined($amountref) ) { $$amountref = $amount; }
724 if ( defined($secondsref) ) { $$secondsref = $seconds; }
725 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
726 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
727 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
729 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
734 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
736 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
737 specified either by I<identifier> or as an FS::prepay_credit object.
739 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>. The scalars (provided by references) will be
740 incremented by the values of the prepaid card.
742 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
743 check or set this customer's I<agentnum>.
745 If there is an error, returns the error, otherwise returns false.
751 my( $self, $prepay_credit, %opt ) = @_;
753 local $SIG{HUP} = 'IGNORE';
754 local $SIG{INT} = 'IGNORE';
755 local $SIG{QUIT} = 'IGNORE';
756 local $SIG{TERM} = 'IGNORE';
757 local $SIG{TSTP} = 'IGNORE';
758 local $SIG{PIPE} = 'IGNORE';
760 my $oldAutoCommit = $FS::UID::AutoCommit;
761 local $FS::UID::AutoCommit = 0;
764 unless ( ref($prepay_credit) ) {
766 my $identifier = $prepay_credit;
768 $prepay_credit = qsearchs(
770 { 'identifier' => $prepay_credit },
775 unless ( $prepay_credit ) {
776 $dbh->rollback if $oldAutoCommit;
777 return "Invalid prepaid card: ". $identifier;
782 if ( $prepay_credit->agentnum ) {
783 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
784 $dbh->rollback if $oldAutoCommit;
785 return "prepaid card not valid for agent ". $self->agentnum;
787 $self->agentnum($prepay_credit->agentnum);
790 my $error = $prepay_credit->delete;
792 $dbh->rollback if $oldAutoCommit;
793 return "removing prepay_credit (transaction rolled back): $error";
796 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
797 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
799 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
804 =item increment_upbytes SECONDS
806 Updates this customer's single or primary account (see L<FS::svc_acct>) by
807 the specified number of upbytes. If there is an error, returns the error,
808 otherwise returns false.
812 sub increment_upbytes {
813 _increment_column( shift, 'upbytes', @_);
816 =item increment_downbytes SECONDS
818 Updates this customer's single or primary account (see L<FS::svc_acct>) by
819 the specified number of downbytes. If there is an error, returns the error,
820 otherwise returns false.
824 sub increment_downbytes {
825 _increment_column( shift, 'downbytes', @_);
828 =item increment_totalbytes SECONDS
830 Updates this customer's single or primary account (see L<FS::svc_acct>) by
831 the specified number of totalbytes. If there is an error, returns the error,
832 otherwise returns false.
836 sub increment_totalbytes {
837 _increment_column( shift, 'totalbytes', @_);
840 =item increment_seconds SECONDS
842 Updates this customer's single or primary account (see L<FS::svc_acct>) by
843 the specified number of seconds. If there is an error, returns the error,
844 otherwise returns false.
848 sub increment_seconds {
849 _increment_column( shift, 'seconds', @_);
852 =item _increment_column AMOUNT
854 Updates this customer's single or primary account (see L<FS::svc_acct>) by
855 the specified number of seconds or bytes. If there is an error, returns
856 the error, otherwise returns false.
860 sub _increment_column {
861 my( $self, $column, $amount ) = @_;
862 warn "$me increment_column called: $column, $amount\n"
865 return '' unless $amount;
867 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
868 $self->ncancelled_pkgs;
871 return 'No packages with primary or single services found'.
872 ' to apply pre-paid time';
873 } elsif ( scalar(@cust_pkg) > 1 ) {
874 #maybe have a way to specify the package/account?
875 return 'Multiple packages found to apply pre-paid time';
878 my $cust_pkg = $cust_pkg[0];
879 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
883 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
886 return 'No account found to apply pre-paid time';
887 } elsif ( scalar(@cust_svc) > 1 ) {
888 return 'Multiple accounts found to apply pre-paid time';
891 my $svc_acct = $cust_svc[0]->svc_x;
892 warn " found service svcnum ". $svc_acct->pkgnum.
893 ' ('. $svc_acct->email. ")\n"
896 $column = "increment_$column";
897 $svc_acct->$column($amount);
901 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
903 Inserts a prepayment in the specified amount for this customer. An optional
904 second argument can specify the prepayment identifier for tracking purposes.
905 If there is an error, returns the error, otherwise returns false.
909 sub insert_cust_pay_prepay {
910 shift->insert_cust_pay('PREP', @_);
913 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
915 Inserts a cash payment in the specified amount for this customer. An optional
916 second argument can specify the payment identifier for tracking purposes.
917 If there is an error, returns the error, otherwise returns false.
921 sub insert_cust_pay_cash {
922 shift->insert_cust_pay('CASH', @_);
925 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
927 Inserts a Western Union payment in the specified amount for this customer. An
928 optional second argument can specify the prepayment identifier for tracking
929 purposes. If there is an error, returns the error, otherwise returns false.
933 sub insert_cust_pay_west {
934 shift->insert_cust_pay('WEST', @_);
937 sub insert_cust_pay {
938 my( $self, $payby, $amount ) = splice(@_, 0, 3);
939 my $payinfo = scalar(@_) ? shift : '';
941 my $cust_pay = new FS::cust_pay {
942 'custnum' => $self->custnum,
943 'paid' => sprintf('%.2f', $amount),
944 #'_date' => #date the prepaid card was purchased???
946 'payinfo' => $payinfo,
954 This method is deprecated. See the I<depend_jobnum> option to the insert and
955 order_pkgs methods for a better way to defer provisioning.
957 Re-schedules all exports by calling the B<reexport> method of all associated
958 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
959 otherwise returns false.
966 carp "WARNING: FS::cust_main::reexport is deprectated; ".
967 "use the depend_jobnum option to insert or order_pkgs to delay export";
969 local $SIG{HUP} = 'IGNORE';
970 local $SIG{INT} = 'IGNORE';
971 local $SIG{QUIT} = 'IGNORE';
972 local $SIG{TERM} = 'IGNORE';
973 local $SIG{TSTP} = 'IGNORE';
974 local $SIG{PIPE} = 'IGNORE';
976 my $oldAutoCommit = $FS::UID::AutoCommit;
977 local $FS::UID::AutoCommit = 0;
980 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
981 my $error = $cust_pkg->reexport;
983 $dbh->rollback if $oldAutoCommit;
988 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
993 =item delete NEW_CUSTNUM
995 This deletes the customer. If there is an error, returns the error, otherwise
998 This will completely remove all traces of the customer record. This is not
999 what you want when a customer cancels service; for that, cancel all of the
1000 customer's packages (see L</cancel>).
1002 If the customer has any uncancelled packages, you need to pass a new (valid)
1003 customer number for those packages to be transferred to. Cancelled packages
1004 will be deleted. Did I mention that this is NOT what you want when a customer
1005 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
1007 You can't delete a customer with invoices (see L<FS::cust_bill>),
1008 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
1009 refunds (see L<FS::cust_refund>).
1016 local $SIG{HUP} = 'IGNORE';
1017 local $SIG{INT} = 'IGNORE';
1018 local $SIG{QUIT} = 'IGNORE';
1019 local $SIG{TERM} = 'IGNORE';
1020 local $SIG{TSTP} = 'IGNORE';
1021 local $SIG{PIPE} = 'IGNORE';
1023 my $oldAutoCommit = $FS::UID::AutoCommit;
1024 local $FS::UID::AutoCommit = 0;
1027 if ( $self->cust_bill ) {
1028 $dbh->rollback if $oldAutoCommit;
1029 return "Can't delete a customer with invoices";
1031 if ( $self->cust_credit ) {
1032 $dbh->rollback if $oldAutoCommit;
1033 return "Can't delete a customer with credits";
1035 if ( $self->cust_pay ) {
1036 $dbh->rollback if $oldAutoCommit;
1037 return "Can't delete a customer with payments";
1039 if ( $self->cust_refund ) {
1040 $dbh->rollback if $oldAutoCommit;
1041 return "Can't delete a customer with refunds";
1044 my @cust_pkg = $self->ncancelled_pkgs;
1046 my $new_custnum = shift;
1047 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1048 $dbh->rollback if $oldAutoCommit;
1049 return "Invalid new customer number: $new_custnum";
1051 foreach my $cust_pkg ( @cust_pkg ) {
1052 my %hash = $cust_pkg->hash;
1053 $hash{'custnum'} = $new_custnum;
1054 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1055 my $error = $new_cust_pkg->replace($cust_pkg,
1056 options => { $cust_pkg->options },
1059 $dbh->rollback if $oldAutoCommit;
1064 my @cancelled_cust_pkg = $self->all_pkgs;
1065 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1066 my $error = $cust_pkg->delete;
1068 $dbh->rollback if $oldAutoCommit;
1073 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1074 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1076 my $error = $cust_main_invoice->delete;
1078 $dbh->rollback if $oldAutoCommit;
1083 my $error = $self->SUPER::delete;
1085 $dbh->rollback if $oldAutoCommit;
1089 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1094 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1096 Replaces the OLD_RECORD with this one in the database. If there is an error,
1097 returns the error, otherwise returns false.
1099 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1100 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1101 expected and rollback the entire transaction; it is not necessary to call
1102 check_invoicing_list first. Here's an example:
1104 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1112 warn "$me replace called\n"
1115 local $SIG{HUP} = 'IGNORE';
1116 local $SIG{INT} = 'IGNORE';
1117 local $SIG{QUIT} = 'IGNORE';
1118 local $SIG{TERM} = 'IGNORE';
1119 local $SIG{TSTP} = 'IGNORE';
1120 local $SIG{PIPE} = 'IGNORE';
1122 # We absolutely have to have an old vs. new record to make this work.
1123 if (!defined($old)) {
1124 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1127 my $curuser = $FS::CurrentUser::CurrentUser;
1128 if ( $self->payby eq 'COMP'
1129 && $self->payby ne $old->payby
1130 && ! $curuser->access_right('Complimentary customer')
1133 return "You are not permitted to create complimentary accounts.";
1136 local($ignore_expired_card) = 1
1137 if $old->payby =~ /^(CARD|DCRD)$/
1138 && $self->payby =~ /^(CARD|DCRD)$/
1139 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1141 my $oldAutoCommit = $FS::UID::AutoCommit;
1142 local $FS::UID::AutoCommit = 0;
1145 my $error = $self->SUPER::replace($old);
1148 $dbh->rollback if $oldAutoCommit;
1152 if ( @param ) { # INVOICING_LIST_ARYREF
1153 my $invoicing_list = shift @param;
1154 $error = $self->check_invoicing_list( $invoicing_list );
1156 $dbh->rollback if $oldAutoCommit;
1159 $self->invoicing_list( $invoicing_list );
1162 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1163 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1164 # card/check/lec info has changed, want to retry realtime_ invoice events
1165 my $error = $self->retry_realtime;
1167 $dbh->rollback if $oldAutoCommit;
1172 unless ( $import || $skip_fuzzyfiles ) {
1173 $error = $self->queue_fuzzyfiles_update;
1175 $dbh->rollback if $oldAutoCommit;
1176 return "updating fuzzy search cache: $error";
1180 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1185 =item queue_fuzzyfiles_update
1187 Used by insert & replace to update the fuzzy search cache
1191 sub queue_fuzzyfiles_update {
1194 local $SIG{HUP} = 'IGNORE';
1195 local $SIG{INT} = 'IGNORE';
1196 local $SIG{QUIT} = 'IGNORE';
1197 local $SIG{TERM} = 'IGNORE';
1198 local $SIG{TSTP} = 'IGNORE';
1199 local $SIG{PIPE} = 'IGNORE';
1201 my $oldAutoCommit = $FS::UID::AutoCommit;
1202 local $FS::UID::AutoCommit = 0;
1205 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1206 my $error = $queue->insert( map $self->getfield($_),
1207 qw(first last company)
1210 $dbh->rollback if $oldAutoCommit;
1211 return "queueing job (transaction rolled back): $error";
1214 if ( $self->ship_last ) {
1215 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1216 $error = $queue->insert( map $self->getfield("ship_$_"),
1217 qw(first last company)
1220 $dbh->rollback if $oldAutoCommit;
1221 return "queueing job (transaction rolled back): $error";
1225 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1232 Checks all fields to make sure this is a valid customer record. If there is
1233 an error, returns the error, otherwise returns false. Called by the insert
1234 and replace methods.
1241 warn "$me check BEFORE: \n". $self->_dump
1245 $self->ut_numbern('custnum')
1246 || $self->ut_number('agentnum')
1247 || $self->ut_textn('agent_custid')
1248 || $self->ut_number('refnum')
1249 || $self->ut_textn('custbatch')
1250 || $self->ut_name('last')
1251 || $self->ut_name('first')
1252 || $self->ut_snumbern('birthdate')
1253 || $self->ut_snumbern('signupdate')
1254 || $self->ut_textn('company')
1255 || $self->ut_text('address1')
1256 || $self->ut_textn('address2')
1257 || $self->ut_text('city')
1258 || $self->ut_textn('county')
1259 || $self->ut_textn('state')
1260 || $self->ut_country('country')
1261 || $self->ut_anything('comments')
1262 || $self->ut_numbern('referral_custnum')
1263 || $self->ut_textn('stateid')
1264 || $self->ut_textn('stateid_state')
1266 #barf. need message catalogs. i18n. etc.
1267 $error .= "Please select an advertising source."
1268 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1269 return $error if $error;
1271 return "Unknown agent"
1272 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1274 return "Unknown refnum"
1275 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1277 return "Unknown referring custnum: ". $self->referral_custnum
1278 unless ! $self->referral_custnum
1279 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1281 if ( $self->ss eq '' ) {
1286 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1287 or return "Illegal social security number: ". $self->ss;
1288 $self->ss("$1-$2-$3");
1292 # bad idea to disable, causes billing to fail because of no tax rates later
1293 # unless ( $import ) {
1294 unless ( qsearch('cust_main_county', {
1295 'country' => $self->country,
1298 return "Unknown state/county/country: ".
1299 $self->state. "/". $self->county. "/". $self->country
1300 unless qsearch('cust_main_county',{
1301 'state' => $self->state,
1302 'county' => $self->county,
1303 'country' => $self->country,
1309 $self->ut_phonen('daytime', $self->country)
1310 || $self->ut_phonen('night', $self->country)
1311 || $self->ut_phonen('fax', $self->country)
1312 || $self->ut_zip('zip', $self->country)
1314 return $error if $error;
1316 if ( $conf->exists('cust_main-require_phone')
1317 && ! length($self->daytime) && ! length($self->night)
1320 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1322 : FS::Msgcat::_gettext('daytime');
1323 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1325 : FS::Msgcat::_gettext('night');
1327 return "$daytime_label or $night_label is required"
1331 if ( $self->has_ship_address
1332 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1333 $self->addr_fields )
1337 $self->ut_name('ship_last')
1338 || $self->ut_name('ship_first')
1339 || $self->ut_textn('ship_company')
1340 || $self->ut_text('ship_address1')
1341 || $self->ut_textn('ship_address2')
1342 || $self->ut_text('ship_city')
1343 || $self->ut_textn('ship_county')
1344 || $self->ut_textn('ship_state')
1345 || $self->ut_country('ship_country')
1347 return $error if $error;
1349 #false laziness with above
1350 unless ( qsearchs('cust_main_county', {
1351 'country' => $self->ship_country,
1354 return "Unknown ship_state/ship_county/ship_country: ".
1355 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1356 unless qsearch('cust_main_county',{
1357 'state' => $self->ship_state,
1358 'county' => $self->ship_county,
1359 'country' => $self->ship_country,
1365 $self->ut_phonen('ship_daytime', $self->ship_country)
1366 || $self->ut_phonen('ship_night', $self->ship_country)
1367 || $self->ut_phonen('ship_fax', $self->ship_country)
1368 || $self->ut_zip('ship_zip', $self->ship_country)
1370 return $error if $error;
1372 return "Unit # is required."
1373 if $self->ship_address2 =~ /^\s*$/
1374 && $conf->exists('cust_main-require_address2');
1376 } else { # ship_ info eq billing info, so don't store dup info in database
1378 $self->setfield("ship_$_", '')
1379 foreach $self->addr_fields;
1381 return "Unit # is required."
1382 if $self->address2 =~ /^\s*$/
1383 && $conf->exists('cust_main-require_address2');
1387 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1388 # or return "Illegal payby: ". $self->payby;
1390 FS::payby->can_payby($self->table, $self->payby)
1391 or return "Illegal payby: ". $self->payby;
1393 $error = $self->ut_numbern('paystart_month')
1394 || $self->ut_numbern('paystart_year')
1395 || $self->ut_numbern('payissue')
1396 || $self->ut_textn('paytype')
1398 return $error if $error;
1400 if ( $self->payip eq '' ) {
1403 $error = $self->ut_ip('payip');
1404 return $error if $error;
1407 # If it is encrypted and the private key is not availaible then we can't
1408 # check the credit card.
1410 my $check_payinfo = 1;
1412 if ($self->is_encrypted($self->payinfo)) {
1416 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1418 my $payinfo = $self->payinfo;
1419 $payinfo =~ s/\D//g;
1420 $payinfo =~ /^(\d{13,16})$/
1421 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1423 $self->payinfo($payinfo);
1425 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1427 return gettext('unknown_card_type')
1428 if cardtype($self->payinfo) eq "Unknown";
1430 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1432 return 'Banned credit card: banned on '.
1433 time2str('%a %h %o at %r', $ban->_date).
1434 ' by '. $ban->otaker.
1435 ' (ban# '. $ban->bannum. ')';
1438 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1439 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1440 $self->paycvv =~ /^(\d{4})$/
1441 or return "CVV2 (CID) for American Express cards is four digits.";
1444 $self->paycvv =~ /^(\d{3})$/
1445 or return "CVV2 (CVC2/CID) is three digits.";
1452 my $cardtype = cardtype($payinfo);
1453 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1455 return "Start date or issue number is required for $cardtype cards"
1456 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1458 return "Start month must be between 1 and 12"
1459 if $self->paystart_month
1460 and $self->paystart_month < 1 || $self->paystart_month > 12;
1462 return "Start year must be 1990 or later"
1463 if $self->paystart_year
1464 and $self->paystart_year < 1990;
1466 return "Issue number must be beween 1 and 99"
1468 and $self->payissue < 1 || $self->payissue > 99;
1471 $self->paystart_month('');
1472 $self->paystart_year('');
1473 $self->payissue('');
1476 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1478 my $payinfo = $self->payinfo;
1479 $payinfo =~ s/[^\d\@]//g;
1480 if ( $conf->exists('echeck-nonus') ) {
1481 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1482 $payinfo = "$1\@$2";
1484 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1485 $payinfo = "$1\@$2";
1487 $self->payinfo($payinfo);
1490 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1492 return 'Banned ACH account: banned on '.
1493 time2str('%a %h %o at %r', $ban->_date).
1494 ' by '. $ban->otaker.
1495 ' (ban# '. $ban->bannum. ')';
1498 } elsif ( $self->payby eq 'LECB' ) {
1500 my $payinfo = $self->payinfo;
1501 $payinfo =~ s/\D//g;
1502 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1504 $self->payinfo($payinfo);
1507 } elsif ( $self->payby eq 'BILL' ) {
1509 $error = $self->ut_textn('payinfo');
1510 return "Illegal P.O. number: ". $self->payinfo if $error;
1513 } elsif ( $self->payby eq 'COMP' ) {
1515 my $curuser = $FS::CurrentUser::CurrentUser;
1516 if ( ! $self->custnum
1517 && ! $curuser->access_right('Complimentary customer')
1520 return "You are not permitted to create complimentary accounts."
1523 $error = $self->ut_textn('payinfo');
1524 return "Illegal comp account issuer: ". $self->payinfo if $error;
1527 } elsif ( $self->payby eq 'PREPAY' ) {
1529 my $payinfo = $self->payinfo;
1530 $payinfo =~ s/\W//g; #anything else would just confuse things
1531 $self->payinfo($payinfo);
1532 $error = $self->ut_alpha('payinfo');
1533 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1534 return "Unknown prepayment identifier"
1535 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1540 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1541 return "Expiration date required"
1542 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1546 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1547 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1548 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1549 ( $m, $y ) = ( $3, "20$2" );
1551 return "Illegal expiration date: ". $self->paydate;
1553 $self->paydate("$y-$m-01");
1554 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1555 return gettext('expired_card')
1557 && !$ignore_expired_card
1558 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1561 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1562 ( ! $conf->exists('require_cardname')
1563 || $self->payby !~ /^(CARD|DCRD)$/ )
1565 $self->payname( $self->first. " ". $self->getfield('last') );
1567 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1568 or return gettext('illegal_name'). " payname: ". $self->payname;
1572 foreach my $flag (qw( tax spool_cdr archived )) {
1573 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1577 $self->otaker(getotaker) unless $self->otaker;
1579 warn "$me check AFTER: \n". $self->_dump
1582 $self->SUPER::check;
1587 Returns a list of fields which have ship_ duplicates.
1592 qw( last first company
1593 address1 address2 city county state zip country
1598 =item has_ship_address
1600 Returns true if this customer record has a separate shipping address.
1604 sub has_ship_address {
1606 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1611 Returns all packages (see L<FS::cust_pkg>) for this customer.
1618 return $self->num_pkgs unless wantarray;
1621 if ( $self->{'_pkgnum'} ) {
1622 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1624 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1627 sort sort_packages @cust_pkg;
1630 =item ncancelled_pkgs
1632 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1636 sub ncancelled_pkgs {
1639 return $self->num_ncancelled_pkgs unless wantarray;
1642 if ( $self->{'_pkgnum'} ) {
1644 @cust_pkg = grep { ! $_->getfield('cancel') }
1645 values %{ $self->{'_pkgnum'}->cache };
1650 qsearch( 'cust_pkg', {
1651 'custnum' => $self->custnum,
1655 qsearch( 'cust_pkg', {
1656 'custnum' => $self->custnum,
1661 sort sort_packages @cust_pkg;
1665 # This should be generalized to use config options to determine order.
1668 if ( $a->get('cancel') xor $b->get('cancel') ) {
1669 return -1 if $b->get('cancel');
1670 return 1 if $a->get('cancel');
1671 #shouldn't get here...
1674 my @a_cust_svc = $a->cust_svc;
1675 my @b_cust_svc = $b->cust_svc;
1676 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
1677 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
1678 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
1679 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
1684 =item suspended_pkgs
1686 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1690 sub suspended_pkgs {
1692 grep { $_->susp } $self->ncancelled_pkgs;
1695 =item unflagged_suspended_pkgs
1697 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1698 customer (thouse packages without the `manual_flag' set).
1702 sub unflagged_suspended_pkgs {
1704 return $self->suspended_pkgs
1705 unless dbdef->table('cust_pkg')->column('manual_flag');
1706 grep { ! $_->manual_flag } $self->suspended_pkgs;
1709 =item unsuspended_pkgs
1711 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1716 sub unsuspended_pkgs {
1718 grep { ! $_->susp } $self->ncancelled_pkgs;
1721 =item num_cancelled_pkgs
1723 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1728 sub num_cancelled_pkgs {
1729 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1732 sub num_ncancelled_pkgs {
1733 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1737 my( $self ) = shift;
1738 my $sql = scalar(@_) ? shift : '';
1739 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1740 my $sth = dbh->prepare(
1741 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1742 ) or die dbh->errstr;
1743 $sth->execute($self->custnum) or die $sth->errstr;
1744 $sth->fetchrow_arrayref->[0];
1749 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1750 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1751 on success or a list of errors.
1757 grep { $_->unsuspend } $self->suspended_pkgs;
1762 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1764 Returns a list: an empty list on success or a list of errors.
1770 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1773 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1775 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1776 PKGPARTs (see L<FS::part_pkg>).
1778 Returns a list: an empty list on success or a list of errors.
1782 sub suspend_if_pkgpart {
1784 my (@pkgparts, %opt);
1785 if (ref($_[0]) eq 'HASH'){
1786 @pkgparts = @{$_[0]{pkgparts}};
1791 grep { $_->suspend(%opt) }
1792 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1793 $self->unsuspended_pkgs;
1796 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1798 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1799 listed PKGPARTs (see L<FS::part_pkg>).
1801 Returns a list: an empty list on success or a list of errors.
1805 sub suspend_unless_pkgpart {
1807 my (@pkgparts, %opt);
1808 if (ref($_[0]) eq 'HASH'){
1809 @pkgparts = @{$_[0]{pkgparts}};
1814 grep { $_->suspend(%opt) }
1815 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1816 $self->unsuspended_pkgs;
1819 =item cancel [ OPTION => VALUE ... ]
1821 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1823 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1825 I<quiet> can be set true to supress email cancellation notices.
1827 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1829 I<ban> can be set true to ban this customer's credit card or ACH information,
1832 Always returns a list: an empty list on success or a list of errors.
1840 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1842 #should try decryption (we might have the private key)
1843 # and if not maybe queue a job for the server that does?
1844 return ( "Can't (yet) ban encrypted credit cards" )
1845 if $self->is_encrypted($self->payinfo);
1847 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1848 my $error = $ban->insert;
1849 return ( $error ) if $error;
1853 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1856 sub _banned_pay_hashref {
1867 'payby' => $payby2ban{$self->payby},
1868 'payinfo' => md5_base64($self->payinfo),
1869 #don't ever *search* on reason! #'reason' =>
1875 Returns all notes (see L<FS::cust_main_note>) for this customer.
1882 qsearch( 'cust_main_note',
1883 { 'custnum' => $self->custnum },
1885 'ORDER BY _DATE DESC'
1891 Returns the agent (see L<FS::agent>) for this customer.
1897 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1900 =item bill_and_collect
1902 Cancels and suspends any packages due, generates bills, applies payments and
1905 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1907 Options are passed as name-value pairs. Currently available options are:
1913 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
1917 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1921 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
1925 If set true, re-charges setup fees.
1929 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1935 sub bill_and_collect {
1936 my( $self, %options ) = @_;
1938 #$options{actual_time} not $options{time} because freeside-daily -d is for
1939 #pre-printing invoices
1940 $self->cancel_expired_pkgs( $options{actual_time} );
1941 $self->suspend_adjourned_pkgs( $options{actual_time} );
1943 my $error = $self->bill( %options );
1944 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
1946 $self->apply_payments_and_credits;
1948 unless ( $conf->exists('cancelled_cust-noevents')
1949 && ! $self->num_ncancelled_pkgs
1952 $error = $self->collect( %options );
1953 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
1959 sub cancel_expired_pkgs {
1960 my ( $self, $time ) = @_;
1962 my @cancel_pkgs = grep { $_->expire && $_->expire <= $time }
1963 $self->ncancelled_pkgs;
1965 foreach my $cust_pkg ( @cancel_pkgs ) {
1966 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
1967 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
1968 'reason_otaker' => $cpr->otaker
1972 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1973 " for custnum ". $self->custnum. ": $error"
1979 sub suspend_adjourned_pkgs {
1980 my ( $self, $time ) = @_;
1984 && ( ( $_->part_pkg->is_prepaid
1989 && $_->adjourn <= $time
1993 $self->ncancelled_pkgs;
1995 foreach my $cust_pkg ( @susp_pkgs ) {
1996 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
1997 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
1998 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
1999 'reason_otaker' => $cpr->otaker
2004 warn "Error suspending package ". $cust_pkg->pkgnum.
2005 " for custnum ". $self->custnum. ": $error"
2013 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2014 conjunction with the collect method.
2016 If there is an error, returns the error, otherwise returns false.
2018 Options are passed as name-value pairs. Currently available options are:
2022 =item resetup - if set true, re-charges setup fees.
2024 =item time - bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
2028 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2030 =item invoice_time - used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
2037 my( $self, %options ) = @_;
2038 return '' if $self->payby eq 'COMP';
2039 warn "$me bill customer ". $self->custnum. "\n"
2042 my $time = $options{'time'} || time;
2047 local $SIG{HUP} = 'IGNORE';
2048 local $SIG{INT} = 'IGNORE';
2049 local $SIG{QUIT} = 'IGNORE';
2050 local $SIG{TERM} = 'IGNORE';
2051 local $SIG{TSTP} = 'IGNORE';
2052 local $SIG{PIPE} = 'IGNORE';
2054 my $oldAutoCommit = $FS::UID::AutoCommit;
2055 local $FS::UID::AutoCommit = 0;
2058 $self->select_for_update; #mutex
2060 #create a new invoice
2061 #(we'll remove it later if it doesn't actually need to be generated [contains
2062 # no line items] and we're inside a transaciton so nothing else will see it)
2063 my $cust_bill = new FS::cust_bill ( {
2064 'custnum' => $self->custnum,
2065 '_date' => ( $options{'invoice_time'} || $time ),
2066 #'charged' => $charged,
2069 $error = $cust_bill->insert;
2071 $dbh->rollback if $oldAutoCommit;
2072 return "can't create invoice for customer #". $self->custnum. ": $error";
2074 my $invnum = $cust_bill->invnum;
2077 # find the packages which are due for billing, find out how much they are
2078 # & generate invoice database.
2081 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2083 my @precommit_hooks = ();
2085 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2086 foreach my $cust_pkg (@cust_pkgs) {
2088 #NO!! next if $cust_pkg->cancel;
2089 next if $cust_pkg->getfield('cancel');
2091 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2093 #? to avoid use of uninitialized value errors... ?
2094 $cust_pkg->setfield('bill', '')
2095 unless defined($cust_pkg->bill);
2097 my $part_pkg = $cust_pkg->part_pkg;
2099 my %hash = $cust_pkg->hash;
2100 my $old_cust_pkg = new FS::cust_pkg \%hash;
2110 if ( ! $cust_pkg->setup &&
2112 ( $conf->exists('disable_setup_suspended_pkgs') &&
2113 ! $cust_pkg->getfield('susp')
2114 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2116 || $options{'resetup'}
2119 warn " bill setup\n" if $DEBUG > 1;
2121 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2123 $dbh->rollback if $oldAutoCommit;
2124 return "$@ running calc_setup for $cust_pkg\n";
2127 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2129 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
2133 # bill recurring fee
2136 #XXX unit stuff here too
2140 if ( $part_pkg->getfield('freq') ne '0' &&
2141 ! $cust_pkg->getfield('susp') &&
2142 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2145 # XXX should this be a package event? probably. events are called
2146 # at collection time at the moment, though...
2147 if ( $part_pkg->can('reset_usage') ) {
2148 warn " resetting usage counters" if $DEBUG > 1;
2149 $part_pkg->reset_usage($cust_pkg);
2152 warn " bill recur\n" if $DEBUG > 1;
2154 # XXX shared with $recur_prog
2155 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2157 #over two params! lets at least switch to a hashref for the rest...
2158 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
2160 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2162 $dbh->rollback if $oldAutoCommit;
2163 return "$@ running calc_recur for $cust_pkg\n";
2166 #change this bit to use Date::Manip? CAREFUL with timezones (see
2167 # mailing list archive)
2168 my ($sec,$min,$hour,$mday,$mon,$year) =
2169 (localtime($sdate) )[0,1,2,3,4,5];
2171 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2172 # only for figuring next bill date, nothing else, so, reset $sdate again
2174 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2175 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2176 $cust_pkg->last_bill($sdate);
2178 if ( $part_pkg->freq =~ /^\d+$/ ) {
2179 $mon += $part_pkg->freq;
2180 until ( $mon < 12 ) { $mon -= 12; $year++; }
2181 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2183 $mday += $weeks * 7;
2184 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2187 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2191 $dbh->rollback if $oldAutoCommit;
2192 return "unparsable frequency: ". $part_pkg->freq;
2194 $cust_pkg->setfield('bill',
2195 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2198 warn "\$setup is undefined" unless defined($setup);
2199 warn "\$recur is undefined" unless defined($recur);
2200 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2203 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2206 if ( $cust_pkg->modified ) { # hmmm.. and if the options are modified?
2208 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2211 $error=$cust_pkg->replace($old_cust_pkg,
2212 options => { $cust_pkg->options },
2214 if ( $error ) { #just in case
2215 $dbh->rollback if $oldAutoCommit;
2216 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2219 $setup = sprintf( "%.2f", $setup );
2220 $recur = sprintf( "%.2f", $recur );
2221 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2222 $dbh->rollback if $oldAutoCommit;
2223 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2225 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2226 $dbh->rollback if $oldAutoCommit;
2227 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2230 if ( $setup != 0 || $recur != 0 ) {
2232 # Only create a postal charge if:
2233 # - this package has a recurring fee OR postal charges are enabled for non-recurring fees
2234 # - AND there isn't already a postal charge for this invoice.
2235 if ( (!$postal_charge) &&
2236 ( !$conf->exists('postal_invoice-recurring_only') ||
2239 $postal_charge = 1; # try only once
2240 my $postal_pkg = $self->charge_postal_fee();
2241 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2242 $dbh->rollback if $oldAutoCommit;
2243 return "can't charge postal invoice fee for customer ".
2244 $self->custnum. ": $postal_pkg";
2246 if ( $postal_pkg ) {
2247 push @cust_pkgs, $postal_pkg;
2251 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2254 push @details, map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2256 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2257 'invnum' => $invnum,
2258 'pkgnum' => $cust_pkg->pkgnum,
2260 'unitsetup' => $unitsetup,
2262 'unitrecur' => $unitrecur,
2263 'quantity' => $cust_pkg->quantity,
2264 'details' => \@details,
2267 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
2268 $cust_bill_pkg->sdate( $hash{last_bill} );
2269 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2270 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
2271 $cust_bill_pkg->sdate( $sdate );
2272 $cust_bill_pkg->edate( $cust_pkg->bill );
2275 $error = $cust_bill_pkg->insert;
2277 $dbh->rollback if $oldAutoCommit;
2278 return "can't create invoice line item for invoice #$invnum: $error";
2280 $total_setup += $setup;
2281 $total_recur += $recur;
2287 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2290 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2293 my %taxhash = map { $_ => $self->get("$prefix$_") }
2294 qw( state county country );
2296 $taxhash{'taxclass'} = $part_pkg->taxclass;
2298 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2301 $taxhash{'taxclass'} = '';
2302 @taxes = qsearch( 'cust_main_county', \%taxhash );
2305 #one more try at a whole-country tax rate
2307 $taxhash{$_} = '' foreach qw( state county );
2308 @taxes = qsearch( 'cust_main_county', \%taxhash );
2311 # maybe eliminate this entirely, along with all the 0% records
2313 $dbh->rollback if $oldAutoCommit;
2315 "fatal: can't find tax rate for state/county/country/taxclass ".
2316 join('/', ( map $self->get("$prefix$_"),
2317 qw(state county country)
2319 $part_pkg->taxclass ). "\n";
2322 foreach my $tax ( @taxes ) {
2324 my $taxable_charged = 0;
2325 $taxable_charged += $setup
2326 unless $part_pkg->setuptax =~ /^Y$/i
2327 || $tax->setuptax =~ /^Y$/i;
2328 $taxable_charged += $recur
2329 unless $part_pkg->recurtax =~ /^Y$/i
2330 || $tax->recurtax =~ /^Y$/i;
2331 next unless $taxable_charged;
2333 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2334 #my ($mon,$year) = (localtime($sdate) )[4,5];
2335 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2337 my $freq = $part_pkg->freq || 1;
2338 if ( $freq !~ /(\d+)$/ ) {
2339 $dbh->rollback if $oldAutoCommit;
2340 return "daily/weekly package definitions not (yet?)".
2341 " compatible with monthly tax exemptions";
2343 my $taxable_per_month =
2344 sprintf("%.2f", $taxable_charged / $freq );
2346 #call the whole thing off if this customer has any old
2347 #exemption records...
2348 my @cust_tax_exempt =
2349 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2350 if ( @cust_tax_exempt ) {
2351 $dbh->rollback if $oldAutoCommit;
2353 'this customer still has old-style tax exemption records; '.
2354 'run bin/fs-migrate-cust_tax_exempt?';
2357 foreach my $which_month ( 1 .. $freq ) {
2359 #maintain the new exemption table now
2362 FROM cust_tax_exempt_pkg
2363 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2364 LEFT JOIN cust_bill USING ( invnum )
2370 my $sth = dbh->prepare($sql) or do {
2371 $dbh->rollback if $oldAutoCommit;
2372 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2380 $dbh->rollback if $oldAutoCommit;
2381 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2383 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2385 my $remaining_exemption =
2386 $tax->exempt_amount - $existing_exemption;
2387 if ( $remaining_exemption > 0 ) {
2388 my $addl = $remaining_exemption > $taxable_per_month
2389 ? $taxable_per_month
2390 : $remaining_exemption;
2391 $taxable_charged -= $addl;
2393 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2394 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2395 'taxnum' => $tax->taxnum,
2396 'year' => 1900+$year,
2398 'amount' => sprintf("%.2f", $addl ),
2400 $error = $cust_tax_exempt_pkg->insert;
2402 $dbh->rollback if $oldAutoCommit;
2403 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2405 } # if $remaining_exemption > 0
2409 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2410 until ( $mon < 13 ) { $mon -= 12; $year++; }
2412 } #foreach $which_month
2414 } #if $tax->exempt_amount
2416 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2418 #$tax += $taxable_charged * $cust_main_county->tax / 100
2419 $tax{ $tax->taxname || 'Tax' } +=
2420 $taxable_charged * $tax->tax / 100
2422 } #foreach my $tax ( @taxes )
2424 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2426 } #if $setup != 0 || $recur != 0
2428 } #if $cust_pkg->modified
2430 } #foreach my $cust_pkg
2432 unless ( $cust_bill->cust_bill_pkg ) {
2433 $cust_bill->delete; #don't create an invoice w/o line items
2434 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2438 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2440 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2441 my $tax = sprintf("%.2f", $tax{$taxname} );
2442 $charged = sprintf( "%.2f", $charged+$tax );
2444 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2445 'invnum' => $invnum,
2451 'itemdesc' => $taxname,
2453 $error = $cust_bill_pkg->insert;
2455 $dbh->rollback if $oldAutoCommit;
2456 return "can't create invoice line item for invoice #$invnum: $error";
2458 $total_setup += $tax;
2462 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2463 $error = $cust_bill->replace;
2465 $dbh->rollback if $oldAutoCommit;
2466 return "can't update charged for invoice #$invnum: $error";
2469 foreach my $hook ( @precommit_hooks ) {
2471 &{$hook}; #($self) ?
2474 $dbh->rollback if $oldAutoCommit;
2475 return "$@ running precommit hook $hook\n";
2479 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2483 =item collect OPTIONS
2485 (Attempt to) collect money for this customer's outstanding invoices (see
2486 L<FS::cust_bill>). Usually used after the bill method.
2488 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2489 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2490 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2492 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2493 and the invoice events web interface.
2495 If there is an error, returns the error, otherwise returns false.
2497 Options are passed as name-value pairs.
2499 Currently available options are:
2501 invoice_time - Use this time when deciding when to print invoices and
2502 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>
2503 for conversion functions.
2505 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2508 quiet - set true to surpress email card/ACH decline notices.
2510 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2513 payby - allows for one time override of normal customer billing method
2518 my( $self, %options ) = @_;
2519 my $invoice_time = $options{'invoice_time'} || time;
2522 local $SIG{HUP} = 'IGNORE';
2523 local $SIG{INT} = 'IGNORE';
2524 local $SIG{QUIT} = 'IGNORE';
2525 local $SIG{TERM} = 'IGNORE';
2526 local $SIG{TSTP} = 'IGNORE';
2527 local $SIG{PIPE} = 'IGNORE';
2529 my $oldAutoCommit = $FS::UID::AutoCommit;
2530 local $FS::UID::AutoCommit = 0;
2533 $self->select_for_update; #mutex
2535 my $balance = $self->balance;
2536 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2538 unless ( $balance > 0 ) { #redundant?????
2539 $dbh->rollback if $oldAutoCommit; #hmm
2543 if ( exists($options{'retry_card'}) ) {
2544 carp 'retry_card option passed to collect is deprecated; use retry';
2545 $options{'retry'} ||= $options{'retry_card'};
2547 if ( exists($options{'retry'}) && $options{'retry'} ) {
2548 my $error = $self->retry_realtime;
2550 $dbh->rollback if $oldAutoCommit;
2556 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2557 $extra_sql = " AND freq = '1m' ";
2559 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2562 foreach my $cust_bill ( $self->open_cust_bill ) {
2564 # don't try to charge for the same invoice if it's already in a batch
2565 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2567 last if $self->balance <= 0;
2569 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2572 foreach my $part_bill_event ( due_events ( $cust_bill,
2573 exists($options{'payby'})
2579 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2580 || $self->balance <= 0; # or if balance<=0
2583 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2584 warn " do_event " . $cust_bill . " ". (%options) . "\n"
2587 if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2588 # gah, even with transactions.
2589 $dbh->commit if $oldAutoCommit; #well.
2598 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2603 =item retry_realtime
2605 Schedules realtime / batch credit card / electronic check / LEC billing
2606 events for for retry. Useful if card information has changed or manual
2607 retry is desired. The 'collect' method must be called to actually retry
2610 Implementation details: For each of this customer's open invoices, changes
2611 the status of the first "done" (with statustext error) realtime processing
2616 sub retry_realtime {
2619 local $SIG{HUP} = 'IGNORE';
2620 local $SIG{INT} = 'IGNORE';
2621 local $SIG{QUIT} = 'IGNORE';
2622 local $SIG{TERM} = 'IGNORE';
2623 local $SIG{TSTP} = 'IGNORE';
2624 local $SIG{PIPE} = 'IGNORE';
2626 my $oldAutoCommit = $FS::UID::AutoCommit;
2627 local $FS::UID::AutoCommit = 0;
2630 foreach my $cust_bill (
2631 grep { $_->cust_bill_event }
2632 $self->open_cust_bill
2634 my @cust_bill_event =
2635 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2637 #$_->part_bill_event->plan eq 'realtime-card'
2638 $_->part_bill_event->eventcode =~
2639 /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2640 && $_->status eq 'done'
2643 $cust_bill->cust_bill_event;
2644 next unless @cust_bill_event;
2645 my $error = $cust_bill_event[0]->retry;
2647 $dbh->rollback if $oldAutoCommit;
2648 return "error scheduling invoice event for retry: $error";
2653 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2658 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2660 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2661 via a Business::OnlinePayment realtime gateway. See
2662 L<http://420.am/business-onlinepayment> for supported gateways.
2664 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2666 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
2668 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2669 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2670 if set, will override the value from the customer record.
2672 I<description> is a free-text field passed to the gateway. It defaults to
2673 "Internet services".
2675 If an I<invnum> is specified, this payment (if successful) is applied to the
2676 specified invoice. If you don't specify an I<invnum> you might want to
2677 call the B<apply_payments> method.
2679 I<quiet> can be set true to surpress email decline notices.
2681 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
2682 resulting paynum, if any.
2684 I<payunique> is a unique identifier for this payment.
2686 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2693 my( $self, $method, $amount, %options ) = @_;
2695 warn "$me realtime_bop: $method $amount\n";
2696 warn " $_ => $options{$_}\n" foreach keys %options;
2699 $options{'description'} ||= 'Internet services';
2701 eval "use Business::OnlinePayment";
2704 my $payinfo = exists($options{'payinfo'})
2705 ? $options{'payinfo'}
2708 my %method2payby = (
2715 # set taxclass and trans_is_recur based on invnum if there is one
2719 my $trans_is_recur = 0;
2720 if ( $options{'invnum'} ) {
2722 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2723 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2726 map { $_->part_pkg }
2728 map { $_->cust_pkg }
2729 $cust_bill->cust_bill_pkg;
2731 my @taxclasses = map $_->taxclass, @part_pkg;
2732 $taxclass = $taxclasses[0]
2733 unless grep { $taxclasses[0] ne $_ } @taxclasses; #unless there are
2734 #different taxclasses
2736 if grep { $_->freq ne '0' } @part_pkg;
2744 #look for an agent gateway override first
2746 if ( $method eq 'CC' ) {
2747 $cardtype = cardtype($payinfo);
2748 } elsif ( $method eq 'ECHECK' ) {
2751 $cardtype = $method;
2755 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2756 cardtype => $cardtype,
2757 taxclass => $taxclass, } )
2758 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2760 taxclass => $taxclass, } )
2761 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2762 cardtype => $cardtype,
2764 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2766 taxclass => '', } );
2768 my $payment_gateway = '';
2769 my( $processor, $login, $password, $action, @bop_options );
2770 if ( $override ) { #use a payment gateway override
2772 $payment_gateway = $override->payment_gateway;
2774 $processor = $payment_gateway->gateway_module;
2775 $login = $payment_gateway->gateway_username;
2776 $password = $payment_gateway->gateway_password;
2777 $action = $payment_gateway->gateway_action;
2778 @bop_options = $payment_gateway->options;
2780 } else { #use the standard settings from the config
2782 ( $processor, $login, $password, $action, @bop_options ) =
2783 $self->default_payment_gateway($method);
2791 my $address = exists($options{'address1'})
2792 ? $options{'address1'}
2794 my $address2 = exists($options{'address2'})
2795 ? $options{'address2'}
2797 $address .= ", ". $address2 if length($address2);
2799 my $o_payname = exists($options{'payname'})
2800 ? $options{'payname'}
2802 my($payname, $payfirst, $paylast);
2803 if ( $o_payname && $method ne 'ECHECK' ) {
2804 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2805 or return "Illegal payname $payname";
2806 ($payfirst, $paylast) = ($1, $2);
2808 $payfirst = $self->getfield('first');
2809 $paylast = $self->getfield('last');
2810 $payname = "$payfirst $paylast";
2813 my @invoicing_list = $self->invoicing_list_emailonly;
2814 if ( $conf->exists('emailinvoiceautoalways')
2815 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
2816 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2817 push @invoicing_list, $self->all_emails;
2820 my $email = ($conf->exists('business-onlinepayment-email-override'))
2821 ? $conf->config('business-onlinepayment-email-override')
2822 : $invoicing_list[0];
2826 my $payip = exists($options{'payip'})
2829 $content{customer_ip} = $payip
2832 $content{invoice_number} = $options{'invnum'}
2833 if exists($options{'invnum'}) && length($options{'invnum'});
2835 $content{email_customer} =
2836 ( $conf->exists('business-onlinepayment-email_customer')
2837 || $conf->exists('business-onlinepayment-email-override') );
2840 if ( $method eq 'CC' ) {
2842 $content{card_number} = $payinfo;
2843 $paydate = exists($options{'paydate'})
2844 ? $options{'paydate'}
2846 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2847 $content{expiration} = "$2/$1";
2849 my $paycvv = exists($options{'paycvv'})
2850 ? $options{'paycvv'}
2852 $content{cvv2} = $paycvv
2855 my $paystart_month = exists($options{'paystart_month'})
2856 ? $options{'paystart_month'}
2857 : $self->paystart_month;
2859 my $paystart_year = exists($options{'paystart_year'})
2860 ? $options{'paystart_year'}
2861 : $self->paystart_year;
2863 $content{card_start} = "$paystart_month/$paystart_year"
2864 if $paystart_month && $paystart_year;
2866 my $payissue = exists($options{'payissue'})
2867 ? $options{'payissue'}
2869 $content{issue_number} = $payissue if $payissue;
2871 if ( $self->_bop_recurring_billing( 'payinfo' => $payinfo,
2872 'trans_is_recur' => $trans_is_recur,
2876 $content{recurring_billing} = 'YES';
2877 $content{acct_code} = 'rebill'
2878 if $conf->exists('credit_card-recurring_billing_acct_code');
2881 } elsif ( $method eq 'ECHECK' ) {
2882 ( $content{account_number}, $content{routing_code} ) =
2883 split('@', $payinfo);
2884 $content{bank_name} = $o_payname;
2885 $content{bank_state} = exists($options{'paystate'})
2886 ? $options{'paystate'}
2887 : $self->getfield('paystate');
2888 $content{account_type} = exists($options{'paytype'})
2889 ? uc($options{'paytype'}) || 'CHECKING'
2890 : uc($self->getfield('paytype')) || 'CHECKING';
2891 $content{account_name} = $payname;
2892 $content{customer_org} = $self->company ? 'B' : 'I';
2893 $content{state_id} = exists($options{'stateid'})
2894 ? $options{'stateid'}
2895 : $self->getfield('stateid');
2896 $content{state_id_state} = exists($options{'stateid_state'})
2897 ? $options{'stateid_state'}
2898 : $self->getfield('stateid_state');
2899 $content{customer_ssn} = exists($options{'ss'})
2902 } elsif ( $method eq 'LEC' ) {
2903 $content{phone} = $payinfo;
2907 # run transaction(s)
2910 my $balance = exists( $options{'balance'} )
2911 ? $options{'balance'}
2914 $self->select_for_update; #mutex ... just until we get our pending record in
2916 #the checks here are intended to catch concurrent payments
2917 #double-form-submission prevention is taken care of in cust_pay_pending::check
2920 return "The customer's balance has changed; $method transaction aborted."
2921 if $self->balance < $balance;
2922 #&& $self->balance < $amount; #might as well anyway?
2924 #also check and make sure there aren't *other* pending payments for this cust
2926 my @pending = qsearch('cust_pay_pending', {
2927 'custnum' => $self->custnum,
2928 'status' => { op=>'!=', value=>'done' }
2930 return "A payment is already being processed for this customer (".
2931 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
2932 "); $method transaction aborted."
2933 if scalar(@pending);
2935 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
2937 my $cust_pay_pending = new FS::cust_pay_pending {
2938 'custnum' => $self->custnum,
2939 #'invnum' => $options{'invnum'},
2942 'payby' => $method2payby{$method},
2943 'payinfo' => $payinfo,
2944 'paydate' => $paydate,
2945 'recurring_billing' => $content{recurring_billing},
2947 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
2949 $cust_pay_pending->payunique( $options{payunique} )
2950 if defined($options{payunique}) && length($options{payunique});
2951 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
2952 return $cpp_new_err if $cpp_new_err;
2954 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2956 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2957 $transaction->content(
2960 'password' => $password,
2961 'action' => $action1,
2962 'description' => $options{'description'},
2963 'amount' => $amount,
2964 #'invoice_number' => $options{'invnum'},
2965 'customer_id' => $self->custnum,
2966 'last_name' => $paylast,
2967 'first_name' => $payfirst,
2969 'address' => $address,
2970 'city' => ( exists($options{'city'})
2973 'state' => ( exists($options{'state'})
2976 'zip' => ( exists($options{'zip'})
2979 'country' => ( exists($options{'country'})
2980 ? $options{'country'}
2982 'referer' => 'http://cleanwhisker.420.am/',
2984 'phone' => $self->daytime || $self->night,
2988 $cust_pay_pending->status('pending');
2989 my $cpp_pending_err = $cust_pay_pending->replace;
2990 return $cpp_pending_err if $cpp_pending_err;
2992 $transaction->submit();
2994 if ( $transaction->is_success() && $action2 ) {
2996 $cust_pay_pending->status('authorized');
2997 my $cpp_authorized_err = $cust_pay_pending->replace;
2998 return $cpp_authorized_err if $cpp_authorized_err;
3000 my $auth = $transaction->authorization;
3001 my $ordernum = $transaction->can('order_number')
3002 ? $transaction->order_number
3006 new Business::OnlinePayment( $processor, @bop_options );
3013 password => $password,
3014 order_number => $ordernum,
3016 authorization => $auth,
3017 description => $options{'description'},
3020 foreach my $field (qw( authorization_source_code returned_ACI
3021 transaction_identifier validation_code
3022 transaction_sequence_num local_transaction_date
3023 local_transaction_time AVS_result_code )) {
3024 $capture{$field} = $transaction->$field() if $transaction->can($field);
3027 $capture->content( %capture );
3031 unless ( $capture->is_success ) {
3032 my $e = "Authorization successful but capture failed, custnum #".
3033 $self->custnum. ': '. $capture->result_code.
3034 ": ". $capture->error_message;
3041 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3042 my $cpp_captured_err = $cust_pay_pending->replace;
3043 return $cpp_captured_err if $cpp_captured_err;
3046 # remove paycvv after initial transaction
3049 #false laziness w/misc/process/payment.cgi - check both to make sure working
3051 if ( defined $self->dbdef_table->column('paycvv')
3052 && length($self->paycvv)
3053 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3055 my $error = $self->remove_cvv;
3057 warn "WARNING: error removing cvv: $error\n";
3065 if ( $transaction->is_success() ) {
3068 if ( $payment_gateway ) { # agent override
3069 $paybatch = $payment_gateway->gatewaynum. '-';
3072 $paybatch .= "$processor:". $transaction->authorization;
3074 $paybatch .= ':'. $transaction->order_number
3075 if $transaction->can('order_number')
3076 && length($transaction->order_number);
3078 my $cust_pay = new FS::cust_pay ( {
3079 'custnum' => $self->custnum,
3080 'invnum' => $options{'invnum'},
3083 'payby' => $method2payby{$method},
3084 'payinfo' => $payinfo,
3085 'paybatch' => $paybatch,
3086 'paydate' => $paydate,
3088 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3089 $cust_pay->payunique( $options{payunique} )
3090 if defined($options{payunique}) && length($options{payunique});
3092 my $oldAutoCommit = $FS::UID::AutoCommit;
3093 local $FS::UID::AutoCommit = 0;
3096 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3098 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3101 $cust_pay->invnum(''); #try again with no specific invnum
3102 my $error2 = $cust_pay->insert( $options{'manual'} ?
3103 ( 'manual' => 1 ) : ()
3106 # gah. but at least we have a record of the state we had to abort in
3107 # from cust_pay_pending now.
3108 my $e = "WARNING: $method captured but payment not recorded - ".
3109 "error inserting payment ($processor): $error2".
3110 " (previously tried insert with invnum #$options{'invnum'}" .
3111 ": $error ) - pending payment saved as paypendingnum ".
3112 $cust_pay_pending->paypendingnum. "\n";
3118 if ( $options{'paynum_ref'} ) {
3119 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3122 $cust_pay_pending->status('done');
3123 $cust_pay_pending->statustext('captured');
3124 my $cpp_done_err = $cust_pay_pending->replace;
3126 if ( $cpp_done_err ) {
3128 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3129 my $e = "WARNING: $method captured but payment not recorded - ".
3130 "error updating status for paypendingnum ".
3131 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3137 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3138 return ''; #no error
3144 my $perror = "$processor error: ". $transaction->error_message;
3146 unless ( $transaction->error_message ) {
3149 #this should be normalized :/
3151 # bad, ad-hoc B:OP:PayflowPro "transaction_response" BS
3152 if ( $transaction->can('param')
3153 && $transaction->param('transaction_response') ) {
3154 $t_response = $transaction->param('transaction_response')
3156 # slightly better, ad-hoc B:OP:TransactionCentral without "param"
3157 } elsif ( $transaction->can('response_page') ) {
3159 'page' => ( $transaction->can('response_page')
3160 ? $transaction->response_page
3163 'code' => ( $transaction->can('response_code')
3164 ? $transaction->response_code
3167 'headers' => ( $transaction->can('response_headers')
3168 ? $transaction->response_headers
3174 "No additional debugging information available for $processor";
3177 $perror .= "No error_message returned from $processor -- ".
3178 ( ref($t_response) ? Dumper($t_response) : $t_response );
3182 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3183 && $conf->exists('emaildecline')
3184 && grep { $_ ne 'POST' } $self->invoicing_list
3185 && ! grep { $transaction->error_message =~ /$_/ }
3186 $conf->config('emaildecline-exclude')
3188 my @templ = $conf->config('declinetemplate');
3189 my $template = new Text::Template (
3191 SOURCE => [ map "$_\n", @templ ],
3192 ) or return "($perror) can't create template: $Text::Template::ERROR";
3193 $template->compile()
3194 or return "($perror) can't compile template: $Text::Template::ERROR";
3196 my $templ_hash = { error => $transaction->error_message };
3198 my $error = send_email(
3199 'from' => $conf->config('invoice_from'),
3200 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3201 'subject' => 'Your payment could not be processed',
3202 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3205 $perror .= " (also received error sending decline notification: $error)"
3210 $cust_pay_pending->status('done');
3211 $cust_pay_pending->statustext("declined: $perror");
3212 my $cpp_done_err = $cust_pay_pending->replace;
3213 if ( $cpp_done_err ) {
3214 my $e = "WARNING: $method declined but pending payment not resolved - ".
3215 "error updating status for paypendingnum ".
3216 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3218 $perror = "$e ($perror)";
3226 =item default_payment_gateway
3230 sub default_payment_gateway {
3231 my( $self, $method ) = @_;
3233 die "Real-time processing not enabled\n"
3234 unless $conf->exists('business-onlinepayment');
3237 my $bop_config = 'business-onlinepayment';
3238 $bop_config .= '-ach'
3239 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3240 my ( $processor, $login, $password, $action, @bop_options ) =
3241 $conf->config($bop_config);
3242 $action ||= 'normal authorization';
3243 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3244 die "No real-time processor is enabled - ".
3245 "did you set the business-onlinepayment configuration value?\n"
3248 ( $processor, $login, $password, $action, @bop_options )
3253 Removes the I<paycvv> field from the database directly.
3255 If there is an error, returns the error, otherwise returns false.
3261 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3262 or return dbh->errstr;
3263 $sth->execute($self->custnum)
3264 or return $sth->errstr;
3269 sub _bop_recurring_billing {
3270 my( $self, %opt ) = @_;
3272 my $method = $conf->config('credit_card-recurring_billing_flag');
3274 if ( $method eq 'transaction_is_recur' ) {
3276 return 1 if $opt{'trans_is_recur'};
3280 my %hash = ( 'custnum' => $self->custnum,
3285 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
3286 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
3297 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3299 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3300 via a Business::OnlinePayment realtime gateway. See
3301 L<http://420.am/business-onlinepayment> for supported gateways.
3303 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3305 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3307 Most gateways require a reference to an original payment transaction to refund,
3308 so you probably need to specify a I<paynum>.
3310 I<amount> defaults to the original amount of the payment if not specified.
3312 I<reason> specifies a reason for the refund.
3314 I<paydate> specifies the expiration date for a credit card overriding the
3315 value from the customer record or the payment record. Specified as yyyy-mm-dd
3317 Implementation note: If I<amount> is unspecified or equal to the amount of the
3318 orignal payment, first an attempt is made to "void" the transaction via
3319 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3320 the normal attempt is made to "refund" ("credit") the transaction via the
3321 gateway is attempted.
3323 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3324 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3325 #if set, will override the value from the customer record.
3327 #If an I<invnum> is specified, this payment (if successful) is applied to the
3328 #specified invoice. If you don't specify an I<invnum> you might want to
3329 #call the B<apply_payments> method.
3333 #some false laziness w/realtime_bop, not enough to make it worth merging
3334 #but some useful small subs should be pulled out
3335 sub realtime_refund_bop {
3336 my( $self, $method, %options ) = @_;
3338 warn "$me realtime_refund_bop: $method refund\n";
3339 warn " $_ => $options{$_}\n" foreach keys %options;
3342 eval "use Business::OnlinePayment";
3346 # look up the original payment and optionally a gateway for that payment
3350 my $amount = $options{'amount'};
3352 my( $processor, $login, $password, @bop_options ) ;
3353 my( $auth, $order_number ) = ( '', '', '' );
3355 if ( $options{'paynum'} ) {
3357 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3358 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3359 or return "Unknown paynum $options{'paynum'}";
3360 $amount ||= $cust_pay->paid;
3362 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3363 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3364 $cust_pay->paybatch;
3365 my $gatewaynum = '';
3366 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3368 if ( $gatewaynum ) { #gateway for the payment to be refunded
3370 my $payment_gateway =
3371 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3372 die "payment gateway $gatewaynum not found"
3373 unless $payment_gateway;
3375 $processor = $payment_gateway->gateway_module;
3376 $login = $payment_gateway->gateway_username;
3377 $password = $payment_gateway->gateway_password;
3378 @bop_options = $payment_gateway->options;
3380 } else { #try the default gateway
3382 my( $conf_processor, $unused_action );
3383 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3384 $self->default_payment_gateway($method);
3386 return "processor of payment $options{'paynum'} $processor does not".
3387 " match default processor $conf_processor"
3388 unless $processor eq $conf_processor;
3393 } else { # didn't specify a paynum, so look for agent gateway overrides
3394 # like a normal transaction
3397 if ( $method eq 'CC' ) {
3398 $cardtype = cardtype($self->payinfo);
3399 } elsif ( $method eq 'ECHECK' ) {
3402 $cardtype = $method;
3405 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3406 cardtype => $cardtype,
3408 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3410 taxclass => '', } );
3412 if ( $override ) { #use a payment gateway override
3414 my $payment_gateway = $override->payment_gateway;
3416 $processor = $payment_gateway->gateway_module;
3417 $login = $payment_gateway->gateway_username;
3418 $password = $payment_gateway->gateway_password;
3419 #$action = $payment_gateway->gateway_action;
3420 @bop_options = $payment_gateway->options;
3422 } else { #use the standard settings from the config
3425 ( $processor, $login, $password, $unused_action, @bop_options ) =
3426 $self->default_payment_gateway($method);
3431 return "neither amount nor paynum specified" unless $amount;
3436 'password' => $password,
3437 'order_number' => $order_number,
3438 'amount' => $amount,
3439 'referer' => 'http://cleanwhisker.420.am/',
3441 $content{authorization} = $auth
3442 if length($auth); #echeck/ACH transactions have an order # but no auth
3443 #(at least with authorize.net)
3445 my $disable_void_after;
3446 if ($conf->exists('disable_void_after')
3447 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3448 $disable_void_after = $1;
3451 #first try void if applicable
3452 if ( $cust_pay && $cust_pay->paid == $amount
3454 ( not defined($disable_void_after) )
3455 || ( time < ($cust_pay->_date + $disable_void_after ) )
3458 warn " attempting void\n" if $DEBUG > 1;
3459 my $void = new Business::OnlinePayment( $processor, @bop_options );
3460 $void->content( 'action' => 'void', %content );
3462 if ( $void->is_success ) {
3463 my $error = $cust_pay->void($options{'reason'});
3465 # gah, even with transactions.
3466 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3467 "error voiding payment: $error";
3471 warn " void successful\n" if $DEBUG > 1;
3476 warn " void unsuccessful, trying refund\n"
3480 my $address = $self->address1;
3481 $address .= ", ". $self->address2 if $self->address2;
3483 my($payname, $payfirst, $paylast);
3484 if ( $self->payname && $method ne 'ECHECK' ) {
3485 $payname = $self->payname;
3486 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3487 or return "Illegal payname $payname";
3488 ($payfirst, $paylast) = ($1, $2);
3490 $payfirst = $self->getfield('first');
3491 $paylast = $self->getfield('last');
3492 $payname = "$payfirst $paylast";
3495 my @invoicing_list = $self->invoicing_list_emailonly;
3496 if ( $conf->exists('emailinvoiceautoalways')
3497 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3498 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3499 push @invoicing_list, $self->all_emails;
3502 my $email = ($conf->exists('business-onlinepayment-email-override'))
3503 ? $conf->config('business-onlinepayment-email-override')
3504 : $invoicing_list[0];
3506 my $payip = exists($options{'payip'})
3509 $content{customer_ip} = $payip
3513 if ( $method eq 'CC' ) {
3516 $content{card_number} = $payinfo = $cust_pay->payinfo;
3517 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3518 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3519 ($content{expiration} = "$2/$1"); # where available
3521 $content{card_number} = $payinfo = $self->payinfo;
3522 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3523 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3524 $content{expiration} = "$2/$1";
3527 } elsif ( $method eq 'ECHECK' ) {
3530 $payinfo = $cust_pay->payinfo;
3532 $payinfo = $self->payinfo;
3534 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3535 $content{bank_name} = $self->payname;
3536 $content{account_type} = 'CHECKING';
3537 $content{account_name} = $payname;
3538 $content{customer_org} = $self->company ? 'B' : 'I';
3539 $content{customer_ssn} = $self->ss;
3540 } elsif ( $method eq 'LEC' ) {
3541 $content{phone} = $payinfo = $self->payinfo;
3545 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3546 my %sub_content = $refund->content(
3547 'action' => 'credit',
3548 'customer_id' => $self->custnum,
3549 'last_name' => $paylast,
3550 'first_name' => $payfirst,
3552 'address' => $address,
3553 'city' => $self->city,
3554 'state' => $self->state,
3555 'zip' => $self->zip,
3556 'country' => $self->country,
3558 'phone' => $self->daytime || $self->night,
3561 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3565 return "$processor error: ". $refund->error_message
3566 unless $refund->is_success();
3568 my %method2payby = (
3574 my $paybatch = "$processor:". $refund->authorization;
3575 $paybatch .= ':'. $refund->order_number
3576 if $refund->can('order_number') && $refund->order_number;
3578 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3579 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3580 last unless @cust_bill_pay;
3581 my $cust_bill_pay = pop @cust_bill_pay;
3582 my $error = $cust_bill_pay->delete;
3586 my $cust_refund = new FS::cust_refund ( {
3587 'custnum' => $self->custnum,
3588 'paynum' => $options{'paynum'},
3589 'refund' => $amount,
3591 'payby' => $method2payby{$method},
3592 'payinfo' => $payinfo,
3593 'paybatch' => $paybatch,
3594 'reason' => $options{'reason'} || 'card or ACH refund',
3596 my $error = $cust_refund->insert;
3598 $cust_refund->paynum(''); #try again with no specific paynum
3599 my $error2 = $cust_refund->insert;
3601 # gah, even with transactions.
3602 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3603 "error inserting refund ($processor): $error2".
3604 " (previously tried insert with paynum #$options{'paynum'}" .
3615 =item batch_card OPTION => VALUE...
3617 Adds a payment for this invoice to the pending credit card batch (see
3618 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3619 runs the payment using a realtime gateway.
3624 my ($self, %options) = @_;
3627 if (exists($options{amount})) {
3628 $amount = $options{amount};
3630 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3632 return '' unless $amount > 0;
3634 my $invnum = delete $options{invnum};
3635 my $payby = $options{invnum} || $self->payby; #dubious
3637 if ($options{'realtime'}) {
3638 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3644 my $oldAutoCommit = $FS::UID::AutoCommit;
3645 local $FS::UID::AutoCommit = 0;
3648 #this needs to handle mysql as well as Pg, like svc_acct.pm
3649 #(make it into a common function if folks need to do batching with mysql)
3650 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3651 or return "Cannot lock pay_batch: " . $dbh->errstr;
3655 'payby' => FS::payby->payby2payment($payby),
3658 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3660 unless ( $pay_batch ) {
3661 $pay_batch = new FS::pay_batch \%pay_batch;
3662 my $error = $pay_batch->insert;
3664 $dbh->rollback if $oldAutoCommit;
3665 die "error creating new batch: $error\n";
3669 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3670 'batchnum' => $pay_batch->batchnum,
3671 'custnum' => $self->custnum,
3674 foreach (qw( address1 address2 city state zip country payby payinfo paydate
3676 $options{$_} = '' unless exists($options{$_});
3679 my $cust_pay_batch = new FS::cust_pay_batch ( {
3680 'batchnum' => $pay_batch->batchnum,
3681 'invnum' => $invnum || 0, # is there a better value?
3682 # this field should be
3684 # cust_bill_pay_batch now
3685 'custnum' => $self->custnum,
3686 'last' => $self->getfield('last'),
3687 'first' => $self->getfield('first'),
3688 'address1' => $options{address1} || $self->address1,
3689 'address2' => $options{address2} || $self->address2,
3690 'city' => $options{city} || $self->city,
3691 'state' => $options{state} || $self->state,
3692 'zip' => $options{zip} || $self->zip,
3693 'country' => $options{country} || $self->country,
3694 'payby' => $options{payby} || $self->payby,
3695 'payinfo' => $options{payinfo} || $self->payinfo,
3696 'exp' => $options{paydate} || $self->paydate,
3697 'payname' => $options{payname} || $self->payname,
3698 'amount' => $amount, # consolidating
3701 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3702 if $old_cust_pay_batch;
3705 if ($old_cust_pay_batch) {
3706 $error = $cust_pay_batch->replace($old_cust_pay_batch)
3708 $error = $cust_pay_batch->insert;
3712 $dbh->rollback if $oldAutoCommit;
3716 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
3717 foreach my $cust_bill ($self->open_cust_bill) {
3718 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3719 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3720 'invnum' => $cust_bill->invnum,
3721 'paybatchnum' => $cust_pay_batch->paybatchnum,
3722 'amount' => $cust_bill->owed,
3725 if ($unapplied >= $cust_bill_pay_batch->amount){
3726 $unapplied -= $cust_bill_pay_batch->amount;
3729 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
3730 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
3732 $error = $cust_bill_pay_batch->insert;
3734 $dbh->rollback if $oldAutoCommit;
3739 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3745 Returns the total owed for this customer on all invoices
3746 (see L<FS::cust_bill/owed>).
3752 $self->total_owed_date(2145859200); #12/31/2037
3755 =item total_owed_date TIME
3757 Returns the total owed for this customer on all invoices with date earlier than
3758 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3759 see L<Time::Local> and L<Date::Parse> for conversion functions.
3763 sub total_owed_date {
3767 foreach my $cust_bill (
3768 grep { $_->_date <= $time }
3769 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3771 $total_bill += $cust_bill->owed;
3773 sprintf( "%.2f", $total_bill );
3776 =item apply_payments_and_credits
3778 Applies unapplied payments and credits.
3780 In most cases, this new method should be used in place of sequential
3781 apply_payments and apply_credits methods.
3783 If there is an error, returns the error, otherwise returns false.
3787 sub apply_payments_and_credits {
3790 local $SIG{HUP} = 'IGNORE';
3791 local $SIG{INT} = 'IGNORE';
3792 local $SIG{QUIT} = 'IGNORE';
3793 local $SIG{TERM} = 'IGNORE';
3794 local $SIG{TSTP} = 'IGNORE';
3795 local $SIG{PIPE} = 'IGNORE';
3797 my $oldAutoCommit = $FS::UID::AutoCommit;
3798 local $FS::UID::AutoCommit = 0;
3801 $self->select_for_update; #mutex
3803 foreach my $cust_bill ( $self->open_cust_bill ) {
3804 my $error = $cust_bill->apply_payments_and_credits;
3806 $dbh->rollback if $oldAutoCommit;
3807 return "Error applying: $error";
3811 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3816 =item apply_credits OPTION => VALUE ...
3818 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3819 to outstanding invoice balances in chronological order (or reverse
3820 chronological order if the I<order> option is set to B<newest>) and returns the
3821 value of any remaining unapplied credits available for refund (see
3822 L<FS::cust_refund>).
3824 Dies if there is an error.
3832 local $SIG{HUP} = 'IGNORE';
3833 local $SIG{INT} = 'IGNORE';
3834 local $SIG{QUIT} = 'IGNORE';
3835 local $SIG{TERM} = 'IGNORE';
3836 local $SIG{TSTP} = 'IGNORE';
3837 local $SIG{PIPE} = 'IGNORE';
3839 my $oldAutoCommit = $FS::UID::AutoCommit;
3840 local $FS::UID::AutoCommit = 0;
3843 $self->select_for_update; #mutex
3845 unless ( $self->total_credited ) {
3846 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3850 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3851 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3853 my @invoices = $self->open_cust_bill;
3854 @invoices = sort { $b->_date <=> $a->_date } @invoices
3855 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3858 foreach my $cust_bill ( @invoices ) {
3861 if ( !defined($credit) || $credit->credited == 0) {
3862 $credit = pop @credits or last;
3865 if ($cust_bill->owed >= $credit->credited) {
3866 $amount=$credit->credited;
3868 $amount=$cust_bill->owed;
3871 my $cust_credit_bill = new FS::cust_credit_bill ( {
3872 'crednum' => $credit->crednum,
3873 'invnum' => $cust_bill->invnum,
3874 'amount' => $amount,
3876 my $error = $cust_credit_bill->insert;
3878 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3882 redo if ($cust_bill->owed > 0);
3886 my $total_credited = $self->total_credited;
3888 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3890 return $total_credited;
3893 =item apply_payments
3895 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3896 to outstanding invoice balances in chronological order.
3898 #and returns the value of any remaining unapplied payments.
3900 Dies if there is an error.
3904 sub apply_payments {
3907 local $SIG{HUP} = 'IGNORE';
3908 local $SIG{INT} = 'IGNORE';
3909 local $SIG{QUIT} = 'IGNORE';
3910 local $SIG{TERM} = 'IGNORE';
3911 local $SIG{TSTP} = 'IGNORE';
3912 local $SIG{PIPE} = 'IGNORE';
3914 my $oldAutoCommit = $FS::UID::AutoCommit;
3915 local $FS::UID::AutoCommit = 0;
3918 $self->select_for_update; #mutex
3922 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3923 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3925 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3926 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3930 foreach my $cust_bill ( @invoices ) {
3933 if ( !defined($payment) || $payment->unapplied == 0 ) {
3934 $payment = pop @payments or last;
3937 if ( $cust_bill->owed >= $payment->unapplied ) {
3938 $amount = $payment->unapplied;
3940 $amount = $cust_bill->owed;
3943 my $cust_bill_pay = new FS::cust_bill_pay ( {
3944 'paynum' => $payment->paynum,
3945 'invnum' => $cust_bill->invnum,
3946 'amount' => $amount,
3948 my $error = $cust_bill_pay->insert;
3950 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3954 redo if ( $cust_bill->owed > 0);
3958 my $total_unapplied_payments = $self->total_unapplied_payments;
3960 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3962 return $total_unapplied_payments;
3965 =item total_credited
3967 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3968 customer. See L<FS::cust_credit/credited>.
3972 sub total_credited {
3974 my $total_credit = 0;
3975 foreach my $cust_credit ( qsearch('cust_credit', {
3976 'custnum' => $self->custnum,
3978 $total_credit += $cust_credit->credited;
3980 sprintf( "%.2f", $total_credit );
3983 =item total_unapplied_payments
3985 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3986 See L<FS::cust_pay/unapplied>.
3990 sub total_unapplied_payments {
3992 my $total_unapplied = 0;
3993 foreach my $cust_pay ( qsearch('cust_pay', {
3994 'custnum' => $self->custnum,
3996 $total_unapplied += $cust_pay->unapplied;
3998 sprintf( "%.2f", $total_unapplied );
4001 =item total_unapplied_refunds
4003 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4004 customer. See L<FS::cust_refund/unapplied>.
4008 sub total_unapplied_refunds {
4010 my $total_unapplied = 0;
4011 foreach my $cust_refund ( qsearch('cust_refund', {
4012 'custnum' => $self->custnum,
4014 $total_unapplied += $cust_refund->unapplied;
4016 sprintf( "%.2f", $total_unapplied );
4021 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4022 total_credited minus total_unapplied_payments).
4030 + $self->total_unapplied_refunds
4031 - $self->total_credited
4032 - $self->total_unapplied_payments
4036 =item balance_date TIME
4038 Returns the balance for this customer, only considering invoices with date
4039 earlier than TIME (total_owed_date minus total_credited minus
4040 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4041 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4050 $self->total_owed_date($time)
4051 + $self->total_unapplied_refunds
4052 - $self->total_credited
4053 - $self->total_unapplied_payments
4057 =item in_transit_payments
4059 Returns the total of requests for payments for this customer pending in
4060 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4064 sub in_transit_payments {
4066 my $in_transit_payments = 0;
4067 foreach my $pay_batch ( qsearch('pay_batch', {
4070 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4071 'batchnum' => $pay_batch->batchnum,
4072 'custnum' => $self->custnum,
4074 $in_transit_payments += $cust_pay_batch->amount;
4077 sprintf( "%.2f", $in_transit_payments );
4080 =item paydate_monthyear
4082 Returns a two-element list consisting of the month and year of this customer's
4083 paydate (credit card expiration date for CARD customers)
4087 sub paydate_monthyear {
4089 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4091 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4098 =item invoicing_list [ ARRAYREF ]
4100 If an arguement is given, sets these email addresses as invoice recipients
4101 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4102 (except as warnings), so use check_invoicing_list first.
4104 Returns a list of email addresses (with svcnum entries expanded).
4106 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4107 check it without disturbing anything by passing nothing.
4109 This interface may change in the future.
4113 sub invoicing_list {
4114 my( $self, $arrayref ) = @_;
4117 my @cust_main_invoice;
4118 if ( $self->custnum ) {
4119 @cust_main_invoice =
4120 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4122 @cust_main_invoice = ();
4124 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4125 #warn $cust_main_invoice->destnum;
4126 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4127 #warn $cust_main_invoice->destnum;
4128 my $error = $cust_main_invoice->delete;
4129 warn $error if $error;
4132 if ( $self->custnum ) {
4133 @cust_main_invoice =
4134 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4136 @cust_main_invoice = ();
4138 my %seen = map { $_->address => 1 } @cust_main_invoice;
4139 foreach my $address ( @{$arrayref} ) {
4140 next if exists $seen{$address} && $seen{$address};
4141 $seen{$address} = 1;
4142 my $cust_main_invoice = new FS::cust_main_invoice ( {
4143 'custnum' => $self->custnum,
4146 my $error = $cust_main_invoice->insert;
4147 warn $error if $error;
4151 if ( $self->custnum ) {
4153 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4160 =item check_invoicing_list ARRAYREF
4162 Checks these arguements as valid input for the invoicing_list method. If there
4163 is an error, returns the error, otherwise returns false.
4167 sub check_invoicing_list {
4168 my( $self, $arrayref ) = @_;
4170 foreach my $address ( @$arrayref ) {
4172 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4173 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4176 my $cust_main_invoice = new FS::cust_main_invoice ( {
4177 'custnum' => $self->custnum,
4180 my $error = $self->custnum
4181 ? $cust_main_invoice->check
4182 : $cust_main_invoice->checkdest
4184 return $error if $error;
4188 return "Email address required"
4189 if $conf->exists('cust_main-require_invoicing_list_email')
4190 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4195 =item set_default_invoicing_list
4197 Sets the invoicing list to all accounts associated with this customer,
4198 overwriting any previous invoicing list.
4202 sub set_default_invoicing_list {
4204 $self->invoicing_list($self->all_emails);
4209 Returns the email addresses of all accounts provisioned for this customer.
4216 foreach my $cust_pkg ( $self->all_pkgs ) {
4217 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4219 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4220 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4222 $list{$_}=1 foreach map { $_->email } @svc_acct;
4227 =item invoicing_list_addpost
4229 Adds postal invoicing to this customer. If this customer is already configured
4230 to receive postal invoices, does nothing.
4234 sub invoicing_list_addpost {
4236 return if grep { $_ eq 'POST' } $self->invoicing_list;
4237 my @invoicing_list = $self->invoicing_list;
4238 push @invoicing_list, 'POST';
4239 $self->invoicing_list(\@invoicing_list);
4242 =item invoicing_list_emailonly
4244 Returns the list of email invoice recipients (invoicing_list without non-email
4245 destinations such as POST and FAX).
4249 sub invoicing_list_emailonly {
4251 warn "$me invoicing_list_emailonly called"
4253 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4256 =item invoicing_list_emailonly_scalar
4258 Returns the list of email invoice recipients (invoicing_list without non-email
4259 destinations such as POST and FAX) as a comma-separated scalar.
4263 sub invoicing_list_emailonly_scalar {
4265 warn "$me invoicing_list_emailonly_scalar called"
4267 join(', ', $self->invoicing_list_emailonly);
4270 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4272 Returns an array of customers referred by this customer (referral_custnum set
4273 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4274 customers referred by customers referred by this customer and so on, inclusive.
4275 The default behavior is DEPTH 1 (no recursion).
4279 sub referral_cust_main {
4281 my $depth = @_ ? shift : 1;
4282 my $exclude = @_ ? shift : {};
4285 map { $exclude->{$_->custnum}++; $_; }
4286 grep { ! $exclude->{ $_->custnum } }
4287 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4291 map { $_->referral_cust_main($depth-1, $exclude) }
4298 =item referral_cust_main_ncancelled
4300 Same as referral_cust_main, except only returns customers with uncancelled
4305 sub referral_cust_main_ncancelled {
4307 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4310 =item referral_cust_pkg [ DEPTH ]
4312 Like referral_cust_main, except returns a flat list of all unsuspended (and
4313 uncancelled) packages for each customer. The number of items in this list may
4314 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4318 sub referral_cust_pkg {
4320 my $depth = @_ ? shift : 1;
4322 map { $_->unsuspended_pkgs }
4323 grep { $_->unsuspended_pkgs }
4324 $self->referral_cust_main($depth);
4327 =item referring_cust_main
4329 Returns the single cust_main record for the customer who referred this customer
4330 (referral_custnum), or false.
4334 sub referring_cust_main {
4336 return '' unless $self->referral_custnum;
4337 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4340 =item credit AMOUNT, REASON
4342 Applies a credit to this customer. If there is an error, returns the error,
4343 otherwise returns false.
4348 my( $self, $amount, $reason, %options ) = @_;
4349 my $cust_credit = new FS::cust_credit {
4350 'custnum' => $self->custnum,
4351 'amount' => $amount,
4352 'reason' => $reason,
4354 $cust_credit->insert(%options);
4357 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4359 Creates a one-time charge for this customer. If there is an error, returns
4360 the error, otherwise returns false.
4366 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4367 if ( ref( $_[0] ) ) {
4368 $amount = $_[0]->{amount};
4369 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4370 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4371 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4372 : '$'. sprintf("%.2f",$amount);
4373 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4374 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4375 $additional = $_[0]->{additional};
4379 $pkg = @_ ? shift : 'One-time charge';
4380 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4381 $taxclass = @_ ? shift : '';
4385 local $SIG{HUP} = 'IGNORE';
4386 local $SIG{INT} = 'IGNORE';
4387 local $SIG{QUIT} = 'IGNORE';
4388 local $SIG{TERM} = 'IGNORE';
4389 local $SIG{TSTP} = 'IGNORE';
4390 local $SIG{PIPE} = 'IGNORE';
4392 my $oldAutoCommit = $FS::UID::AutoCommit;
4393 local $FS::UID::AutoCommit = 0;
4396 my $part_pkg = new FS::part_pkg ( {
4398 'comment' => $comment,
4402 'classnum' => $classnum ? $classnum : '',
4403 'taxclass' => $taxclass,
4406 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4407 ( 0 .. @$additional - 1 )
4409 'additional_count' => scalar(@$additional),
4410 'setup_fee' => $amount,
4413 my $error = $part_pkg->insert( options => \%options );
4415 $dbh->rollback if $oldAutoCommit;
4419 my $pkgpart = $part_pkg->pkgpart;
4420 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4421 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4422 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4423 $error = $type_pkgs->insert;
4425 $dbh->rollback if $oldAutoCommit;
4430 my $cust_pkg = new FS::cust_pkg ( {
4431 'custnum' => $self->custnum,
4432 'pkgpart' => $pkgpart,
4433 'quantity' => $quantity,
4436 $error = $cust_pkg->insert;
4438 $dbh->rollback if $oldAutoCommit;
4442 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4447 #=item charge_postal_fee
4449 #Applies a one time charge this customer. If there is an error,
4450 #returns the error, returns the cust_pkg charge object or false
4451 #if there was no charge.
4455 # This should be a customer event. For that to work requires that bill
4456 # also be a customer event.
4458 sub charge_postal_fee {
4461 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4462 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4464 my $cust_pkg = new FS::cust_pkg ( {
4465 'custnum' => $self->custnum,
4466 'pkgpart' => $pkgpart,
4470 my $error = $cust_pkg->insert;
4471 $error ? $error : $cust_pkg;
4476 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4482 sort { $a->_date <=> $b->_date }
4483 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4486 =item open_cust_bill
4488 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4493 sub open_cust_bill {
4495 grep { $_->owed > 0 } $self->cust_bill;
4500 Returns all the credits (see L<FS::cust_credit>) for this customer.
4506 sort { $a->_date <=> $b->_date }
4507 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4512 Returns all the payments (see L<FS::cust_pay>) for this customer.
4518 sort { $a->_date <=> $b->_date }
4519 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4524 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4530 sort { $a->_date <=> $b->_date }
4531 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4537 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4543 sort { $a->_date <=> $b->_date }
4544 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4549 Returns a name string for this customer, either "Company (Last, First)" or
4556 my $name = $self->contact;
4557 $name = $self->company. " ($name)" if $self->company;
4563 Returns a name string for this (service/shipping) contact, either
4564 "Company (Last, First)" or "Last, First".
4570 if ( $self->get('ship_last') ) {
4571 my $name = $self->ship_contact;
4572 $name = $self->ship_company. " ($name)" if $self->ship_company;
4581 Returns a name string for this customer, either "Company" or "First Last".
4587 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4590 =item ship_name_short
4592 Returns a name string for this (service/shipping) contact, either "Company"
4597 sub ship_name_short {
4599 if ( $self->get('ship_last') ) {
4600 $self->ship_company !~ /^\s*$/
4601 ? $self->ship_company
4602 : $self->ship_contact_firstlast;
4604 $self->name_company_or_firstlast;
4610 Returns this customer's full (billing) contact name only, "Last, First"
4616 $self->get('last'). ', '. $self->first;
4621 Returns this customer's full (shipping) contact name only, "Last, First"
4627 $self->get('ship_last')
4628 ? $self->get('ship_last'). ', '. $self->ship_first
4632 =item contact_firstlast
4634 Returns this customers full (billing) contact name only, "First Last".
4638 sub contact_firstlast {
4640 $self->first. ' '. $self->get('last');
4643 =item ship_contact_firstlast
4645 Returns this customer's full (shipping) contact name only, "First Last".
4649 sub ship_contact_firstlast {
4651 $self->get('ship_last')
4652 ? $self->first. ' '. $self->get('ship_last')
4653 : $self->contact_firstlast;
4658 Returns this customer's full country name
4664 code2country($self->country);
4671 Returns a status string for this customer, currently:
4675 =item prospect - No packages have ever been ordered
4677 =item active - One or more recurring packages is active
4679 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4681 =item suspended - All non-cancelled recurring packages are suspended
4683 =item cancelled - All recurring packages are cancelled
4689 sub status { shift->cust_status(@_); }
4693 for my $status (qw( prospect active inactive suspended cancelled )) {
4694 my $method = $status.'_sql';
4695 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4696 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4697 $sth->execute( ($self->custnum) x $numnum )
4698 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4699 return $status if $sth->fetchrow_arrayref->[0];
4703 =item ucfirst_cust_status
4705 =item ucfirst_status
4707 Returns the status with the first character capitalized.
4711 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4713 sub ucfirst_cust_status {
4715 ucfirst($self->cust_status);
4720 Returns a hex triplet color string for this customer's status.
4724 use vars qw(%statuscolor);
4725 tie %statuscolor, 'Tie::IxHash',
4726 'prospect' => '7e0079', #'000000', #black? naw, purple
4727 'active' => '00CC00', #green
4728 'inactive' => '0000CC', #blue
4729 'suspended' => 'FF9900', #yellow
4730 'cancelled' => 'FF0000', #red
4733 sub statuscolor { shift->cust_statuscolor(@_); }
4735 sub cust_statuscolor {
4737 $statuscolor{$self->cust_status};
4742 =head1 CLASS METHODS
4748 Class method that returns the list of possible status strings for customers
4749 (see L<the status method|/status>). For example:
4751 @statuses = FS::cust_main->statuses();
4756 #my $self = shift; #could be class...
4762 Returns an SQL expression identifying prospective cust_main records (customers
4763 with no packages ever ordered)
4767 use vars qw($select_count_pkgs);
4768 $select_count_pkgs =
4769 "SELECT COUNT(*) FROM cust_pkg
4770 WHERE cust_pkg.custnum = cust_main.custnum";
4772 sub select_count_pkgs_sql {
4776 sub prospect_sql { "
4777 0 = ( $select_count_pkgs )
4782 Returns an SQL expression identifying active cust_main records (customers with
4783 active recurring packages).
4788 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
4794 Returns an SQL expression identifying inactive cust_main records (customers with
4795 no active recurring packages, but otherwise unsuspended/uncancelled).
4799 sub inactive_sql { "
4800 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4802 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4808 Returns an SQL expression identifying suspended cust_main records.
4813 sub suspended_sql { susp_sql(@_); }
4815 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
4817 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4823 Returns an SQL expression identifying cancelled cust_main records.
4827 sub cancelled_sql { cancel_sql(@_); }
4830 my $recurring_sql = FS::cust_pkg->recurring_sql;
4831 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
4834 0 < ( $select_count_pkgs )
4835 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
4836 AND 0 = ( $select_count_pkgs AND $recurring_sql
4837 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4839 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4845 =item uncancelled_sql
4847 Returns an SQL expression identifying un-cancelled cust_main records.
4851 sub uncancelled_sql { uncancel_sql(@_); }
4852 sub uncancel_sql { "
4853 ( 0 < ( $select_count_pkgs
4854 AND ( cust_pkg.cancel IS NULL
4855 OR cust_pkg.cancel = 0
4858 OR 0 = ( $select_count_pkgs )
4864 Returns an SQL fragment to retreive the balance.
4869 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4870 WHERE cust_bill.custnum = cust_main.custnum )
4871 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4872 WHERE cust_pay.custnum = cust_main.custnum )
4873 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4874 WHERE cust_credit.custnum = cust_main.custnum )
4875 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4876 WHERE cust_refund.custnum = cust_main.custnum )
4879 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4881 Returns an SQL fragment to retreive the balance for this customer, only
4882 considering invoices with date earlier than START_TIME, and optionally not
4883 later than END_TIME (total_owed_date minus total_credited minus
4884 total_unapplied_payments).
4886 Times are specified as SQL fragments or numeric
4887 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4888 L<Date::Parse> for conversion functions. The empty string can be passed
4889 to disable that time constraint completely.
4891 Available options are:
4895 =item unapplied_date - set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
4897 =item total - set to true to remove all customer comparison clauses, for totals
4899 =item where - WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4901 =item join - JOIN clause (typically used with the total option)
4909 sub balance_date_sql {
4910 my( $class, $start, $end, %opt ) = @_;
4912 my $owed = FS::cust_bill->owed_sql;
4913 my $unapp_refund = FS::cust_refund->unapplied_sql;
4914 my $unapp_credit = FS::cust_credit->unapplied_sql;
4915 my $unapp_pay = FS::cust_pay->unapplied_sql;
4917 my $j = $opt{'join'} || '';
4919 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4920 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4921 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4922 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4924 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4925 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4926 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4927 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4932 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4934 Helper method for balance_date_sql; name (and usage) subject to change
4935 (suggestions welcome).
4937 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4938 cust_refund, cust_credit or cust_pay).
4940 If TABLE is "cust_bill" or the unapplied_date option is true, only
4941 considers records with date earlier than START_TIME, and optionally not
4942 later than END_TIME .
4946 sub _money_table_where {
4947 my( $class, $table, $start, $end, %opt ) = @_;
4950 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4951 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4952 push @where, "$table._date <= $start" if defined($start) && length($start);
4953 push @where, "$table._date > $end" if defined($end) && length($end);
4955 push @where, @{$opt{'where'}} if $opt{'where'};
4956 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4962 =item search_sql HASHREF
4966 Returns a qsearch hash expression to search for parameters specified in HREF.
4967 Valid parameters are
4975 =item cancelled_pkgs
4981 listref of start date, end date
4987 =item current_balance
4989 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
4993 =item flattened_pkgs
5002 my ($class, $params) = @_;
5013 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5015 "cust_main.agentnum = $1";
5022 #prospect active inactive suspended cancelled
5023 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5024 my $method = $params->{'status'}. '_sql';
5025 #push @where, $class->$method();
5026 push @where, FS::cust_main->$method();
5030 # parse cancelled package checkbox
5035 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5036 unless $params->{'cancelled_pkgs'};
5042 foreach my $field (qw( signupdate )) {
5044 next unless exists($params->{$field});
5046 my($beginning, $ending) = @{$params->{$field}};
5049 "cust_main.$field IS NOT NULL",
5050 "cust_main.$field >= $beginning",
5051 "cust_main.$field <= $ending";
5053 $orderby ||= "ORDER BY cust_main.$field";
5061 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5063 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5070 #my $balance_sql = $class->balance_sql();
5071 my $balance_sql = FS::cust_main->balance_sql();
5073 push @where, map { s/current_balance/$balance_sql/; $_ }
5074 @{ $params->{'current_balance'} };
5080 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
5082 "cust_main.custbatch = '$1'";
5086 # setup queries, subs, etc. for the search
5089 $orderby ||= 'ORDER BY custnum';
5091 # here is the agent virtualization
5092 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5094 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5096 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5098 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5100 my $select = join(', ',
5101 'cust_main.custnum',
5102 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5105 my(@extra_headers) = ();
5106 my(@extra_fields) = ();
5108 if ($params->{'flattened_pkgs'}) {
5110 if ($dbh->{Driver}->{Name} eq 'Pg') {
5112 $select .= ", array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
5114 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5115 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5116 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5118 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5119 "omitting packing information from report.";
5122 my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
5124 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5125 $sth->execute() or die $sth->errstr;
5126 my $headerrow = $sth->fetchrow_arrayref;
5127 my $headercount = $headerrow ? $headerrow->[0] : 0;
5128 while($headercount) {
5129 unshift @extra_headers, "Package ". $headercount;
5130 unshift @extra_fields, eval q!sub {my $c = shift;
5131 my @a = split '\|', $c->magic;
5132 my $p = $a[!.--$headercount. q!];
5140 'table' => 'cust_main',
5141 'select' => $select,
5143 'extra_sql' => $extra_sql,
5144 'order_by' => $orderby,
5145 'count_query' => $count_query,
5146 'extra_headers' => \@extra_headers,
5147 'extra_fields' => \@extra_fields,
5152 =item email_search_sql HASHREF
5156 Emails a notice to the specified customers.
5158 Valid parameters are those of the L<search_sql> method, plus the following:
5180 Optional job queue job for status updates.
5184 Returns an error message, or false for success.
5186 If an error occurs during any email, stops the enture send and returns that
5187 error. Presumably if you're getting SMTP errors aborting is better than
5188 retrying everything.
5192 sub email_search_sql {
5193 my($class, $params) = @_;
5195 my $from = delete $params->{from};
5196 my $subject = delete $params->{subject};
5197 my $html_body = delete $params->{html_body};
5198 my $text_body = delete $params->{text_body};
5200 my $job = delete $params->{'job'};
5202 $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
5203 unless ref($params->{'payby'});
5205 my $sql_query = $class->search_sql($params);
5207 my $count_query = delete($sql_query->{'count_query'});
5208 my $count_sth = dbh->prepare($count_query)
5209 or die "Error preparing $count_query: ". dbh->errstr;
5211 or die "Error executing $count_query: ". $count_sth->errstr;
5212 my $count_arrayref = $count_sth->fetchrow_arrayref;
5213 my $num_cust = $count_arrayref->[0];
5215 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5216 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5219 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5221 #eventually order+limit magic to reduce memory use?
5222 foreach my $cust_main ( qsearch($sql_query) ) {
5224 my $to = $cust_main->invoicing_list_emailonly_scalar;
5227 my $error = send_email(
5231 'subject' => $subject,
5232 'html_body' => $html_body,
5233 'text_body' => $text_body,
5236 return $error if $error;
5238 if ( $job ) { #progressbar foo
5240 if ( time - $min_sec > $last ) {
5241 my $error = $job->update_statustext(
5242 int( 100 * $num / $num_cust )
5244 die $error if $error;
5254 use Storable qw(thaw);
5257 sub process_email_search_sql {
5259 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5261 my $param = thaw(decode_base64(shift));
5262 warn Dumper($param) if $DEBUG;
5264 $param->{'job'} = $job;
5266 $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
5267 unless ref($param->{'payby'});
5269 my $error = FS::cust_main->email_search_sql( $param );
5270 die $error if $error;
5274 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5276 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5277 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5278 appropriate ship_ field is also searched).
5280 Additional options are the same as FS::Record::qsearch
5285 my( $self, $fuzzy, $hash, @opt) = @_;
5290 check_and_rebuild_fuzzyfiles();
5291 foreach my $field ( keys %$fuzzy ) {
5293 my $all = $self->all_X($field);
5294 next unless scalar(@$all);
5297 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5300 foreach ( keys %match ) {
5301 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5302 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5305 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5308 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5310 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5318 Returns a masked version of the named field
5323 my ($self, $field) = @_;
5327 'x'x(length($self->getfield($field))-4).
5328 substr($self->getfield($field), (length($self->getfield($field))-4));
5338 =item smart_search OPTION => VALUE ...
5340 Accepts the following options: I<search>, the string to search for. The string
5341 will be searched for as a customer number, phone number, name or company name,
5342 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5343 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5344 skip fuzzy matching when an exact match is found.
5346 Any additional options are treated as an additional qualifier on the search
5349 Returns a (possibly empty) array of FS::cust_main objects.
5356 #here is the agent virtualization
5357 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5361 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5362 my $search = delete $options{'search'};
5363 ( my $alphanum_search = $search ) =~ s/\W//g;
5365 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5367 #false laziness w/Record::ut_phone
5368 my $phonen = "$1-$2-$3";
5369 $phonen .= " x$4" if $4;
5371 push @cust_main, qsearch( {
5372 'table' => 'cust_main',
5373 'hashref' => { %options },
5374 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5376 join(' OR ', map "$_ = '$phonen'",
5377 qw( daytime night fax
5378 ship_daytime ship_night ship_fax )
5381 " AND $agentnums_sql", #agent virtualization
5384 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5385 #try looking for matches with extensions unless one was specified
5387 push @cust_main, qsearch( {
5388 'table' => 'cust_main',
5389 'hashref' => { %options },
5390 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5392 join(' OR ', map "$_ LIKE '$phonen\%'",
5394 ship_daytime ship_night )
5397 " AND $agentnums_sql", #agent virtualization
5402 # custnum search (also try agent_custid), with some tweaking options if your
5403 # legacy cust "numbers" have letters
5404 } elsif ( $search =~ /^\s*(\d+)\s*$/
5405 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5406 && $search =~ /^\s*(\w\w?\d+)\s*$/
5411 push @cust_main, qsearch( {
5412 'table' => 'cust_main',
5413 'hashref' => { 'custnum' => $1, %options },
5414 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5417 push @cust_main, qsearch( {
5418 'table' => 'cust_main',
5419 'hashref' => { 'agent_custid' => $1, %options },
5420 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5423 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5425 my($company, $last, $first) = ( $1, $2, $3 );
5427 # "Company (Last, First)"
5428 #this is probably something a browser remembered,
5429 #so just do an exact search
5431 foreach my $prefix ( '', 'ship_' ) {
5432 push @cust_main, qsearch( {
5433 'table' => 'cust_main',
5434 'hashref' => { $prefix.'first' => $first,
5435 $prefix.'last' => $last,
5436 $prefix.'company' => $company,
5439 'extra_sql' => " AND $agentnums_sql",
5443 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5444 # try (ship_){last,company}
5448 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5449 # # full strings the browser remembers won't work
5450 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5452 use Lingua::EN::NameParse;
5453 my $NameParse = new Lingua::EN::NameParse(
5455 allow_reversed => 1,
5458 my($last, $first) = ( '', '' );
5459 #maybe disable this too and just rely on NameParse?
5460 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5462 ($last, $first) = ( $1, $2 );
5464 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5465 } elsif ( ! $NameParse->parse($value) ) {
5467 my %name = $NameParse->components;
5468 $first = $name{'given_name_1'};
5469 $last = $name{'surname_1'};
5473 if ( $first && $last ) {
5475 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5478 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5480 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5481 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5484 push @cust_main, qsearch( {
5485 'table' => 'cust_main',
5486 'hashref' => \%options,
5487 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5490 # or it just be something that was typed in... (try that in a sec)
5494 my $q_value = dbh->quote($value);
5497 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5498 $sql .= " ( LOWER(last) = $q_value
5499 OR LOWER(company) = $q_value
5500 OR LOWER(ship_last) = $q_value
5501 OR LOWER(ship_company) = $q_value
5504 push @cust_main, qsearch( {
5505 'table' => 'cust_main',
5506 'hashref' => \%options,
5507 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5510 #always do substring & fuzzy,
5511 #getting complains searches are not returning enough
5512 unless ( @cust_main && $skip_fuzzy ) { #no exact match, trying substring/fuzzy
5514 #still some false laziness w/search_sql (was search/cust_main.cgi)
5519 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
5520 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5523 if ( $first && $last ) {
5526 { 'first' => { op=>'ILIKE', value=>"%$first%" },
5527 'last' => { op=>'ILIKE', value=>"%$last%" },
5529 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
5530 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
5537 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
5538 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
5542 foreach my $hashref ( @hashrefs ) {
5544 push @cust_main, qsearch( {
5545 'table' => 'cust_main',
5546 'hashref' => { %$hashref,
5549 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
5558 " AND $agentnums_sql", #extra_sql #agent virtualization
5561 if ( $first && $last ) {
5562 push @cust_main, FS::cust_main->fuzzy_search(
5563 { 'last' => $last, #fuzzy hashref
5564 'first' => $first }, #
5568 foreach my $field ( 'last', 'company' ) {
5570 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
5577 #eliminate duplicates
5579 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5587 Accepts the following options: I<email>, the email address to search for. The
5588 email address will be searched for as an email invoice destination and as an
5591 #Any additional options are treated as an additional qualifier on the search
5592 #(i.e. I<agentnum>).
5594 Returns a (possibly empty) array of FS::cust_main objects (but usually just
5604 my $email = delete $options{'email'};
5606 #we're only being used by RT at the moment... no agent virtualization yet
5607 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5611 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
5613 my ( $user, $domain ) = ( $1, $2 );
5615 warn "$me smart_search: searching for $user in domain $domain"
5621 'table' => 'cust_main_invoice',
5622 'hashref' => { 'dest' => $email },
5629 map $_->cust_svc->cust_pkg,
5631 'table' => 'svc_acct',
5632 'hashref' => { 'username' => $user, },
5634 'AND ( SELECT domain FROM svc_domain
5635 WHERE svc_acct.domsvc = svc_domain.svcnum
5636 ) = '. dbh->quote($domain),
5642 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5644 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
5651 =item check_and_rebuild_fuzzyfiles
5655 use vars qw(@fuzzyfields);
5656 @fuzzyfields = ( 'last', 'first', 'company' );
5658 sub check_and_rebuild_fuzzyfiles {
5659 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5660 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
5663 =item rebuild_fuzzyfiles
5667 sub rebuild_fuzzyfiles {
5669 use Fcntl qw(:flock);
5671 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5672 mkdir $dir, 0700 unless -d $dir;
5674 foreach my $fuzzy ( @fuzzyfields ) {
5676 open(LOCK,">>$dir/cust_main.$fuzzy")
5677 or die "can't open $dir/cust_main.$fuzzy: $!";
5679 or die "can't lock $dir/cust_main.$fuzzy: $!";
5681 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
5682 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
5684 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
5685 my $sth = dbh->prepare("SELECT $field FROM cust_main".
5686 " WHERE $field != '' AND $field IS NOT NULL");
5687 $sth->execute or die $sth->errstr;
5689 while ( my $row = $sth->fetchrow_arrayref ) {
5690 print CACHE $row->[0]. "\n";
5695 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
5697 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
5708 my( $self, $field ) = @_;
5709 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5710 open(CACHE,"<$dir/cust_main.$field")
5711 or die "can't open $dir/cust_main.$field: $!";
5712 my @array = map { chomp; $_; } <CACHE>;
5717 =item append_fuzzyfiles LASTNAME COMPANY
5721 sub append_fuzzyfiles {
5722 #my( $first, $last, $company ) = @_;
5724 &check_and_rebuild_fuzzyfiles;
5726 use Fcntl qw(:flock);
5728 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5730 foreach my $field (qw( first last company )) {
5735 open(CACHE,">>$dir/cust_main.$field")
5736 or die "can't open $dir/cust_main.$field: $!";
5737 flock(CACHE,LOCK_EX)
5738 or die "can't lock $dir/cust_main.$field: $!";
5740 print CACHE "$value\n";
5742 flock(CACHE,LOCK_UN)
5743 or die "can't unlock $dir/cust_main.$field: $!";
5752 =item process_batch_import
5754 Load a batch import as a queued JSRPC job
5758 use Storable qw(thaw);
5761 sub process_batch_import {
5764 my $param = thaw(decode_base64(shift));
5765 warn Dumper($param) if $DEBUG;
5767 my $files = $param->{'uploaded_files'}
5768 or die "No files provided.\n";
5770 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
5772 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
5773 my $file = $dir. $files{'file'};
5776 if ( $file =~ /\.(\w+)$/i ) {
5780 warn "can't parse file type from filename $file; defaulting to CSV";
5785 FS::cust_main::batch_import( {
5789 custbatch => $param->{custbatch},
5790 agentnum => $param->{'agentnum'},
5791 refnum => $param->{'refnum'},
5792 pkgpart => $param->{'pkgpart'},
5793 #'fields' => [qw( cust_pkg.setup dayphone first last address1 address2
5794 # city state zip comments )],
5795 'format' => $param->{'format'},
5800 die "$error\n" if $error;
5808 #some false laziness w/cdr.pm now
5812 my $job = $param->{job};
5814 my $filename = $param->{file};
5815 my $type = $param->{type} || 'csv';
5817 my $custbatch = $param->{custbatch};
5819 my $agentnum = $param->{agentnum};
5820 my $refnum = $param->{refnum};
5821 my $pkgpart = $param->{pkgpart};
5823 my $format = $param->{'format'};
5827 if ( $format eq 'simple' ) {
5828 @fields = qw( cust_pkg.setup dayphone first last
5829 address1 address2 city state zip comments );
5831 } elsif ( $format eq 'extended' ) {
5832 @fields = qw( agent_custid refnum
5833 last first address1 address2 city state zip country
5835 ship_last ship_first ship_address1 ship_address2
5836 ship_city ship_state ship_zip ship_country
5837 payinfo paycvv paydate
5840 svc_acct.username svc_acct._password
5843 } elsif ( $format eq 'extended-plus_company' ) {
5844 @fields = qw( agent_custid refnum
5845 last first company address1 address2 city state zip country
5847 ship_last ship_first ship_company ship_address1 ship_address2
5848 ship_city ship_state ship_zip ship_country
5849 payinfo paycvv paydate
5852 svc_acct.username svc_acct._password
5856 die "unknown format $format";
5862 if ( $type eq 'csv' ) {
5864 eval "use Text::CSV_XS;";
5867 $parser = new Text::CSV_XS;
5869 @buffer = split(/\r?\n/, slurp($filename) );
5870 $count = scalar(@buffer);
5872 } elsif ( $type eq 'xls' ) {
5874 eval "use Spreadsheet::ParseExcel;";
5877 my $excel = new Spreadsheet::ParseExcel::Workbook->Parse($filename);
5878 $parser = $excel->{Worksheet}[0]; #first sheet
5880 $count = $parser->{MaxRow} || $parser->{MinRow};
5884 die "Unknown file type $type\n";
5889 local $SIG{HUP} = 'IGNORE';
5890 local $SIG{INT} = 'IGNORE';
5891 local $SIG{QUIT} = 'IGNORE';
5892 local $SIG{TERM} = 'IGNORE';
5893 local $SIG{TSTP} = 'IGNORE';
5894 local $SIG{PIPE} = 'IGNORE';
5896 my $oldAutoCommit = $FS::UID::AutoCommit;
5897 local $FS::UID::AutoCommit = 0;
5902 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
5906 if ( $type eq 'csv' ) {
5908 last unless scalar(@buffer);
5909 $line = shift(@buffer);
5911 $parser->parse($line) or do {
5912 $dbh->rollback if $oldAutoCommit;
5913 return "can't parse: ". $parser->error_input();
5915 @columns = $parser->fields();
5917 } elsif ( $type eq 'xls' ) {
5919 last if $row > ($parser->{MaxRow} || $parser->{MinRow});
5921 my @row = @{ $parser->{Cells}[$row] };
5922 @columns = map $_->{Val}, @row;
5925 #warn $z++. ": $_\n" for @columns;
5928 die "Unknown file type $type\n";
5931 #warn join('-',@columns);
5934 custbatch => $custbatch,
5935 agentnum => $agentnum,
5937 country => $conf->config('countrydefault') || 'US',
5938 payby => $payby, #default
5939 paydate => '12/2037', #default
5941 my $billtime = time;
5942 my %cust_pkg = ( pkgpart => $pkgpart );
5944 foreach my $field ( @fields ) {
5946 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
5948 #$cust_pkg{$1} = str2time( shift @$columns );
5949 if ( $1 eq 'pkgpart' ) {
5950 $cust_pkg{$1} = shift @columns;
5951 } elsif ( $1 eq 'setup' ) {
5952 $billtime = str2time(shift @columns);
5954 $cust_pkg{$1} = str2time( shift @columns );
5957 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
5959 $svc_acct{$1} = shift @columns;
5963 #refnum interception
5964 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
5966 my $referral = $columns[0];
5967 my %hash = ( 'referral' => $referral,
5968 'agentnum' => $agentnum,
5972 my $part_referral = qsearchs('part_referral', \%hash )
5973 || new FS::part_referral \%hash;
5975 unless ( $part_referral->refnum ) {
5976 my $error = $part_referral->insert;
5978 $dbh->rollback if $oldAutoCommit;
5979 return "can't auto-insert advertising source: $referral: $error";
5983 $columns[0] = $part_referral->refnum;
5986 my $value = shift @columns;
5987 $cust_main{$field} = $value if length($value);
5991 $cust_main{'payby'} = 'CARD'
5992 if defined $cust_main{'payinfo'}
5993 && length $cust_main{'payinfo'};
5995 my $invoicing_list = $cust_main{'invoicing_list'}
5996 ? [ delete $cust_main{'invoicing_list'} ]
5999 my $cust_main = new FS::cust_main ( \%cust_main );
6002 tie my %hash, 'Tie::RefHash'; #this part is important
6004 if ( $cust_pkg{'pkgpart'} ) {
6005 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
6008 if ( $svc_acct{'username'} ) {
6009 my $part_pkg = $cust_pkg->part_pkg;
6010 unless ( $part_pkg ) {
6011 $dbh->rollback if $oldAutoCommit;
6012 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
6014 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
6015 push @svc_acct, new FS::svc_acct ( \%svc_acct )
6018 $hash{$cust_pkg} = \@svc_acct;
6021 my $error = $cust_main->insert( \%hash, $invoicing_list );
6024 $dbh->rollback if $oldAutoCommit;
6025 return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
6028 if ( $format eq 'simple' ) {
6030 #false laziness w/bill.cgi
6031 $error = $cust_main->bill( 'time' => $billtime );
6033 $dbh->rollback if $oldAutoCommit;
6034 return "can't bill customer for $line: $error";
6037 $error = $cust_main->apply_payments_and_credits;
6039 $dbh->rollback if $oldAutoCommit;
6040 return "can't bill customer for $line: $error";
6043 $error = $cust_main->collect();
6045 $dbh->rollback if $oldAutoCommit;
6046 return "can't collect customer for $line: $error";
6053 if ( $job && time - $min_sec > $last ) { #progress bar
6054 $job->update_statustext( int(100 * $row / $count) );
6060 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
6062 return "Empty file!" unless $row;
6074 #warn join('-',keys %$param);
6075 my $fh = $param->{filehandle};
6076 my @fields = @{$param->{fields}};
6078 eval "use Text::CSV_XS;";
6081 my $csv = new Text::CSV_XS;
6088 local $SIG{HUP} = 'IGNORE';
6089 local $SIG{INT} = 'IGNORE';
6090 local $SIG{QUIT} = 'IGNORE';
6091 local $SIG{TERM} = 'IGNORE';
6092 local $SIG{TSTP} = 'IGNORE';
6093 local $SIG{PIPE} = 'IGNORE';
6095 my $oldAutoCommit = $FS::UID::AutoCommit;
6096 local $FS::UID::AutoCommit = 0;
6099 #while ( $columns = $csv->getline($fh) ) {
6101 while ( defined($line=<$fh>) ) {
6103 $csv->parse($line) or do {
6104 $dbh->rollback if $oldAutoCommit;
6105 return "can't parse: ". $csv->error_input();
6108 my @columns = $csv->fields();
6109 #warn join('-',@columns);
6112 foreach my $field ( @fields ) {
6113 $row{$field} = shift @columns;
6116 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6117 unless ( $cust_main ) {
6118 $dbh->rollback if $oldAutoCommit;
6119 return "unknown custnum $row{'custnum'}";
6122 if ( $row{'amount'} > 0 ) {
6123 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6125 $dbh->rollback if $oldAutoCommit;
6129 } elsif ( $row{'amount'} < 0 ) {
6130 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6133 $dbh->rollback if $oldAutoCommit;
6143 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6145 return "Empty file!" unless $imported;
6151 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6153 Sends a templated email notification to the customer (see L<Text::Template>).
6155 OPTIONS is a hash and may include
6157 I<from> - the email sender (default is invoice_from)
6159 I<to> - comma-separated scalar or arrayref of recipients
6160 (default is invoicing_list)
6162 I<subject> - The subject line of the sent email notification
6163 (default is "Notice from company_name")
6165 I<extra_fields> - a hashref of name/value pairs which will be substituted
6168 The following variables are vavailable in the template.
6170 I<$first> - the customer first name
6171 I<$last> - the customer last name
6172 I<$company> - the customer company
6173 I<$payby> - a description of the method of payment for the customer
6174 # would be nice to use FS::payby::shortname
6175 I<$payinfo> - the account information used to collect for this customer
6176 I<$expdate> - the expiration of the customer payment in seconds from epoch
6181 my ($customer, $template, %options) = @_;
6183 return unless $conf->exists($template);
6185 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6186 $from = $options{from} if exists($options{from});
6188 my $to = join(',', $customer->invoicing_list_emailonly);
6189 $to = $options{to} if exists($options{to});
6191 my $subject = "Notice from " . $conf->config('company_name')
6192 if $conf->exists('company_name');
6193 $subject = $options{subject} if exists($options{subject});
6195 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6196 SOURCE => [ map "$_\n",
6197 $conf->config($template)]
6199 or die "can't create new Text::Template object: Text::Template::ERROR";
6200 $notify_template->compile()
6201 or die "can't compile template: Text::Template::ERROR";
6203 my $paydate = $customer->paydate || '2037-12-31';
6204 $FS::notify_template::_template::first = $customer->first;
6205 $FS::notify_template::_template::last = $customer->last;
6206 $FS::notify_template::_template::company = $customer->company;
6207 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6208 my $payby = $customer->payby;
6209 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6210 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6212 #credit cards expire at the end of the month/year of their exp date
6213 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6214 $FS::notify_template::_template::payby = 'credit card';
6215 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6216 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6218 }elsif ($payby eq 'COMP') {
6219 $FS::notify_template::_template::payby = 'complimentary account';
6221 $FS::notify_template::_template::payby = 'current method';
6223 $FS::notify_template::_template::expdate = $expire_time;
6225 for (keys %{$options{extra_fields}}){
6227 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6230 send_email(from => $from,
6232 subject => $subject,
6233 body => $notify_template->fill_in( PACKAGE =>
6234 'FS::notify_template::_template' ),
6239 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6241 Generates a templated notification to the customer (see L<Text::Template>).
6243 OPTIONS is a hash and may include
6245 I<extra_fields> - a hashref of name/value pairs which will be substituted
6246 into the template. These values may override values mentioned below
6247 and those from the customer record.
6249 The following variables are available in the template instead of or in addition
6250 to the fields of the customer record.
6252 I<$payby> - a description of the method of payment for the customer
6253 # would be nice to use FS::payby::shortname
6254 I<$payinfo> - the masked account information used to collect for this customer
6255 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6256 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress
6260 sub generate_letter {
6261 my ($self, $template, %options) = @_;
6263 return unless $conf->exists($template);
6265 my $letter_template = new Text::Template
6267 SOURCE => [ map "$_\n", $conf->config($template)],
6268 DELIMITERS => [ '[@--', '--@]' ],
6270 or die "can't create new Text::Template object: Text::Template::ERROR";
6272 $letter_template->compile()
6273 or die "can't compile template: Text::Template::ERROR";
6275 my %letter_data = map { $_ => $self->$_ } $self->fields;
6276 $letter_data{payinfo} = $self->mask_payinfo;
6278 my $paydate = $self->paydate || '2037-12-31';
6279 my $payby = $self->payby;
6280 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6281 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6283 #credit cards expire at the end of the month/year of their exp date
6284 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6285 $letter_data{payby} = 'credit card';
6286 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6287 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6289 }elsif ($payby eq 'COMP') {
6290 $letter_data{payby} = 'complimentary account';
6292 $letter_data{payby} = 'current method';
6294 $letter_data{expdate} = $expire_time;
6296 for (keys %{$options{extra_fields}}){
6297 $letter_data{$_} = $options{extra_fields}->{$_};
6300 unless(exists($letter_data{returnaddress})){
6301 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6302 $self->_agent_template)
6305 $letter_data{returnaddress} = length($retadd) ? $retadd : '~';
6308 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6310 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6311 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6315 ) or die "can't open temp file: $!\n";
6317 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6319 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6323 =item print_ps TEMPLATE
6325 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6331 my $file = $self->generate_letter(@_);
6332 FS::Misc::generate_ps($file);
6335 =item print TEMPLATE
6337 Prints the filled in template.
6339 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6343 sub queueable_print {
6346 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6347 or die "invalid customer number: " . $opt{custvnum};
6349 my $error = $self->print( $opt{template} );
6350 die $error if $error;
6354 my ($self, $template) = (shift, shift);
6355 do_print [ $self->print_ps($template) ];
6358 sub agent_template {
6360 $self->_agent_plandata('agent_templatename');
6363 sub agent_invoice_from {
6365 $self->_agent_plandata('agent_invoice_from');
6368 sub _agent_plandata {
6369 my( $self, $option ) = @_;
6372 if ( driver_name =~ /^Pg/i ) {
6374 } elsif ( driver_name =~ /^mysql/i ) {
6377 die "don't know how to use regular expressions in ". driver_name. " databases";
6380 my $part_bill_event = qsearchs( 'part_bill_event',
6382 'payby' => $self->payby,
6383 'plan' => 'send_agent',
6384 'plandata' => { 'op' => $regexp,
6385 'value' => "(^|\n)agentnum ".
6393 'ORDER BY seconds LIMIT 1'
6396 return '' unless $part_bill_event;
6398 if ( $part_bill_event->plandata =~ /^$option (.*)$/m ) {
6401 warn "can't parse part_bill_event eventpart#". $part_bill_event->eventpart.
6402 " plandata for $option";
6409 ## actual sub, not a method, designed to be called from the queue.
6410 ## sets up the customer, and calls the bill_and_collect
6411 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6412 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6413 $cust_main->bill_and_collect(
6418 sub _upgrade_data { #class method
6419 my ($class, %opts) = @_;
6421 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
6422 my $sth = dbh->prepare($sql) or die dbh->errstr;
6423 $sth->execute or die $sth->errstr;
6433 The delete method should possibly take an FS::cust_main object reference
6434 instead of a scalar customer number.
6436 Bill and collect options should probably be passed as references instead of a
6439 There should probably be a configuration file with a list of allowed credit
6442 No multiple currency support (probably a larger project than just this module).
6444 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6446 Birthdates rely on negative epoch values.
6448 The payby for card/check batches is broken. With mixed batching, bad
6453 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6454 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6455 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.