5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 use Scalar::Util qw( blessed );
12 use Time::Local qw(timelocal_nocheck);
15 use Digest::MD5 qw(md5_base64);
19 use File::Slurp qw( slurp );
20 use File::Temp qw( tempfile );
21 use String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
24 use FS::UID qw( getotaker dbh driver_name );
25 use FS::Record qw( qsearchs qsearch dbdef );
26 use FS::Misc qw( generate_email send_email generate_ps do_print );
27 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
32 use FS::cust_bill_pkg_display;
34 use FS::cust_pay_pending;
35 use FS::cust_pay_void;
36 use FS::cust_pay_batch;
39 use FS::part_referral;
40 use FS::cust_main_county;
41 use FS::cust_tax_location;
43 use FS::cust_main_invoice;
44 use FS::cust_credit_bill;
45 use FS::cust_bill_pay;
46 use FS::prepay_credit;
50 use FS::part_event_condition;
53 use FS::payment_gateway;
54 use FS::agent_payment_gateway;
56 use FS::payinfo_Mixin;
59 @ISA = qw( FS::payinfo_Mixin FS::Record );
61 @EXPORT_OK = qw( smart_search );
63 $realtime_bop_decline_quiet = 0;
65 # 1 is mostly method/subroutine entry and options
66 # 2 traces progress of some operations
67 # 3 is even more information including possibly sensitive data
69 $me = '[FS::cust_main]';
73 $ignore_expired_card = 0;
75 @encrypted_fields = ('payinfo', 'paycvv');
76 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
78 #ask FS::UID to run this stuff for us later
79 #$FS::UID::callback{'FS::cust_main'} = sub {
80 install_callback FS::UID sub {
82 #yes, need it for stuff below (prolly should be cached)
87 my ( $hashref, $cache ) = @_;
88 if ( exists $hashref->{'pkgnum'} ) {
89 #@{ $self->{'_pkgnum'} } = ();
90 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
91 $self->{'_pkgnum'} = $subcache;
92 #push @{ $self->{'_pkgnum'} },
93 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
99 FS::cust_main - Object methods for cust_main records
105 $record = new FS::cust_main \%hash;
106 $record = new FS::cust_main { 'column' => 'value' };
108 $error = $record->insert;
110 $error = $new_record->replace($old_record);
112 $error = $record->delete;
114 $error = $record->check;
116 @cust_pkg = $record->all_pkgs;
118 @cust_pkg = $record->ncancelled_pkgs;
120 @cust_pkg = $record->suspended_pkgs;
122 $error = $record->bill;
123 $error = $record->bill %options;
124 $error = $record->bill 'time' => $time;
126 $error = $record->collect;
127 $error = $record->collect %options;
128 $error = $record->collect 'invoice_time' => $time,
133 An FS::cust_main object represents a customer. FS::cust_main inherits from
134 FS::Record. The following fields are currently supported:
138 =item custnum - primary key (assigned automatically for new customers)
140 =item agentnum - agent (see L<FS::agent>)
142 =item refnum - Advertising source (see L<FS::part_referral>)
148 =item ss - social security number (optional)
150 =item company - (optional)
154 =item address2 - (optional)
158 =item county - (optional, see L<FS::cust_main_county>)
160 =item state - (see L<FS::cust_main_county>)
164 =item country - (see L<FS::cust_main_county>)
166 =item daytime - phone (optional)
168 =item night - phone (optional)
170 =item fax - phone (optional)
172 =item ship_first - name
174 =item ship_last - name
176 =item ship_company - (optional)
180 =item ship_address2 - (optional)
184 =item ship_county - (optional, see L<FS::cust_main_county>)
186 =item ship_state - (see L<FS::cust_main_county>)
190 =item ship_country - (see L<FS::cust_main_county>)
192 =item ship_daytime - phone (optional)
194 =item ship_night - phone (optional)
196 =item ship_fax - phone (optional)
198 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
200 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
202 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
206 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
208 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
210 =item paystart_month - start date month (maestro/solo cards only)
212 =item paystart_year - start date year (maestro/solo cards only)
214 =item payissue - issue number (maestro/solo cards only)
216 =item payname - name on card or billing name
218 =item payip - IP address from which payment information was received
220 =item tax - tax exempt, empty or `Y'
222 =item otaker - order taker (assigned automatically, see L<FS::UID>)
224 =item comments - comments (optional)
226 =item referral_custnum - referring customer number
228 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
230 =item dundate - a suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
232 =item squelch_cdr - Discourage individual CDR printing, empty or `Y'
242 Creates a new customer. To add the customer to the database, see L<"insert">.
244 Note that this stores the hash reference, not a distinct copy of the hash it
245 points to. You can ask the object for a copy with the I<hash> method.
249 sub table { 'cust_main'; }
251 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
253 Adds this customer to the database. If there is an error, returns the error,
254 otherwise returns false.
256 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
257 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
258 are inserted atomicly, or the transaction is rolled back. Passing an empty
259 hash reference is equivalent to not supplying this parameter. There should be
260 a better explanation of this, but until then, here's an example:
263 tie %hash, 'Tie::RefHash'; #this part is important
265 $cust_pkg => [ $svc_acct ],
268 $cust_main->insert( \%hash );
270 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
271 be set as the invoicing list (see L<"invoicing_list">). Errors return as
272 expected and rollback the entire transaction; it is not necessary to call
273 check_invoicing_list first. The invoicing_list is set after the records in the
274 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
275 invoicing_list destination to the newly-created svc_acct. Here's an example:
277 $cust_main->insert( {}, [ $email, 'POST' ] );
279 Currently available options are: I<depend_jobnum> and I<noexport>.
281 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
282 on the supplied jobnum (they will not run until the specific job completes).
283 This can be used to defer provisioning until some action completes (such
284 as running the customer's credit card successfully).
286 The I<noexport> option is deprecated. If I<noexport> is set true, no
287 provisioning jobs (exports) are scheduled. (You can schedule them later with
288 the B<reexport> method.)
294 my $cust_pkgs = @_ ? shift : {};
295 my $invoicing_list = @_ ? shift : '';
297 warn "$me insert called with options ".
298 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
301 local $SIG{HUP} = 'IGNORE';
302 local $SIG{INT} = 'IGNORE';
303 local $SIG{QUIT} = 'IGNORE';
304 local $SIG{TERM} = 'IGNORE';
305 local $SIG{TSTP} = 'IGNORE';
306 local $SIG{PIPE} = 'IGNORE';
308 my $oldAutoCommit = $FS::UID::AutoCommit;
309 local $FS::UID::AutoCommit = 0;
312 my $prepay_identifier = '';
313 my( $amount, $seconds ) = ( 0, 0 );
315 if ( $self->payby eq 'PREPAY' ) {
317 $self->payby('BILL');
318 $prepay_identifier = $self->payinfo;
321 warn " looking up prepaid card $prepay_identifier\n"
324 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
326 $dbh->rollback if $oldAutoCommit;
327 #return "error applying prepaid card (transaction rolled back): $error";
331 $payby = 'PREP' if $amount;
333 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
336 $self->payby('BILL');
337 $amount = $self->paid;
341 warn " inserting $self\n"
344 $self->signupdate(time) unless $self->signupdate;
346 my $error = $self->SUPER::insert;
348 $dbh->rollback if $oldAutoCommit;
349 #return "inserting cust_main record (transaction rolled back): $error";
353 warn " setting invoicing list\n"
356 if ( $invoicing_list ) {
357 $error = $self->check_invoicing_list( $invoicing_list );
359 $dbh->rollback if $oldAutoCommit;
360 #return "checking invoicing_list (transaction rolled back): $error";
363 $self->invoicing_list( $invoicing_list );
366 if ( $conf->config('cust_main-skeleton_tables')
367 && $conf->config('cust_main-skeleton_custnum') ) {
369 warn " inserting skeleton records\n"
372 my $error = $self->start_copy_skel;
374 $dbh->rollback if $oldAutoCommit;
380 warn " ordering packages\n"
383 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
385 $dbh->rollback if $oldAutoCommit;
390 $dbh->rollback if $oldAutoCommit;
391 return "No svc_acct record to apply pre-paid time";
395 warn " inserting initial $payby payment of $amount\n"
397 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
399 $dbh->rollback if $oldAutoCommit;
400 return "inserting payment (transaction rolled back): $error";
404 unless ( $import || $skip_fuzzyfiles ) {
405 warn " queueing fuzzyfiles update\n"
407 $error = $self->queue_fuzzyfiles_update;
409 $dbh->rollback if $oldAutoCommit;
410 return "updating fuzzy search cache: $error";
414 warn " insert complete; committing transaction\n"
417 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
422 sub start_copy_skel {
425 #'mg_user_preference' => {},
426 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
427 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
428 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
429 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
430 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
433 _copy_skel( 'cust_main', #tablename
434 $conf->config('cust_main-skeleton_custnum'), #sourceid
435 $self->custnum, #destid
436 @tables, #child tables
440 #recursive subroutine, not a method
442 my( $table, $sourceid, $destid, %child_tables ) = @_;
445 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
446 ( $table, $primary_key ) = ( $1, $2 );
448 my $dbdef_table = dbdef->table($table);
449 $primary_key = $dbdef_table->primary_key
450 or return "$table has no primary key".
451 " (or do you need to run dbdef-create?)";
454 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
455 join (', ', keys %child_tables). "\n"
458 foreach my $child_table_def ( keys %child_tables ) {
462 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
463 ( $child_table, $child_pkey ) = ( $1, $2 );
465 $child_table = $child_table_def;
467 $child_pkey = dbdef->table($child_table)->primary_key;
468 # or return "$table has no primary key".
469 # " (or do you need to run dbdef-create?)\n";
473 if ( keys %{ $child_tables{$child_table_def} } ) {
475 return "$child_table has no primary key".
476 " (run dbdef-create or try specifying it?)\n"
479 #false laziness w/Record::insert and only works on Pg
480 #refactor the proper last-inserted-id stuff out of Record::insert if this
481 # ever gets use for anything besides a quick kludge for one customer
482 my $default = dbdef->table($child_table)->column($child_pkey)->default;
483 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
484 or return "can't parse $child_table.$child_pkey default value ".
485 " for sequence name: $default";
490 my @sel_columns = grep { $_ ne $primary_key }
491 dbdef->table($child_table)->columns;
492 my $sel_columns = join(', ', @sel_columns );
494 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
495 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
496 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
498 my $sel_st = "SELECT $sel_columns FROM $child_table".
499 " WHERE $primary_key = $sourceid";
502 my $sel_sth = dbh->prepare( $sel_st )
503 or return dbh->errstr;
505 $sel_sth->execute or return $sel_sth->errstr;
507 while ( my $row = $sel_sth->fetchrow_hashref ) {
509 warn " selected row: ".
510 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
514 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
515 my $ins_sth =dbh->prepare($statement)
516 or return dbh->errstr;
517 my @param = ( $destid, map $row->{$_}, @ins_columns );
518 warn " $statement: [ ". join(', ', @param). " ]\n"
520 $ins_sth->execute( @param )
521 or return $ins_sth->errstr;
523 #next unless keys %{ $child_tables{$child_table} };
524 next unless $sequence;
526 #another section of that laziness
527 my $seq_sql = "SELECT currval('$sequence')";
528 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
529 $seq_sth->execute or return $seq_sth->errstr;
530 my $insertid = $seq_sth->fetchrow_arrayref->[0];
532 # don't drink soap! recurse! recurse! okay!
534 _copy_skel( $child_table_def,
535 $row->{$child_pkey}, #sourceid
537 %{ $child_tables{$child_table_def} },
539 return $error if $error;
549 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
551 Like the insert method on an existing record, this method orders a package
552 and included services atomicaly. Pass a Tie::RefHash data structure to this
553 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
554 be a better explanation of this, but until then, here's an example:
557 tie %hash, 'Tie::RefHash'; #this part is important
559 $cust_pkg => [ $svc_acct ],
562 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
564 Services can be new, in which case they are inserted, or existing unaudited
565 services, in which case they are linked to the newly-created package.
567 Currently available options are: I<depend_jobnum> and I<noexport>.
569 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
570 on the supplied jobnum (they will not run until the specific job completes).
571 This can be used to defer provisioning until some action completes (such
572 as running the customer's credit card successfully).
574 The I<noexport> option is deprecated. If I<noexport> is set true, no
575 provisioning jobs (exports) are scheduled. (You can schedule them later with
576 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
577 on the cust_main object is not recommended, as existing services will also be
584 my $cust_pkgs = shift;
587 my %svc_options = ();
588 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
589 if exists $options{'depend_jobnum'};
590 warn "$me order_pkgs called with options ".
591 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
594 local $SIG{HUP} = 'IGNORE';
595 local $SIG{INT} = 'IGNORE';
596 local $SIG{QUIT} = 'IGNORE';
597 local $SIG{TERM} = 'IGNORE';
598 local $SIG{TSTP} = 'IGNORE';
599 local $SIG{PIPE} = 'IGNORE';
601 my $oldAutoCommit = $FS::UID::AutoCommit;
602 local $FS::UID::AutoCommit = 0;
605 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
607 foreach my $cust_pkg ( keys %$cust_pkgs ) {
608 $cust_pkg->custnum( $self->custnum );
609 my $error = $cust_pkg->insert;
611 $dbh->rollback if $oldAutoCommit;
612 return "inserting cust_pkg (transaction rolled back): $error";
614 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
615 if ( $svc_something->svcnum ) {
616 my $old_cust_svc = $svc_something->cust_svc;
617 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
618 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
619 $error = $new_cust_svc->replace($old_cust_svc);
621 $svc_something->pkgnum( $cust_pkg->pkgnum );
622 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
623 $svc_something->seconds( $svc_something->seconds + $$seconds );
626 $error = $svc_something->insert(%svc_options);
629 $dbh->rollback if $oldAutoCommit;
630 #return "inserting svc_ (transaction rolled back): $error";
636 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
640 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
642 Recharges this (existing) customer with the specified prepaid card (see
643 L<FS::prepay_credit>), specified either by I<identifier> or as an
644 FS::prepay_credit object. If there is an error, returns the error, otherwise
647 Optionally, four scalar references can be passed as well. They will have their
648 values filled in with the amount, number of seconds, and number of upload and
649 download bytes applied by this prepaid
654 sub recharge_prepay {
655 my( $self, $prepay_credit, $amountref, $secondsref,
656 $upbytesref, $downbytesref, $totalbytesref ) = @_;
658 local $SIG{HUP} = 'IGNORE';
659 local $SIG{INT} = 'IGNORE';
660 local $SIG{QUIT} = 'IGNORE';
661 local $SIG{TERM} = 'IGNORE';
662 local $SIG{TSTP} = 'IGNORE';
663 local $SIG{PIPE} = 'IGNORE';
665 my $oldAutoCommit = $FS::UID::AutoCommit;
666 local $FS::UID::AutoCommit = 0;
669 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
671 my $error = $self->get_prepay($prepay_credit, \$amount,
672 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
673 || $self->increment_seconds($seconds)
674 || $self->increment_upbytes($upbytes)
675 || $self->increment_downbytes($downbytes)
676 || $self->increment_totalbytes($totalbytes)
677 || $self->insert_cust_pay_prepay( $amount,
679 ? $prepay_credit->identifier
684 $dbh->rollback if $oldAutoCommit;
688 if ( defined($amountref) ) { $$amountref = $amount; }
689 if ( defined($secondsref) ) { $$secondsref = $seconds; }
690 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
691 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
692 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
694 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
699 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
701 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
702 specified either by I<identifier> or as an FS::prepay_credit object.
704 References to I<amount> and I<seconds> scalars should be passed as arguments
705 and will be incremented by the values of the prepaid card.
707 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
708 check or set this customer's I<agentnum>.
710 If there is an error, returns the error, otherwise returns false.
716 my( $self, $prepay_credit, $amountref, $secondsref,
717 $upref, $downref, $totalref) = @_;
719 local $SIG{HUP} = 'IGNORE';
720 local $SIG{INT} = 'IGNORE';
721 local $SIG{QUIT} = 'IGNORE';
722 local $SIG{TERM} = 'IGNORE';
723 local $SIG{TSTP} = 'IGNORE';
724 local $SIG{PIPE} = 'IGNORE';
726 my $oldAutoCommit = $FS::UID::AutoCommit;
727 local $FS::UID::AutoCommit = 0;
730 unless ( ref($prepay_credit) ) {
732 my $identifier = $prepay_credit;
734 $prepay_credit = qsearchs(
736 { 'identifier' => $prepay_credit },
741 unless ( $prepay_credit ) {
742 $dbh->rollback if $oldAutoCommit;
743 return "Invalid prepaid card: ". $identifier;
748 if ( $prepay_credit->agentnum ) {
749 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
750 $dbh->rollback if $oldAutoCommit;
751 return "prepaid card not valid for agent ". $self->agentnum;
753 $self->agentnum($prepay_credit->agentnum);
756 my $error = $prepay_credit->delete;
758 $dbh->rollback if $oldAutoCommit;
759 return "removing prepay_credit (transaction rolled back): $error";
762 $$amountref += $prepay_credit->amount;
763 $$secondsref += $prepay_credit->seconds;
764 $$upref += $prepay_credit->upbytes;
765 $$downref += $prepay_credit->downbytes;
766 $$totalref += $prepay_credit->totalbytes;
768 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
773 =item increment_upbytes SECONDS
775 Updates this customer's single or primary account (see L<FS::svc_acct>) by
776 the specified number of upbytes. If there is an error, returns the error,
777 otherwise returns false.
781 sub increment_upbytes {
782 _increment_column( shift, 'upbytes', @_);
785 =item increment_downbytes SECONDS
787 Updates this customer's single or primary account (see L<FS::svc_acct>) by
788 the specified number of downbytes. If there is an error, returns the error,
789 otherwise returns false.
793 sub increment_downbytes {
794 _increment_column( shift, 'downbytes', @_);
797 =item increment_totalbytes SECONDS
799 Updates this customer's single or primary account (see L<FS::svc_acct>) by
800 the specified number of totalbytes. If there is an error, returns the error,
801 otherwise returns false.
805 sub increment_totalbytes {
806 _increment_column( shift, 'totalbytes', @_);
809 =item increment_seconds SECONDS
811 Updates this customer's single or primary account (see L<FS::svc_acct>) by
812 the specified number of seconds. If there is an error, returns the error,
813 otherwise returns false.
817 sub increment_seconds {
818 _increment_column( shift, 'seconds', @_);
821 =item _increment_column AMOUNT
823 Updates this customer's single or primary account (see L<FS::svc_acct>) by
824 the specified number of seconds or bytes. If there is an error, returns
825 the error, otherwise returns false.
829 sub _increment_column {
830 my( $self, $column, $amount ) = @_;
831 warn "$me increment_column called: $column, $amount\n"
834 return '' unless $amount;
836 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
837 $self->ncancelled_pkgs;
840 return 'No packages with primary or single services found'.
841 ' to apply pre-paid time';
842 } elsif ( scalar(@cust_pkg) > 1 ) {
843 #maybe have a way to specify the package/account?
844 return 'Multiple packages found to apply pre-paid time';
847 my $cust_pkg = $cust_pkg[0];
848 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
852 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
855 return 'No account found to apply pre-paid time';
856 } elsif ( scalar(@cust_svc) > 1 ) {
857 return 'Multiple accounts found to apply pre-paid time';
860 my $svc_acct = $cust_svc[0]->svc_x;
861 warn " found service svcnum ". $svc_acct->pkgnum.
862 ' ('. $svc_acct->email. ")\n"
865 $column = "increment_$column";
866 $svc_acct->$column($amount);
870 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
872 Inserts a prepayment in the specified amount for this customer. An optional
873 second argument can specify the prepayment identifier for tracking purposes.
874 If there is an error, returns the error, otherwise returns false.
878 sub insert_cust_pay_prepay {
879 shift->insert_cust_pay('PREP', @_);
882 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
884 Inserts a cash payment in the specified amount for this customer. An optional
885 second argument can specify the payment identifier for tracking purposes.
886 If there is an error, returns the error, otherwise returns false.
890 sub insert_cust_pay_cash {
891 shift->insert_cust_pay('CASH', @_);
894 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
896 Inserts a Western Union payment in the specified amount for this customer. An
897 optional second argument can specify the prepayment identifier for tracking
898 purposes. If there is an error, returns the error, otherwise returns false.
902 sub insert_cust_pay_west {
903 shift->insert_cust_pay('WEST', @_);
906 sub insert_cust_pay {
907 my( $self, $payby, $amount ) = splice(@_, 0, 3);
908 my $payinfo = scalar(@_) ? shift : '';
910 my $cust_pay = new FS::cust_pay {
911 'custnum' => $self->custnum,
912 'paid' => sprintf('%.2f', $amount),
913 #'_date' => #date the prepaid card was purchased???
915 'payinfo' => $payinfo,
923 This method is deprecated. See the I<depend_jobnum> option to the insert and
924 order_pkgs methods for a better way to defer provisioning.
926 Re-schedules all exports by calling the B<reexport> method of all associated
927 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
928 otherwise returns false.
935 carp "WARNING: FS::cust_main::reexport is deprectated; ".
936 "use the depend_jobnum option to insert or order_pkgs to delay export";
938 local $SIG{HUP} = 'IGNORE';
939 local $SIG{INT} = 'IGNORE';
940 local $SIG{QUIT} = 'IGNORE';
941 local $SIG{TERM} = 'IGNORE';
942 local $SIG{TSTP} = 'IGNORE';
943 local $SIG{PIPE} = 'IGNORE';
945 my $oldAutoCommit = $FS::UID::AutoCommit;
946 local $FS::UID::AutoCommit = 0;
949 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
950 my $error = $cust_pkg->reexport;
952 $dbh->rollback if $oldAutoCommit;
957 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
962 =item delete NEW_CUSTNUM
964 This deletes the customer. If there is an error, returns the error, otherwise
967 This will completely remove all traces of the customer record. This is not
968 what you want when a customer cancels service; for that, cancel all of the
969 customer's packages (see L</cancel>).
971 If the customer has any uncancelled packages, you need to pass a new (valid)
972 customer number for those packages to be transferred to. Cancelled packages
973 will be deleted. Did I mention that this is NOT what you want when a customer
974 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
976 You can't delete a customer with invoices (see L<FS::cust_bill>),
977 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
978 refunds (see L<FS::cust_refund>).
985 local $SIG{HUP} = 'IGNORE';
986 local $SIG{INT} = 'IGNORE';
987 local $SIG{QUIT} = 'IGNORE';
988 local $SIG{TERM} = 'IGNORE';
989 local $SIG{TSTP} = 'IGNORE';
990 local $SIG{PIPE} = 'IGNORE';
992 my $oldAutoCommit = $FS::UID::AutoCommit;
993 local $FS::UID::AutoCommit = 0;
996 if ( $self->cust_bill ) {
997 $dbh->rollback if $oldAutoCommit;
998 return "Can't delete a customer with invoices";
1000 if ( $self->cust_credit ) {
1001 $dbh->rollback if $oldAutoCommit;
1002 return "Can't delete a customer with credits";
1004 if ( $self->cust_pay ) {
1005 $dbh->rollback if $oldAutoCommit;
1006 return "Can't delete a customer with payments";
1008 if ( $self->cust_refund ) {
1009 $dbh->rollback if $oldAutoCommit;
1010 return "Can't delete a customer with refunds";
1013 my @cust_pkg = $self->ncancelled_pkgs;
1015 my $new_custnum = shift;
1016 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1017 $dbh->rollback if $oldAutoCommit;
1018 return "Invalid new customer number: $new_custnum";
1020 foreach my $cust_pkg ( @cust_pkg ) {
1021 my %hash = $cust_pkg->hash;
1022 $hash{'custnum'} = $new_custnum;
1023 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1024 my $error = $new_cust_pkg->replace($cust_pkg,
1025 options => { $cust_pkg->options },
1028 $dbh->rollback if $oldAutoCommit;
1033 my @cancelled_cust_pkg = $self->all_pkgs;
1034 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1035 my $error = $cust_pkg->delete;
1037 $dbh->rollback if $oldAutoCommit;
1042 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1043 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1045 my $error = $cust_main_invoice->delete;
1047 $dbh->rollback if $oldAutoCommit;
1052 my $error = $self->SUPER::delete;
1054 $dbh->rollback if $oldAutoCommit;
1058 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1063 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ]
1065 Replaces the OLD_RECORD with this one in the database. If there is an error,
1066 returns the error, otherwise returns false.
1068 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1069 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1070 expected and rollback the entire transaction; it is not necessary to call
1071 check_invoicing_list first. Here's an example:
1073 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1080 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1082 : $self->replace_old;
1086 warn "$me replace called\n"
1089 my $curuser = $FS::CurrentUser::CurrentUser;
1090 if ( $self->payby eq 'COMP'
1091 && $self->payby ne $old->payby
1092 && ! $curuser->access_right('Complimentary customer')
1095 return "You are not permitted to create complimentary accounts.";
1098 local($ignore_expired_card) = 1
1099 if $old->payby =~ /^(CARD|DCRD)$/
1100 && $self->payby =~ /^(CARD|DCRD)$/
1101 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1103 local $SIG{HUP} = 'IGNORE';
1104 local $SIG{INT} = 'IGNORE';
1105 local $SIG{QUIT} = 'IGNORE';
1106 local $SIG{TERM} = 'IGNORE';
1107 local $SIG{TSTP} = 'IGNORE';
1108 local $SIG{PIPE} = 'IGNORE';
1110 my $oldAutoCommit = $FS::UID::AutoCommit;
1111 local $FS::UID::AutoCommit = 0;
1114 my $error = $self->SUPER::replace($old);
1117 $dbh->rollback if $oldAutoCommit;
1121 if ( @param ) { # INVOICING_LIST_ARYREF
1122 my $invoicing_list = shift @param;
1123 $error = $self->check_invoicing_list( $invoicing_list );
1125 $dbh->rollback if $oldAutoCommit;
1128 $self->invoicing_list( $invoicing_list );
1131 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1132 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1133 # card/check/lec info has changed, want to retry realtime_ invoice events
1134 my $error = $self->retry_realtime;
1136 $dbh->rollback if $oldAutoCommit;
1141 unless ( $import || $skip_fuzzyfiles ) {
1142 $error = $self->queue_fuzzyfiles_update;
1144 $dbh->rollback if $oldAutoCommit;
1145 return "updating fuzzy search cache: $error";
1149 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1154 =item queue_fuzzyfiles_update
1156 Used by insert & replace to update the fuzzy search cache
1160 sub queue_fuzzyfiles_update {
1163 local $SIG{HUP} = 'IGNORE';
1164 local $SIG{INT} = 'IGNORE';
1165 local $SIG{QUIT} = 'IGNORE';
1166 local $SIG{TERM} = 'IGNORE';
1167 local $SIG{TSTP} = 'IGNORE';
1168 local $SIG{PIPE} = 'IGNORE';
1170 my $oldAutoCommit = $FS::UID::AutoCommit;
1171 local $FS::UID::AutoCommit = 0;
1174 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1175 my $error = $queue->insert( map $self->getfield($_),
1176 qw(first last company)
1179 $dbh->rollback if $oldAutoCommit;
1180 return "queueing job (transaction rolled back): $error";
1183 if ( $self->ship_last ) {
1184 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1185 $error = $queue->insert( map $self->getfield("ship_$_"),
1186 qw(first last company)
1189 $dbh->rollback if $oldAutoCommit;
1190 return "queueing job (transaction rolled back): $error";
1194 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1201 Checks all fields to make sure this is a valid customer record. If there is
1202 an error, returns the error, otherwise returns false. Called by the insert
1203 and replace methods.
1210 warn "$me check BEFORE: \n". $self->_dump
1214 $self->ut_numbern('custnum')
1215 || $self->ut_number('agentnum')
1216 || $self->ut_textn('agent_custid')
1217 || $self->ut_number('refnum')
1218 || $self->ut_textn('custbatch')
1219 || $self->ut_name('last')
1220 || $self->ut_name('first')
1221 || $self->ut_snumbern('birthdate')
1222 || $self->ut_snumbern('signupdate')
1223 || $self->ut_textn('company')
1224 || $self->ut_text('address1')
1225 || $self->ut_textn('address2')
1226 || $self->ut_text('city')
1227 || $self->ut_textn('county')
1228 || $self->ut_textn('state')
1229 || $self->ut_country('country')
1230 || $self->ut_anything('comments')
1231 || $self->ut_numbern('referral_custnum')
1232 || $self->ut_textn('stateid')
1233 || $self->ut_textn('stateid_state')
1234 || $self->ut_textn('invoice_terms')
1236 #barf. need message catalogs. i18n. etc.
1237 $error .= "Please select an advertising source."
1238 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1239 return $error if $error;
1241 return "Unknown agent"
1242 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1244 return "Unknown refnum"
1245 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1247 return "Unknown referring custnum: ". $self->referral_custnum
1248 unless ! $self->referral_custnum
1249 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1251 if ( $self->ss eq '' ) {
1256 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1257 or return "Illegal social security number: ". $self->ss;
1258 $self->ss("$1-$2-$3");
1262 # bad idea to disable, causes billing to fail because of no tax rates later
1263 # unless ( $import ) {
1264 unless ( qsearch('cust_main_county', {
1265 'country' => $self->country,
1268 return "Unknown state/county/country: ".
1269 $self->state. "/". $self->county. "/". $self->country
1270 unless qsearch('cust_main_county',{
1271 'state' => $self->state,
1272 'county' => $self->county,
1273 'country' => $self->country,
1279 $self->ut_phonen('daytime', $self->country)
1280 || $self->ut_phonen('night', $self->country)
1281 || $self->ut_phonen('fax', $self->country)
1282 || $self->ut_zip('zip', $self->country)
1284 return $error if $error;
1286 if ( $conf->exists('cust_main-require_phone')
1287 && ! length($self->daytime) && ! length($self->night)
1290 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1292 : FS::Msgcat::_gettext('daytime');
1293 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1295 : FS::Msgcat::_gettext('night');
1297 return "$daytime_label or $night_label is required"
1301 if ( $self->has_ship_address
1302 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1303 $self->addr_fields )
1307 $self->ut_name('ship_last')
1308 || $self->ut_name('ship_first')
1309 || $self->ut_textn('ship_company')
1310 || $self->ut_text('ship_address1')
1311 || $self->ut_textn('ship_address2')
1312 || $self->ut_text('ship_city')
1313 || $self->ut_textn('ship_county')
1314 || $self->ut_textn('ship_state')
1315 || $self->ut_country('ship_country')
1317 return $error if $error;
1319 #false laziness with above
1320 unless ( qsearchs('cust_main_county', {
1321 'country' => $self->ship_country,
1324 return "Unknown ship_state/ship_county/ship_country: ".
1325 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1326 unless qsearch('cust_main_county',{
1327 'state' => $self->ship_state,
1328 'county' => $self->ship_county,
1329 'country' => $self->ship_country,
1335 $self->ut_phonen('ship_daytime', $self->ship_country)
1336 || $self->ut_phonen('ship_night', $self->ship_country)
1337 || $self->ut_phonen('ship_fax', $self->ship_country)
1338 || $self->ut_zip('ship_zip', $self->ship_country)
1340 return $error if $error;
1342 return "Unit # is required."
1343 if $self->ship_address2 =~ /^\s*$/
1344 && $conf->exists('cust_main-require_address2');
1346 } else { # ship_ info eq billing info, so don't store dup info in database
1348 $self->setfield("ship_$_", '')
1349 foreach $self->addr_fields;
1351 return "Unit # is required."
1352 if $self->address2 =~ /^\s*$/
1353 && $conf->exists('cust_main-require_address2');
1357 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1358 # or return "Illegal payby: ". $self->payby;
1360 FS::payby->can_payby($self->table, $self->payby)
1361 or return "Illegal payby: ". $self->payby;
1363 $error = $self->ut_numbern('paystart_month')
1364 || $self->ut_numbern('paystart_year')
1365 || $self->ut_numbern('payissue')
1366 || $self->ut_textn('paytype')
1368 return $error if $error;
1370 if ( $self->payip eq '' ) {
1373 $error = $self->ut_ip('payip');
1374 return $error if $error;
1377 # If it is encrypted and the private key is not availaible then we can't
1378 # check the credit card.
1380 my $check_payinfo = 1;
1382 if ($self->is_encrypted($self->payinfo)) {
1386 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1388 my $payinfo = $self->payinfo;
1389 $payinfo =~ s/\D//g;
1390 $payinfo =~ /^(\d{13,16})$/
1391 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1393 $self->payinfo($payinfo);
1395 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1397 return gettext('unknown_card_type')
1398 if cardtype($self->payinfo) eq "Unknown";
1400 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1402 return 'Banned credit card: banned on '.
1403 time2str('%a %h %o at %r', $ban->_date).
1404 ' by '. $ban->otaker.
1405 ' (ban# '. $ban->bannum. ')';
1408 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1409 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1410 $self->paycvv =~ /^(\d{4})$/
1411 or return "CVV2 (CID) for American Express cards is four digits.";
1414 $self->paycvv =~ /^(\d{3})$/
1415 or return "CVV2 (CVC2/CID) is three digits.";
1422 my $cardtype = cardtype($payinfo);
1423 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1425 return "Start date or issue number is required for $cardtype cards"
1426 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1428 return "Start month must be between 1 and 12"
1429 if $self->paystart_month
1430 and $self->paystart_month < 1 || $self->paystart_month > 12;
1432 return "Start year must be 1990 or later"
1433 if $self->paystart_year
1434 and $self->paystart_year < 1990;
1436 return "Issue number must be beween 1 and 99"
1438 and $self->payissue < 1 || $self->payissue > 99;
1441 $self->paystart_month('');
1442 $self->paystart_year('');
1443 $self->payissue('');
1446 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1448 my $payinfo = $self->payinfo;
1449 $payinfo =~ s/[^\d\@]//g;
1450 if ( $conf->exists('echeck-nonus') ) {
1451 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1452 $payinfo = "$1\@$2";
1454 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1455 $payinfo = "$1\@$2";
1457 $self->payinfo($payinfo);
1460 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1462 return 'Banned ACH account: banned on '.
1463 time2str('%a %h %o at %r', $ban->_date).
1464 ' by '. $ban->otaker.
1465 ' (ban# '. $ban->bannum. ')';
1468 } elsif ( $self->payby eq 'LECB' ) {
1470 my $payinfo = $self->payinfo;
1471 $payinfo =~ s/\D//g;
1472 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1474 $self->payinfo($payinfo);
1477 } elsif ( $self->payby eq 'BILL' ) {
1479 $error = $self->ut_textn('payinfo');
1480 return "Illegal P.O. number: ". $self->payinfo if $error;
1483 } elsif ( $self->payby eq 'COMP' ) {
1485 my $curuser = $FS::CurrentUser::CurrentUser;
1486 if ( ! $self->custnum
1487 && ! $curuser->access_right('Complimentary customer')
1490 return "You are not permitted to create complimentary accounts."
1493 $error = $self->ut_textn('payinfo');
1494 return "Illegal comp account issuer: ". $self->payinfo if $error;
1497 } elsif ( $self->payby eq 'PREPAY' ) {
1499 my $payinfo = $self->payinfo;
1500 $payinfo =~ s/\W//g; #anything else would just confuse things
1501 $self->payinfo($payinfo);
1502 $error = $self->ut_alpha('payinfo');
1503 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1504 return "Unknown prepayment identifier"
1505 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1510 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1511 return "Expiration date required"
1512 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1516 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1517 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1518 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1519 ( $m, $y ) = ( $3, "20$2" );
1521 return "Illegal expiration date: ". $self->paydate;
1523 $self->paydate("$y-$m-01");
1524 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1525 return gettext('expired_card')
1527 && !$ignore_expired_card
1528 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1531 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1532 ( ! $conf->exists('require_cardname')
1533 || $self->payby !~ /^(CARD|DCRD)$/ )
1535 $self->payname( $self->first. " ". $self->getfield('last') );
1537 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1538 or return gettext('illegal_name'). " payname: ". $self->payname;
1542 foreach my $flag (qw( tax spool_cdr squelch_cdr )) {
1543 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1547 $self->otaker(getotaker) unless $self->otaker;
1549 warn "$me check AFTER: \n". $self->_dump
1552 $self->SUPER::check;
1557 Returns a list of fields which have ship_ duplicates.
1562 qw( last first company
1563 address1 address2 city county state zip country
1568 =item has_ship_address
1570 Returns true if this customer record has a separate shipping address.
1574 sub has_ship_address {
1576 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1581 Returns all packages (see L<FS::cust_pkg>) for this customer.
1588 return $self->num_pkgs unless wantarray;
1591 if ( $self->{'_pkgnum'} ) {
1592 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1594 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1597 sort sort_packages @cust_pkg;
1602 Synonym for B<all_pkgs>.
1607 shift->all_pkgs(@_);
1610 =item ncancelled_pkgs
1612 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1616 sub ncancelled_pkgs {
1619 return $self->num_ncancelled_pkgs unless wantarray;
1622 if ( $self->{'_pkgnum'} ) {
1624 warn "$me ncancelled_pkgs: returning cached objects"
1627 @cust_pkg = grep { ! $_->getfield('cancel') }
1628 values %{ $self->{'_pkgnum'}->cache };
1632 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1633 $self->custnum. "\n"
1637 qsearch( 'cust_pkg', {
1638 'custnum' => $self->custnum,
1642 qsearch( 'cust_pkg', {
1643 'custnum' => $self->custnum,
1648 sort sort_packages @cust_pkg;
1652 # This should be generalized to use config options to determine order.
1654 if ( $a->get('cancel') and $b->get('cancel') ) {
1655 $a->pkgnum <=> $b->pkgnum;
1656 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1657 return -1 if $b->get('cancel');
1658 return 1 if $a->get('cancel');
1661 $a->pkgnum <=> $b->pkgnum;
1665 =item suspended_pkgs
1667 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1671 sub suspended_pkgs {
1673 grep { $_->susp } $self->ncancelled_pkgs;
1676 =item unflagged_suspended_pkgs
1678 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1679 customer (thouse packages without the `manual_flag' set).
1683 sub unflagged_suspended_pkgs {
1685 return $self->suspended_pkgs
1686 unless dbdef->table('cust_pkg')->column('manual_flag');
1687 grep { ! $_->manual_flag } $self->suspended_pkgs;
1690 =item unsuspended_pkgs
1692 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1697 sub unsuspended_pkgs {
1699 grep { ! $_->susp } $self->ncancelled_pkgs;
1702 =item num_cancelled_pkgs
1704 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1709 sub num_cancelled_pkgs {
1710 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1713 sub num_ncancelled_pkgs {
1714 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1718 my( $self ) = shift;
1719 my $sql = scalar(@_) ? shift : '';
1720 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1721 my $sth = dbh->prepare(
1722 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1723 ) or die dbh->errstr;
1724 $sth->execute($self->custnum) or die $sth->errstr;
1725 $sth->fetchrow_arrayref->[0];
1730 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1731 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1732 on success or a list of errors.
1738 grep { $_->unsuspend } $self->suspended_pkgs;
1743 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1745 Returns a list: an empty list on success or a list of errors.
1751 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1754 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1756 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1757 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1758 of a list of pkgparts; the hashref has the following keys:
1762 =item pkgparts - listref of pkgparts
1764 =item (other options are passed to the suspend method)
1769 Returns a list: an empty list on success or a list of errors.
1773 sub suspend_if_pkgpart {
1775 my (@pkgparts, %opt);
1776 if (ref($_[0]) eq 'HASH'){
1777 @pkgparts = @{$_[0]{pkgparts}};
1782 grep { $_->suspend(%opt) }
1783 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1784 $self->unsuspended_pkgs;
1787 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1789 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1790 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1791 instead of a list of pkgparts; the hashref has the following keys:
1795 =item pkgparts - listref of pkgparts
1797 =item (other options are passed to the suspend method)
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:
1827 =item quiet - can be set true to supress email cancellation notices.
1829 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
1831 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1835 Always returns a list: an empty list on success or a list of errors.
1840 my( $self, %opt ) = @_;
1842 warn "$me cancel called on customer ". $self->custnum. " with options ".
1843 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1846 return ( 'access denied' )
1847 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1849 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1851 #should try decryption (we might have the private key)
1852 # and if not maybe queue a job for the server that does?
1853 return ( "Can't (yet) ban encrypted credit cards" )
1854 if $self->is_encrypted($self->payinfo);
1856 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1857 my $error = $ban->insert;
1858 return ( $error ) if $error;
1862 my @pkgs = $self->ncancelled_pkgs;
1864 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1865 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1868 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1871 sub _banned_pay_hashref {
1882 'payby' => $payby2ban{$self->payby},
1883 'payinfo' => md5_base64($self->payinfo),
1884 #don't ever *search* on reason! #'reason' =>
1890 Returns all notes (see L<FS::cust_main_note>) for this customer.
1897 qsearch( 'cust_main_note',
1898 { 'custnum' => $self->custnum },
1900 'ORDER BY _DATE DESC'
1906 Returns the agent (see L<FS::agent>) for this customer.
1912 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1915 =item bill_and_collect
1917 Cancels and suspends any packages due, generates bills, applies payments and
1920 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1922 Options are passed as name-value pairs. Currently available options are:
1928 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:
1932 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1936 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.
1940 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1944 If set true, re-charges setup fees.
1948 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)
1954 sub bill_and_collect {
1955 my( $self, %options ) = @_;
1961 #$options{actual_time} not $options{time} because freeside-daily -d is for
1962 #pre-printing invoices
1963 my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
1964 $self->ncancelled_pkgs;
1966 foreach my $cust_pkg ( @cancel_pkgs ) {
1967 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
1968 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
1969 'reason_otaker' => $cpr->otaker
1973 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1974 " for custnum ". $self->custnum. ": $error"
1982 #$options{actual_time} not $options{time} because freeside-daily -d is for
1983 #pre-printing invoices
1986 && ( ( $_->part_pkg->is_prepaid
1988 && $_->bill < $options{actual_time}
1991 && $_->adjourn <= $options{actual_time}
1995 $self->ncancelled_pkgs;
1997 foreach my $cust_pkg ( @susp_pkgs ) {
1998 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
1999 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2000 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2001 'reason_otaker' => $cpr->otaker
2006 warn "Error suspending package ". $cust_pkg->pkgnum.
2007 " for custnum ". $self->custnum. ": $error"
2015 my $error = $self->bill( %options );
2016 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
2018 $self->apply_payments_and_credits;
2020 $error = $self->collect( %options );
2021 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2027 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2028 conjunction with the collect method by calling B<bill_and_collect>.
2030 If there is an error, returns the error, otherwise returns false.
2032 Options are passed as name-value pairs. Currently available options are:
2038 If set true, re-charges setup fees.
2042 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:
2046 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2050 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2052 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2056 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.
2063 my( $self, %options ) = @_;
2064 return '' if $self->payby eq 'COMP';
2065 warn "$me bill customer ". $self->custnum. "\n"
2068 my $time = $options{'time'} || time;
2071 local $SIG{HUP} = 'IGNORE';
2072 local $SIG{INT} = 'IGNORE';
2073 local $SIG{QUIT} = 'IGNORE';
2074 local $SIG{TERM} = 'IGNORE';
2075 local $SIG{TSTP} = 'IGNORE';
2076 local $SIG{PIPE} = 'IGNORE';
2078 my $oldAutoCommit = $FS::UID::AutoCommit;
2079 local $FS::UID::AutoCommit = 0;
2082 $self->select_for_update; #mutex
2084 my @cust_bill_pkg = ();
2087 # find the packages which are due for billing, find out how much they are
2088 # & generate invoice database.
2091 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2095 my @precommit_hooks = ();
2097 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2098 foreach my $cust_pkg (@cust_pkgs) {
2100 #NO!! next if $cust_pkg->cancel;
2101 next if $cust_pkg->getfield('cancel');
2103 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2105 #? to avoid use of uninitialized value errors... ?
2106 $cust_pkg->setfield('bill', '')
2107 unless defined($cust_pkg->bill);
2109 #my $part_pkg = $cust_pkg->part_pkg;
2111 my $real_pkgpart = $cust_pkg->pkgpart;
2112 my %hash = $cust_pkg->hash;
2114 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2116 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2119 $self->_make_lines( 'part_pkg' => $part_pkg,
2120 'cust_pkg' => $cust_pkg,
2121 'precommit_hooks' => \@precommit_hooks,
2122 'line_items' => \@cust_bill_pkg,
2123 'setup' => \$total_setup,
2124 'recur' => \$total_recur,
2125 'tax_matrix' => \%taxlisthash,
2127 'options' => \%options,
2130 $dbh->rollback if $oldAutoCommit;
2134 } #foreach my $part_pkg
2136 } #foreach my $cust_pkg
2138 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2139 #but do commit any package date cycling that happened
2140 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2144 my $postal_pkg = $self->charge_postal_fee();
2145 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2146 $dbh->rollback if $oldAutoCommit;
2147 return "can't charge postal invoice fee for customer ".
2148 $self->custnum. ": $postal_pkg";
2150 if ( $postal_pkg ) {
2151 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2153 $self->_make_lines( 'part_pkg' => $part_pkg,
2154 'cust_pkg' => $postal_pkg,
2155 'precommit_hooks' => \@precommit_hooks,
2156 'line_items' => \@cust_bill_pkg,
2157 'setup' => \$total_setup,
2158 'recur' => \$total_recur,
2159 'tax_matrix' => \%taxlisthash,
2161 'options' => \%options,
2164 $dbh->rollback if $oldAutoCommit;
2170 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2171 foreach my $tax ( keys %taxlisthash ) {
2172 my $tax_object = shift @{ $taxlisthash{$tax} };
2173 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2174 my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2175 unless (ref($listref_or_error)) {
2176 $dbh->rollback if $oldAutoCommit;
2177 return $listref_or_error;
2179 unshift @{ $taxlisthash{$tax} }, $tax_object;
2181 warn "adding ". $listref_or_error->[1].
2182 " as ". $listref_or_error->[0]. "\n"
2184 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2185 if ( $taxname{ $listref_or_error->[0] } ) {
2186 push @{ $taxname{ $listref_or_error->[0] } }, $tax_object->taxname;
2188 $taxname{ $listref_or_error->[0] } = [ $tax_object->taxname ];
2193 #some taxes are taxed
2196 warn "finding taxed taxes...\n" if $DEBUG > 2;
2197 foreach my $tax ( keys %taxlisthash ) {
2198 my $tax_object = shift @{ $taxlisthash{$tax} };
2199 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2201 next unless $tax_object->can('tax_on_tax');
2203 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2204 my $totname = ref( $tot ). ' '. $tot->taxnum;
2206 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2208 next unless exists( $taxlisthash{ $totname } ); # only increase
2210 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2211 if ( exists( $totlisthash{ $totname } ) ) {
2212 push @{ $totlisthash{ $totname } }, $tax{ $tax_object->taxname };
2214 $totlisthash{ $totname } = [ $tot, $tax{ $tax_object->taxname } ];
2219 warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2220 foreach my $tax ( keys %totlisthash ) {
2221 my $tax_object = shift @{ $totlisthash{$tax} };
2222 warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2224 my $listref_or_error = $tax_object->taxline( @{ $totlisthash{$tax} } );
2225 unless (ref($listref_or_error)) {
2226 $dbh->rollback if $oldAutoCommit;
2227 return $listref_or_error;
2230 warn "adding taxed tax amount ". $listref_or_error->[1].
2231 " as ". $tax_object->taxname. "\n"
2233 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2236 #consolidate and create tax line items
2237 warn "consolidating and generating...\n" if $DEBUG > 2;
2238 foreach my $taxname ( keys %taxname ) {
2241 warn "adding $taxname\n" if $DEBUG > 1;
2242 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2243 $tax += $tax{$taxitem} unless $seen{$taxitem};
2244 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2248 $tax = sprintf('%.2f', $tax );
2249 $total_setup = sprintf('%.2f', $total_setup+$tax );
2251 push @cust_bill_pkg, new FS::cust_bill_pkg {
2257 'itemdesc' => $taxname,
2262 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2264 #create the new invoice
2265 my $cust_bill = new FS::cust_bill ( {
2266 'custnum' => $self->custnum,
2267 '_date' => ( $options{'invoice_time'} || $time ),
2268 'charged' => $charged,
2270 my $error = $cust_bill->insert;
2272 $dbh->rollback if $oldAutoCommit;
2273 return "can't create invoice for customer #". $self->custnum. ": $error";
2276 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2277 $cust_bill_pkg->invnum($cust_bill->invnum);
2278 my $error = $cust_bill_pkg->insert;
2280 $dbh->rollback if $oldAutoCommit;
2281 return "can't create invoice line item: $error";
2286 foreach my $hook ( @precommit_hooks ) {
2288 &{$hook}; #($self) ?
2291 $dbh->rollback if $oldAutoCommit;
2292 return "$@ running precommit hook $hook\n";
2296 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2302 my ($self, %params) = @_;
2304 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2305 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2306 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2307 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2308 my $total_setup = $params{setup} or die "no setup accumulator specified";
2309 my $total_recur = $params{recur} or die "no recur accumulator specified";
2310 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2311 my $time = $params{'time'} or die "no time specified";
2312 my (%options) = %{$params{options}}; #hmmm only for 'resetup'
2315 my $real_pkgpart = $cust_pkg->pkgpart;
2316 my %hash = $cust_pkg->hash;
2317 my $old_cust_pkg = new FS::cust_pkg \%hash;
2323 $cust_pkg->pkgpart($part_pkg->pkgpart);
2331 if ( ! $cust_pkg->setup &&
2333 ( $conf->exists('disable_setup_suspended_pkgs') &&
2334 ! $cust_pkg->getfield('susp')
2335 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2337 || $options{'resetup'}
2340 warn " bill setup\n" if $DEBUG > 1;
2343 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2344 return "$@ running calc_setup for $cust_pkg\n"
2347 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2349 $cust_pkg->setfield('setup', $time)
2350 unless $cust_pkg->setup;
2351 #do need it, but it won't get written to the db
2352 #|| $cust_pkg->pkgpart != $real_pkgpart;
2357 # bill recurring fee
2360 #XXX unit stuff here too
2364 if ( $part_pkg->getfield('freq') ne '0' &&
2365 ! $cust_pkg->getfield('susp') &&
2366 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2369 # XXX should this be a package event? probably. events are called
2370 # at collection time at the moment, though...
2371 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2372 if $part_pkg->can('reset_usage');
2373 #don't want to reset usage just cause we want a line item??
2374 #&& $part_pkg->pkgpart == $real_pkgpart;
2376 warn " bill recur\n" if $DEBUG > 1;
2379 # XXX shared with $recur_prog
2380 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2382 #over two params! lets at least switch to a hashref for the rest...
2383 my %param = ( 'precommit_hooks' => $precommit_hooks, );
2385 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2386 return "$@ running calc_recur for $cust_pkg\n"
2390 #change this bit to use Date::Manip? CAREFUL with timezones (see
2391 # mailing list archive)
2392 my ($sec,$min,$hour,$mday,$mon,$year) =
2393 (localtime($sdate) )[0,1,2,3,4,5];
2395 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2396 # only for figuring next bill date, nothing else, so, reset $sdate again
2398 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2399 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2400 $cust_pkg->last_bill($sdate);
2402 if ( $part_pkg->freq =~ /^\d+$/ ) {
2403 $mon += $part_pkg->freq;
2404 until ( $mon < 12 ) { $mon -= 12; $year++; }
2405 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2407 $mday += $weeks * 7;
2408 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2411 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2415 return "unparsable frequency: ". $part_pkg->freq;
2417 $cust_pkg->setfield('bill',
2418 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2422 warn "\$setup is undefined" unless defined($setup);
2423 warn "\$recur is undefined" unless defined($recur);
2424 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2427 # If there's line items, create em cust_bill_pkg records
2428 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2433 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2434 # hmm.. and if just the options are modified in some weird price plan?
2436 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2439 my $error = $cust_pkg->replace( $old_cust_pkg,
2440 'options' => { $cust_pkg->options },
2442 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2443 if $error; #just in case
2446 $setup = sprintf( "%.2f", $setup );
2447 $recur = sprintf( "%.2f", $recur );
2448 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2449 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2451 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2452 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2455 if ( $setup != 0 || $recur != 0 ) {
2457 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2460 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2462 warn " adding customer package invoice detail: $_\n"
2463 foreach @cust_pkg_detail;
2465 push @details, @cust_pkg_detail;
2467 my $cust_bill_pkg = new FS::cust_bill_pkg {
2468 'pkgnum' => $cust_pkg->pkgnum,
2470 'unitsetup' => $unitsetup,
2472 'unitrecur' => $unitrecur,
2473 'quantity' => $cust_pkg->quantity,
2474 'details' => \@details,
2477 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
2478 $cust_bill_pkg->sdate( $hash{last_bill} );
2479 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2480 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
2481 $cust_bill_pkg->sdate( $sdate );
2482 $cust_bill_pkg->edate( $cust_pkg->bill );
2485 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2486 unless $part_pkg->pkgpart == $real_pkgpart;
2488 $$total_setup += $setup;
2489 $$total_recur += $recur;
2496 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg);
2497 return $error if $error;
2499 push @$cust_bill_pkgs, $cust_bill_pkg;
2501 } #if $setup != 0 || $recur != 0
2511 my $part_pkg = shift;
2512 my $taxlisthash = shift;
2513 my $cust_bill_pkg = shift;
2514 my $cust_pkg = shift;
2516 my %cust_bill_pkg = ();
2520 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2525 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
2526 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
2527 push @classes, 'setup' if $cust_bill_pkg->setup;
2528 push @classes, 'recur' if $cust_bill_pkg->recur;
2530 if ( $conf->exists('enable_taxproducts')
2531 && (scalar($part_pkg->part_pkg_taxoverride) || $part_pkg->has_taxproduct)
2532 && ( $self->tax !~ /Y/i && $self->payby ne 'COMP' )
2536 foreach my $class (@classes) {
2537 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $prefix );
2538 return $err_or_ref unless ref($err_or_ref);
2539 $taxes{$class} = $err_or_ref;
2542 unless (exists $taxes{''}) {
2543 my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $prefix );
2544 return $err_or_ref unless ref($err_or_ref);
2545 $taxes{''} = $err_or_ref;
2548 } elsif ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
2550 my %taxhash = map { $_ => $self->get("$prefix$_") }
2551 qw( state county country );
2553 $taxhash{'taxclass'} = $part_pkg->taxclass;
2555 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2558 $taxhash{'taxclass'} = '';
2559 @taxes = qsearch( 'cust_main_county', \%taxhash );
2562 #one more try at a whole-country tax rate
2564 $taxhash{$_} = '' foreach qw( state county );
2565 @taxes = qsearch( 'cust_main_county', \%taxhash );
2568 $taxes{''} = [ @taxes ];
2569 $taxes{'setup'} = [ @taxes ];
2570 $taxes{'recur'} = [ @taxes ];
2571 $taxes{$_} = [ @taxes ] foreach (@classes);
2573 # maybe eliminate this entirely, along with all the 0% records
2576 "fatal: can't find tax rate for state/county/country/taxclass ".
2577 join('/', ( map $self->get("$prefix$_"),
2578 qw(state county country)
2580 $part_pkg->taxclass ). "\n";
2583 } #if $conf->exists('enable_taxproducts') ...
2586 if ( $conf->exists('separate_usage') ) {
2587 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
2588 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
2589 push @display, new FS::cust_bill_pkg_display { type => 'S' };
2590 push @display, new FS::cust_bill_pkg_display { type => 'R' };
2591 push @display, new FS::cust_bill_pkg_display { type => 'U',
2594 if ($section && $summary) {
2595 $display[2]->post_total('Y');
2596 push @display, new FS::cust_bill_pkg_display { type => 'U',
2601 $cust_bill_pkg->set('display', \@display);
2603 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
2604 foreach my $key (keys %tax_cust_bill_pkg) {
2605 my @taxes = @{ $taxes{$key} };
2606 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
2608 foreach my $tax ( @taxes ) {
2609 my $taxname = ref( $tax ). ' '. $tax->taxnum;
2610 if ( exists( $taxlisthash->{ $taxname } ) ) {
2611 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
2613 $taxlisthash->{ $taxname } = [ $tax, $tax_cust_bill_pkg ];
2623 my $part_pkg = shift;
2628 my $geocode = $self->geocode('cch');
2630 my @taxclassnums = map { $_->taxclassnum }
2631 $part_pkg->part_pkg_taxoverride($class);
2633 unless (@taxclassnums) {
2634 @taxclassnums = map { $_->taxclassnum }
2635 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
2637 warn "Found taxclassnum values of ". join(',', @taxclassnums)
2642 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2644 @taxes = qsearch({ 'table' => 'tax_rate',
2645 'hashref' => { 'geocode' => $geocode, },
2646 'extra_sql' => $extra_sql,
2648 if scalar(@taxclassnums);
2650 # maybe eliminate this entirely, along with all the 0% records
2653 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2654 join('/', ( map $self->get("$prefix$_"),
2657 $part_pkg->taxproduct_description,
2658 $part_pkg->pkgpart ). "\n";
2661 warn "Found taxes ".
2662 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
2669 =item collect OPTIONS
2671 (Attempt to) collect money for this customer's outstanding invoices (see
2672 L<FS::cust_bill>). Usually used after the bill method.
2674 Actions are now triggered by billing events; see L<FS::part_event> and the
2675 billing events web interface. Old-style invoice events (see
2676 L<FS::part_bill_event>) have been deprecated.
2678 If there is an error, returns the error, otherwise returns false.
2680 Options are passed as name-value pairs.
2682 Currently available options are:
2688 Use this time when deciding when to print invoices and 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> for conversion functions.
2692 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2696 set true to surpress email card/ACH decline notices.
2700 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2704 allows for one time override of normal customer billing method
2708 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)
2716 my( $self, %options ) = @_;
2717 my $invoice_time = $options{'invoice_time'} || time;
2720 local $SIG{HUP} = 'IGNORE';
2721 local $SIG{INT} = 'IGNORE';
2722 local $SIG{QUIT} = 'IGNORE';
2723 local $SIG{TERM} = 'IGNORE';
2724 local $SIG{TSTP} = 'IGNORE';
2725 local $SIG{PIPE} = 'IGNORE';
2727 my $oldAutoCommit = $FS::UID::AutoCommit;
2728 local $FS::UID::AutoCommit = 0;
2731 $self->select_for_update; #mutex
2734 my $balance = $self->balance;
2735 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2738 if ( exists($options{'retry_card'}) ) {
2739 carp 'retry_card option passed to collect is deprecated; use retry';
2740 $options{'retry'} ||= $options{'retry_card'};
2742 if ( exists($options{'retry'}) && $options{'retry'} ) {
2743 my $error = $self->retry_realtime;
2745 $dbh->rollback if $oldAutoCommit;
2750 # false laziness w/pay_batch::import_results
2752 my $due_cust_event = $self->due_cust_event(
2753 'debug' => ( $options{'debug'} || 0 ),
2754 'time' => $invoice_time,
2755 'check_freq' => $options{'check_freq'},
2757 unless( ref($due_cust_event) ) {
2758 $dbh->rollback if $oldAutoCommit;
2759 return $due_cust_event;
2762 foreach my $cust_event ( @$due_cust_event ) {
2766 #re-eval event conditions (a previous event could have changed things)
2767 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2768 #don't leave stray "new/locked" records around
2769 my $error = $cust_event->delete;
2771 #gah, even with transactions
2772 $dbh->commit if $oldAutoCommit; #well.
2779 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2780 warn " running cust_event ". $cust_event->eventnum. "\n"
2784 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2785 if ( my $error = $cust_event->do_event() ) {
2786 #XXX wtf is this? figure out a proper dealio with return value
2788 # gah, even with transactions.
2789 $dbh->commit if $oldAutoCommit; #well.
2796 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2801 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2803 Inserts database records for and returns an ordered listref of new events due
2804 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2805 events are due, an empty listref is returned. If there is an error, returns a
2806 scalar error message.
2808 To actually run the events, call each event's test_condition method, and if
2809 still true, call the event's do_event method.
2811 Options are passed as a hashref or as a list of name-value pairs. Available
2818 Search only for events of this check frequency (how often events of this type are checked); currently "1d" (daily, the default) and "1m" (monthly) are recognized.
2822 "Current time" for the events.
2826 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)
2830 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2834 Explicitly pass the objects to be tested (typically used with eventtable).
2840 sub due_cust_event {
2842 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2845 #my $DEBUG = $opt{'debug'}
2846 local($DEBUG) = $opt{'debug'}
2847 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2849 warn "$me due_cust_event called with options ".
2850 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2853 $opt{'time'} ||= time;
2855 local $SIG{HUP} = 'IGNORE';
2856 local $SIG{INT} = 'IGNORE';
2857 local $SIG{QUIT} = 'IGNORE';
2858 local $SIG{TERM} = 'IGNORE';
2859 local $SIG{TSTP} = 'IGNORE';
2860 local $SIG{PIPE} = 'IGNORE';
2862 my $oldAutoCommit = $FS::UID::AutoCommit;
2863 local $FS::UID::AutoCommit = 0;
2866 $self->select_for_update; #mutex
2869 # 1: find possible events (initial search)
2872 my @cust_event = ();
2874 my @eventtable = $opt{'eventtable'}
2875 ? ( $opt{'eventtable'} )
2876 : FS::part_event->eventtables_runorder;
2878 foreach my $eventtable ( @eventtable ) {
2881 if ( $opt{'objects'} ) {
2883 @objects = @{ $opt{'objects'} };
2887 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2888 @objects = ( $eventtable eq 'cust_main' )
2890 : ( $self->$eventtable() );
2894 my @e_cust_event = ();
2896 my $cross = "CROSS JOIN $eventtable";
2897 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2898 unless $eventtable eq 'cust_main';
2900 foreach my $object ( @objects ) {
2902 #this first search uses the condition_sql magic for optimization.
2903 #the more possible events we can eliminate in this step the better
2905 my $cross_where = '';
2906 my $pkey = $object->primary_key;
2907 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2909 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2911 FS::part_event_condition->where_conditions_sql( $eventtable,
2912 'time'=>$opt{'time'}
2914 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2916 $extra_sql = "AND $extra_sql" if $extra_sql;
2918 #here is the agent virtualization
2919 $extra_sql .= " AND ( part_event.agentnum IS NULL
2920 OR part_event.agentnum = ". $self->agentnum. ' )';
2922 $extra_sql .= " $order";
2924 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2925 if $opt{'debug'} > 2;
2926 my @part_event = qsearch( {
2927 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2928 'select' => 'part_event.*',
2929 'table' => 'part_event',
2930 'addl_from' => "$cross $join",
2931 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2932 'eventtable' => $eventtable,
2935 'extra_sql' => "AND $cross_where $extra_sql",
2939 my $pkey = $object->primary_key;
2940 warn " ". scalar(@part_event).
2941 " possible events found for $eventtable ". $object->$pkey(). "\n";
2944 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2948 warn " ". scalar(@e_cust_event).
2949 " subtotal possible cust events found for $eventtable\n"
2952 push @cust_event, @e_cust_event;
2956 warn " ". scalar(@cust_event).
2957 " total possible cust events found in initial search\n"
2961 # 2: test conditions
2966 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
2967 'stats_hashref' => \%unsat ),
2970 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
2973 warn " invalid conditions not eliminated with condition_sql:\n".
2974 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
2981 unless( $opt{testonly} ) {
2982 foreach my $cust_event ( @cust_event ) {
2984 my $error = $cust_event->insert();
2986 $dbh->rollback if $oldAutoCommit;
2993 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2999 warn " returning events: ". Dumper(@cust_event). "\n"
3006 =item retry_realtime
3008 Schedules realtime / batch credit card / electronic check / LEC billing
3009 events for for retry. Useful if card information has changed or manual
3010 retry is desired. The 'collect' method must be called to actually retry
3013 Implementation details: For either this customer, or for each of this
3014 customer's open invoices, changes the status of the first "done" (with
3015 statustext error) realtime processing event to "failed".
3019 sub retry_realtime {
3022 local $SIG{HUP} = 'IGNORE';
3023 local $SIG{INT} = 'IGNORE';
3024 local $SIG{QUIT} = 'IGNORE';
3025 local $SIG{TERM} = 'IGNORE';
3026 local $SIG{TSTP} = 'IGNORE';
3027 local $SIG{PIPE} = 'IGNORE';
3029 my $oldAutoCommit = $FS::UID::AutoCommit;
3030 local $FS::UID::AutoCommit = 0;
3033 #a little false laziness w/due_cust_event (not too bad, really)
3035 my $join = FS::part_event_condition->join_conditions_sql;
3036 my $order = FS::part_event_condition->order_conditions_sql;
3039 . join ( ' OR ' , map {
3040 "( part_event.eventtable = " . dbh->quote($_)
3041 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3042 } FS::part_event->eventtables)
3045 #here is the agent virtualization
3046 my $agent_virt = " ( part_event.agentnum IS NULL
3047 OR part_event.agentnum = ". $self->agentnum. ' )';
3049 #XXX this shouldn't be hardcoded, actions should declare it...
3050 my @realtime_events = qw(
3051 cust_bill_realtime_card
3052 cust_bill_realtime_check
3053 cust_bill_realtime_lec
3057 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3062 my @cust_event = qsearchs({
3063 'table' => 'cust_event',
3064 'select' => 'cust_event.*',
3065 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3066 'hashref' => { 'status' => 'done' },
3067 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3068 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3071 my %seen_invnum = ();
3072 foreach my $cust_event (@cust_event) {
3074 #max one for the customer, one for each open invoice
3075 my $cust_X = $cust_event->cust_X;
3076 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3080 or $cust_event->part_event->eventtable eq 'cust_bill'
3083 my $error = $cust_event->retry;
3085 $dbh->rollback if $oldAutoCommit;
3086 return "error scheduling event for retry: $error";
3091 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3096 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3098 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3099 via a Business::OnlinePayment realtime gateway. See
3100 L<http://420.am/business-onlinepayment> for supported gateways.
3102 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3104 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3106 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3107 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3108 if set, will override the value from the customer record.
3110 I<description> is a free-text field passed to the gateway. It defaults to
3111 "Internet services".
3113 If an I<invnum> is specified, this payment (if successful) is applied to the
3114 specified invoice. If you don't specify an I<invnum> you might want to
3115 call the B<apply_payments> method.
3117 I<quiet> can be set true to surpress email decline notices.
3119 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3120 resulting paynum, if any.
3122 I<payunique> is a unique identifier for this payment.
3124 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3129 my( $self, $method, $amount, %options ) = @_;
3131 warn "$me realtime_bop: $method $amount\n";
3132 warn " $_ => $options{$_}\n" foreach keys %options;
3135 $options{'description'} ||= 'Internet services';
3137 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3139 eval "use Business::OnlinePayment";
3142 my $payinfo = exists($options{'payinfo'})
3143 ? $options{'payinfo'}
3146 my %method2payby = (
3153 # check for banned credit card/ACH
3156 my $ban = qsearchs('banned_pay', {
3157 'payby' => $method2payby{$method},
3158 'payinfo' => md5_base64($payinfo),
3160 return "Banned credit card" if $ban;
3167 if ( $options{'invnum'} ) {
3168 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3169 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3171 map { $_->part_pkg->taxclass }
3173 map { $_->cust_pkg }
3174 $cust_bill->cust_bill_pkg;
3175 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3176 #different taxclasses
3177 $taxclass = $taxclasses[0];
3181 #look for an agent gateway override first
3183 if ( $method eq 'CC' ) {
3184 $cardtype = cardtype($payinfo);
3185 } elsif ( $method eq 'ECHECK' ) {
3188 $cardtype = $method;
3192 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3193 cardtype => $cardtype,
3194 taxclass => $taxclass, } )
3195 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3197 taxclass => $taxclass, } )
3198 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3199 cardtype => $cardtype,
3201 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3203 taxclass => '', } );
3205 my $payment_gateway = '';
3206 my( $processor, $login, $password, $action, @bop_options );
3207 if ( $override ) { #use a payment gateway override
3209 $payment_gateway = $override->payment_gateway;
3211 $processor = $payment_gateway->gateway_module;
3212 $login = $payment_gateway->gateway_username;
3213 $password = $payment_gateway->gateway_password;
3214 $action = $payment_gateway->gateway_action;
3215 @bop_options = $payment_gateway->options;
3217 } else { #use the standard settings from the config
3219 ( $processor, $login, $password, $action, @bop_options ) =
3220 $self->default_payment_gateway($method);
3228 my $address = exists($options{'address1'})
3229 ? $options{'address1'}
3231 my $address2 = exists($options{'address2'})
3232 ? $options{'address2'}
3234 $address .= ", ". $address2 if length($address2);
3236 my $o_payname = exists($options{'payname'})
3237 ? $options{'payname'}
3239 my($payname, $payfirst, $paylast);
3240 if ( $o_payname && $method ne 'ECHECK' ) {
3241 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3242 or return "Illegal payname $payname";
3243 ($payfirst, $paylast) = ($1, $2);
3245 $payfirst = $self->getfield('first');
3246 $paylast = $self->getfield('last');
3247 $payname = "$payfirst $paylast";
3250 my @invoicing_list = $self->invoicing_list_emailonly;
3251 if ( $conf->exists('emailinvoiceautoalways')
3252 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3253 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3254 push @invoicing_list, $self->all_emails;
3257 my $email = ($conf->exists('business-onlinepayment-email-override'))
3258 ? $conf->config('business-onlinepayment-email-override')
3259 : $invoicing_list[0];
3263 my $payip = exists($options{'payip'})
3266 $content{customer_ip} = $payip
3269 $content{invoice_number} = $options{'invnum'}
3270 if exists($options{'invnum'}) && length($options{'invnum'});
3272 $content{email_customer} =
3273 ( $conf->exists('business-onlinepayment-email_customer')
3274 || $conf->exists('business-onlinepayment-email-override') );
3277 if ( $method eq 'CC' ) {
3279 $content{card_number} = $payinfo;
3280 $paydate = exists($options{'paydate'})
3281 ? $options{'paydate'}
3283 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3284 $content{expiration} = "$2/$1";
3286 my $paycvv = exists($options{'paycvv'})
3287 ? $options{'paycvv'}
3289 $content{cvv2} = $paycvv
3292 my $paystart_month = exists($options{'paystart_month'})
3293 ? $options{'paystart_month'}
3294 : $self->paystart_month;
3296 my $paystart_year = exists($options{'paystart_year'})
3297 ? $options{'paystart_year'}
3298 : $self->paystart_year;
3300 $content{card_start} = "$paystart_month/$paystart_year"
3301 if $paystart_month && $paystart_year;
3303 my $payissue = exists($options{'payissue'})
3304 ? $options{'payissue'}
3306 $content{issue_number} = $payissue if $payissue;
3308 $content{recurring_billing} = 'YES'
3309 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3311 'payinfo' => $payinfo,
3313 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3315 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3319 } elsif ( $method eq 'ECHECK' ) {
3320 ( $content{account_number}, $content{routing_code} ) =
3321 split('@', $payinfo);
3322 $content{bank_name} = $o_payname;
3323 $content{bank_state} = exists($options{'paystate'})
3324 ? $options{'paystate'}
3325 : $self->getfield('paystate');
3326 $content{account_type} = exists($options{'paytype'})
3327 ? uc($options{'paytype'}) || 'CHECKING'
3328 : uc($self->getfield('paytype')) || 'CHECKING';
3329 $content{account_name} = $payname;
3330 $content{customer_org} = $self->company ? 'B' : 'I';
3331 $content{state_id} = exists($options{'stateid'})
3332 ? $options{'stateid'}
3333 : $self->getfield('stateid');
3334 $content{state_id_state} = exists($options{'stateid_state'})
3335 ? $options{'stateid_state'}
3336 : $self->getfield('stateid_state');
3337 $content{customer_ssn} = exists($options{'ss'})
3340 } elsif ( $method eq 'LEC' ) {
3341 $content{phone} = $payinfo;
3345 # run transaction(s)
3348 my $balance = exists( $options{'balance'} )
3349 ? $options{'balance'}
3352 $self->select_for_update; #mutex ... just until we get our pending record in
3354 #the checks here are intended to catch concurrent payments
3355 #double-form-submission prevention is taken care of in cust_pay_pending::check
3358 return "The customer's balance has changed; $method transaction aborted."
3359 if $self->balance < $balance;
3360 #&& $self->balance < $amount; #might as well anyway?
3362 #also check and make sure there aren't *other* pending payments for this cust
3364 my @pending = qsearch('cust_pay_pending', {
3365 'custnum' => $self->custnum,
3366 'status' => { op=>'!=', value=>'done' }
3368 return "A payment is already being processed for this customer (".
3369 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3370 "); $method transaction aborted."
3371 if scalar(@pending);
3373 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3375 my $cust_pay_pending = new FS::cust_pay_pending {
3376 'custnum' => $self->custnum,
3377 #'invnum' => $options{'invnum'},
3380 'payby' => $method2payby{$method},
3381 'payinfo' => $payinfo,
3382 'paydate' => $paydate,
3384 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3386 $cust_pay_pending->payunique( $options{payunique} )
3387 if defined($options{payunique}) && length($options{payunique});
3388 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3389 return $cpp_new_err if $cpp_new_err;
3391 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3393 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3394 $transaction->content(
3397 'password' => $password,
3398 'action' => $action1,
3399 'description' => $options{'description'},
3400 'amount' => $amount,
3401 #'invoice_number' => $options{'invnum'},
3402 'customer_id' => $self->custnum,
3403 'last_name' => $paylast,
3404 'first_name' => $payfirst,
3406 'address' => $address,
3407 'city' => ( exists($options{'city'})
3410 'state' => ( exists($options{'state'})
3413 'zip' => ( exists($options{'zip'})
3416 'country' => ( exists($options{'country'})
3417 ? $options{'country'}
3419 'referer' => 'http://cleanwhisker.420.am/',
3421 'phone' => $self->daytime || $self->night,
3425 $cust_pay_pending->status('pending');
3426 my $cpp_pending_err = $cust_pay_pending->replace;
3427 return $cpp_pending_err if $cpp_pending_err;
3430 my $BOP_TESTING = 0;
3431 my $BOP_TESTING_SUCCESS = 1;
3433 unless ( $BOP_TESTING ) {
3434 $transaction->submit();
3436 if ( $BOP_TESTING_SUCCESS ) {
3437 $transaction->is_success(1);
3438 $transaction->authorization('fake auth');
3440 $transaction->is_success(0);
3441 $transaction->error_message('fake failure');
3445 if ( $transaction->is_success() && $action2 ) {
3447 $cust_pay_pending->status('authorized');
3448 my $cpp_authorized_err = $cust_pay_pending->replace;
3449 return $cpp_authorized_err if $cpp_authorized_err;
3451 my $auth = $transaction->authorization;
3452 my $ordernum = $transaction->can('order_number')
3453 ? $transaction->order_number
3457 new Business::OnlinePayment( $processor, @bop_options );
3464 password => $password,
3465 order_number => $ordernum,
3467 authorization => $auth,
3468 description => $options{'description'},
3471 foreach my $field (qw( authorization_source_code returned_ACI
3472 transaction_identifier validation_code
3473 transaction_sequence_num local_transaction_date
3474 local_transaction_time AVS_result_code )) {
3475 $capture{$field} = $transaction->$field() if $transaction->can($field);
3478 $capture->content( %capture );
3482 unless ( $capture->is_success ) {
3483 my $e = "Authorization successful but capture failed, custnum #".
3484 $self->custnum. ': '. $capture->result_code.
3485 ": ". $capture->error_message;
3492 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3493 my $cpp_captured_err = $cust_pay_pending->replace;
3494 return $cpp_captured_err if $cpp_captured_err;
3497 # remove paycvv after initial transaction
3500 #false laziness w/misc/process/payment.cgi - check both to make sure working
3502 if ( defined $self->dbdef_table->column('paycvv')
3503 && length($self->paycvv)
3504 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3506 my $error = $self->remove_cvv;
3508 warn "WARNING: error removing cvv: $error\n";
3516 if ( $transaction->is_success() ) {
3519 if ( $payment_gateway ) { # agent override
3520 $paybatch = $payment_gateway->gatewaynum. '-';
3523 $paybatch .= "$processor:". $transaction->authorization;
3525 $paybatch .= ':'. $transaction->order_number
3526 if $transaction->can('order_number')
3527 && length($transaction->order_number);
3529 my $cust_pay = new FS::cust_pay ( {
3530 'custnum' => $self->custnum,
3531 'invnum' => $options{'invnum'},
3534 'payby' => $method2payby{$method},
3535 'payinfo' => $payinfo,
3536 'paybatch' => $paybatch,
3537 'paydate' => $paydate,
3539 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3540 $cust_pay->payunique( $options{payunique} )
3541 if defined($options{payunique}) && length($options{payunique});
3543 my $oldAutoCommit = $FS::UID::AutoCommit;
3544 local $FS::UID::AutoCommit = 0;
3547 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3549 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3552 $cust_pay->invnum(''); #try again with no specific invnum
3553 my $error2 = $cust_pay->insert( $options{'manual'} ?
3554 ( 'manual' => 1 ) : ()
3557 # gah. but at least we have a record of the state we had to abort in
3558 # from cust_pay_pending now.
3559 my $e = "WARNING: $method captured but payment not recorded - ".
3560 "error inserting payment ($processor): $error2".
3561 " (previously tried insert with invnum #$options{'invnum'}" .
3562 ": $error ) - pending payment saved as paypendingnum ".
3563 $cust_pay_pending->paypendingnum. "\n";
3569 if ( $options{'paynum_ref'} ) {
3570 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3573 $cust_pay_pending->status('done');
3574 $cust_pay_pending->statustext('captured');
3575 my $cpp_done_err = $cust_pay_pending->replace;
3577 if ( $cpp_done_err ) {
3579 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3580 my $e = "WARNING: $method captured but payment not recorded - ".
3581 "error updating status for paypendingnum ".
3582 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3588 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3589 return ''; #no error
3595 my $perror = "$processor error: ". $transaction->error_message;
3597 unless ( $transaction->error_message ) {
3600 if ( $transaction->can('response_page') ) {
3602 'page' => ( $transaction->can('response_page')
3603 ? $transaction->response_page
3606 'code' => ( $transaction->can('response_code')
3607 ? $transaction->response_code
3610 'headers' => ( $transaction->can('response_headers')
3611 ? $transaction->response_headers
3617 "No additional debugging information available for $processor";
3620 $perror .= "No error_message returned from $processor -- ".
3621 ( ref($t_response) ? Dumper($t_response) : $t_response );
3625 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3626 && $conf->exists('emaildecline')
3627 && grep { $_ ne 'POST' } $self->invoicing_list
3628 && ! grep { $transaction->error_message =~ /$_/ }
3629 $conf->config('emaildecline-exclude')
3631 my @templ = $conf->config('declinetemplate');
3632 my $template = new Text::Template (
3634 SOURCE => [ map "$_\n", @templ ],
3635 ) or return "($perror) can't create template: $Text::Template::ERROR";
3636 $template->compile()
3637 or return "($perror) can't compile template: $Text::Template::ERROR";
3639 my $templ_hash = { error => $transaction->error_message };
3641 my $error = send_email(
3642 'from' => $conf->config('invoice_from'),
3643 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3644 'subject' => 'Your payment could not be processed',
3645 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3648 $perror .= " (also received error sending decline notification: $error)"
3653 $cust_pay_pending->status('done');
3654 $cust_pay_pending->statustext("declined: $perror");
3655 my $cpp_done_err = $cust_pay_pending->replace;
3656 if ( $cpp_done_err ) {
3657 my $e = "WARNING: $method declined but pending payment not resolved - ".
3658 "error updating status for paypendingnum ".
3659 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3661 $perror = "$e ($perror)";
3674 my( $self, $method, $amount, %options ) = @_;
3676 if ( $options{'fake_failure'} ) {
3677 return "Error: No error; test failure requested with fake_failure";
3680 my %method2payby = (
3687 #if ( $payment_gateway ) { # agent override
3688 # $paybatch = $payment_gateway->gatewaynum. '-';
3691 #$paybatch .= "$processor:". $transaction->authorization;
3693 #$paybatch .= ':'. $transaction->order_number
3694 # if $transaction->can('order_number')
3695 # && length($transaction->order_number);
3697 my $paybatch = 'FakeProcessor:54:32';
3699 my $cust_pay = new FS::cust_pay ( {
3700 'custnum' => $self->custnum,
3701 'invnum' => $options{'invnum'},
3704 'payby' => $method2payby{$method},
3705 #'payinfo' => $payinfo,
3706 'payinfo' => '4111111111111111',
3707 'paybatch' => $paybatch,
3708 #'paydate' => $paydate,
3709 'paydate' => '2012-05-01',
3711 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3713 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3716 $cust_pay->invnum(''); #try again with no specific invnum
3717 my $error2 = $cust_pay->insert( $options{'manual'} ?
3718 ( 'manual' => 1 ) : ()
3721 # gah, even with transactions.
3722 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3723 "error inserting (fake!) payment: $error2".
3724 " (previously tried insert with invnum #$options{'invnum'}" .
3731 if ( $options{'paynum_ref'} ) {
3732 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3735 return ''; #no error
3739 =item default_payment_gateway
3743 sub default_payment_gateway {
3744 my( $self, $method ) = @_;
3746 die "Real-time processing not enabled\n"
3747 unless $conf->exists('business-onlinepayment');
3750 my $bop_config = 'business-onlinepayment';
3751 $bop_config .= '-ach'
3752 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3753 my ( $processor, $login, $password, $action, @bop_options ) =
3754 $conf->config($bop_config);
3755 $action ||= 'normal authorization';
3756 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3757 die "No real-time processor is enabled - ".
3758 "did you set the business-onlinepayment configuration value?\n"
3761 ( $processor, $login, $password, $action, @bop_options )
3766 Removes the I<paycvv> field from the database directly.
3768 If there is an error, returns the error, otherwise returns false.
3774 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3775 or return dbh->errstr;
3776 $sth->execute($self->custnum)
3777 or return $sth->errstr;
3782 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3784 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3785 via a Business::OnlinePayment realtime gateway. See
3786 L<http://420.am/business-onlinepayment> for supported gateways.
3788 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3790 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3792 Most gateways require a reference to an original payment transaction to refund,
3793 so you probably need to specify a I<paynum>.
3795 I<amount> defaults to the original amount of the payment if not specified.
3797 I<reason> specifies a reason for the refund.
3799 I<paydate> specifies the expiration date for a credit card overriding the
3800 value from the customer record or the payment record. Specified as yyyy-mm-dd
3802 Implementation note: If I<amount> is unspecified or equal to the amount of the
3803 orignal payment, first an attempt is made to "void" the transaction via
3804 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3805 the normal attempt is made to "refund" ("credit") the transaction via the
3806 gateway is attempted.
3808 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3809 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3810 #if set, will override the value from the customer record.
3812 #If an I<invnum> is specified, this payment (if successful) is applied to the
3813 #specified invoice. If you don't specify an I<invnum> you might want to
3814 #call the B<apply_payments> method.
3818 #some false laziness w/realtime_bop, not enough to make it worth merging
3819 #but some useful small subs should be pulled out
3820 sub realtime_refund_bop {
3821 my( $self, $method, %options ) = @_;
3823 warn "$me realtime_refund_bop: $method refund\n";
3824 warn " $_ => $options{$_}\n" foreach keys %options;
3827 eval "use Business::OnlinePayment";
3831 # look up the original payment and optionally a gateway for that payment
3835 my $amount = $options{'amount'};
3837 my( $processor, $login, $password, @bop_options ) ;
3838 my( $auth, $order_number ) = ( '', '', '' );
3840 if ( $options{'paynum'} ) {
3842 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3843 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3844 or return "Unknown paynum $options{'paynum'}";
3845 $amount ||= $cust_pay->paid;
3847 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3848 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3849 $cust_pay->paybatch;
3850 my $gatewaynum = '';
3851 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3853 if ( $gatewaynum ) { #gateway for the payment to be refunded
3855 my $payment_gateway =
3856 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3857 die "payment gateway $gatewaynum not found"
3858 unless $payment_gateway;
3860 $processor = $payment_gateway->gateway_module;
3861 $login = $payment_gateway->gateway_username;
3862 $password = $payment_gateway->gateway_password;
3863 @bop_options = $payment_gateway->options;
3865 } else { #try the default gateway
3867 my( $conf_processor, $unused_action );
3868 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3869 $self->default_payment_gateway($method);
3871 return "processor of payment $options{'paynum'} $processor does not".
3872 " match default processor $conf_processor"
3873 unless $processor eq $conf_processor;
3878 } else { # didn't specify a paynum, so look for agent gateway overrides
3879 # like a normal transaction
3882 if ( $method eq 'CC' ) {
3883 $cardtype = cardtype($self->payinfo);
3884 } elsif ( $method eq 'ECHECK' ) {
3887 $cardtype = $method;
3890 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3891 cardtype => $cardtype,
3893 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3895 taxclass => '', } );
3897 if ( $override ) { #use a payment gateway override
3899 my $payment_gateway = $override->payment_gateway;
3901 $processor = $payment_gateway->gateway_module;
3902 $login = $payment_gateway->gateway_username;
3903 $password = $payment_gateway->gateway_password;
3904 #$action = $payment_gateway->gateway_action;
3905 @bop_options = $payment_gateway->options;
3907 } else { #use the standard settings from the config
3910 ( $processor, $login, $password, $unused_action, @bop_options ) =
3911 $self->default_payment_gateway($method);
3916 return "neither amount nor paynum specified" unless $amount;
3921 'password' => $password,
3922 'order_number' => $order_number,
3923 'amount' => $amount,
3924 'referer' => 'http://cleanwhisker.420.am/',
3926 $content{authorization} = $auth
3927 if length($auth); #echeck/ACH transactions have an order # but no auth
3928 #(at least with authorize.net)
3930 my $disable_void_after;
3931 if ($conf->exists('disable_void_after')
3932 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3933 $disable_void_after = $1;
3936 #first try void if applicable
3937 if ( $cust_pay && $cust_pay->paid == $amount
3939 ( not defined($disable_void_after) )
3940 || ( time < ($cust_pay->_date + $disable_void_after ) )
3943 warn " attempting void\n" if $DEBUG > 1;
3944 my $void = new Business::OnlinePayment( $processor, @bop_options );
3945 $void->content( 'action' => 'void', %content );
3947 if ( $void->is_success ) {
3948 my $error = $cust_pay->void($options{'reason'});
3950 # gah, even with transactions.
3951 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3952 "error voiding payment: $error";
3956 warn " void successful\n" if $DEBUG > 1;
3961 warn " void unsuccessful, trying refund\n"
3965 my $address = $self->address1;
3966 $address .= ", ". $self->address2 if $self->address2;
3968 my($payname, $payfirst, $paylast);
3969 if ( $self->payname && $method ne 'ECHECK' ) {
3970 $payname = $self->payname;
3971 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3972 or return "Illegal payname $payname";
3973 ($payfirst, $paylast) = ($1, $2);
3975 $payfirst = $self->getfield('first');
3976 $paylast = $self->getfield('last');
3977 $payname = "$payfirst $paylast";
3980 my @invoicing_list = $self->invoicing_list_emailonly;
3981 if ( $conf->exists('emailinvoiceautoalways')
3982 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3983 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3984 push @invoicing_list, $self->all_emails;
3987 my $email = ($conf->exists('business-onlinepayment-email-override'))
3988 ? $conf->config('business-onlinepayment-email-override')
3989 : $invoicing_list[0];
3991 my $payip = exists($options{'payip'})
3994 $content{customer_ip} = $payip
3998 if ( $method eq 'CC' ) {
4001 $content{card_number} = $payinfo = $cust_pay->payinfo;
4002 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
4003 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
4004 ($content{expiration} = "$2/$1"); # where available
4006 $content{card_number} = $payinfo = $self->payinfo;
4007 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
4008 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4009 $content{expiration} = "$2/$1";
4012 } elsif ( $method eq 'ECHECK' ) {
4015 $payinfo = $cust_pay->payinfo;
4017 $payinfo = $self->payinfo;
4019 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
4020 $content{bank_name} = $self->payname;
4021 $content{account_type} = 'CHECKING';
4022 $content{account_name} = $payname;
4023 $content{customer_org} = $self->company ? 'B' : 'I';
4024 $content{customer_ssn} = $self->ss;
4025 } elsif ( $method eq 'LEC' ) {
4026 $content{phone} = $payinfo = $self->payinfo;
4030 my $refund = new Business::OnlinePayment( $processor, @bop_options );
4031 my %sub_content = $refund->content(
4032 'action' => 'credit',
4033 'customer_id' => $self->custnum,
4034 'last_name' => $paylast,
4035 'first_name' => $payfirst,
4037 'address' => $address,
4038 'city' => $self->city,
4039 'state' => $self->state,
4040 'zip' => $self->zip,
4041 'country' => $self->country,
4043 'phone' => $self->daytime || $self->night,
4046 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
4050 return "$processor error: ". $refund->error_message
4051 unless $refund->is_success();
4053 my %method2payby = (
4059 my $paybatch = "$processor:". $refund->authorization;
4060 $paybatch .= ':'. $refund->order_number
4061 if $refund->can('order_number') && $refund->order_number;
4063 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4064 my @cust_bill_pay = $cust_pay->cust_bill_pay;
4065 last unless @cust_bill_pay;
4066 my $cust_bill_pay = pop @cust_bill_pay;
4067 my $error = $cust_bill_pay->delete;
4071 my $cust_refund = new FS::cust_refund ( {
4072 'custnum' => $self->custnum,
4073 'paynum' => $options{'paynum'},
4074 'refund' => $amount,
4076 'payby' => $method2payby{$method},
4077 'payinfo' => $payinfo,
4078 'paybatch' => $paybatch,
4079 'reason' => $options{'reason'} || 'card or ACH refund',
4081 my $error = $cust_refund->insert;
4083 $cust_refund->paynum(''); #try again with no specific paynum
4084 my $error2 = $cust_refund->insert;
4086 # gah, even with transactions.
4087 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4088 "error inserting refund ($processor): $error2".
4089 " (previously tried insert with paynum #$options{'paynum'}" .
4100 =item batch_card OPTION => VALUE...
4102 Adds a payment for this invoice to the pending credit card batch (see
4103 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4104 runs the payment using a realtime gateway.
4109 my ($self, %options) = @_;
4112 if (exists($options{amount})) {
4113 $amount = $options{amount};
4115 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4117 return '' unless $amount > 0;
4119 my $invnum = delete $options{invnum};
4120 my $payby = $options{invnum} || $self->payby; #dubious
4122 if ($options{'realtime'}) {
4123 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4129 my $oldAutoCommit = $FS::UID::AutoCommit;
4130 local $FS::UID::AutoCommit = 0;
4133 #this needs to handle mysql as well as Pg, like svc_acct.pm
4134 #(make it into a common function if folks need to do batching with mysql)
4135 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4136 or return "Cannot lock pay_batch: " . $dbh->errstr;
4140 'payby' => FS::payby->payby2payment($payby),
4143 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4145 unless ( $pay_batch ) {
4146 $pay_batch = new FS::pay_batch \%pay_batch;
4147 my $error = $pay_batch->insert;
4149 $dbh->rollback if $oldAutoCommit;
4150 die "error creating new batch: $error\n";
4154 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4155 'batchnum' => $pay_batch->batchnum,
4156 'custnum' => $self->custnum,
4159 foreach (qw( address1 address2 city state zip country payby payinfo paydate
4161 $options{$_} = '' unless exists($options{$_});
4164 my $cust_pay_batch = new FS::cust_pay_batch ( {
4165 'batchnum' => $pay_batch->batchnum,
4166 'invnum' => $invnum || 0, # is there a better value?
4167 # this field should be
4169 # cust_bill_pay_batch now
4170 'custnum' => $self->custnum,
4171 'last' => $self->getfield('last'),
4172 'first' => $self->getfield('first'),
4173 'address1' => $options{address1} || $self->address1,
4174 'address2' => $options{address2} || $self->address2,
4175 'city' => $options{city} || $self->city,
4176 'state' => $options{state} || $self->state,
4177 'zip' => $options{zip} || $self->zip,
4178 'country' => $options{country} || $self->country,
4179 'payby' => $options{payby} || $self->payby,
4180 'payinfo' => $options{payinfo} || $self->payinfo,
4181 'exp' => $options{paydate} || $self->paydate,
4182 'payname' => $options{payname} || $self->payname,
4183 'amount' => $amount, # consolidating
4186 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4187 if $old_cust_pay_batch;
4190 if ($old_cust_pay_batch) {
4191 $error = $cust_pay_batch->replace($old_cust_pay_batch)
4193 $error = $cust_pay_batch->insert;
4197 $dbh->rollback if $oldAutoCommit;
4201 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
4202 foreach my $cust_bill ($self->open_cust_bill) {
4203 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4204 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4205 'invnum' => $cust_bill->invnum,
4206 'paybatchnum' => $cust_pay_batch->paybatchnum,
4207 'amount' => $cust_bill->owed,
4210 if ($unapplied >= $cust_bill_pay_batch->amount){
4211 $unapplied -= $cust_bill_pay_batch->amount;
4214 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4215 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4217 $error = $cust_bill_pay_batch->insert;
4219 $dbh->rollback if $oldAutoCommit;
4224 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4230 Returns the total owed for this customer on all invoices
4231 (see L<FS::cust_bill/owed>).
4237 $self->total_owed_date(2145859200); #12/31/2037
4240 =item total_owed_date TIME
4242 Returns the total owed for this customer on all invoices with date earlier than
4243 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4244 see L<Time::Local> and L<Date::Parse> for conversion functions.
4248 sub total_owed_date {
4252 foreach my $cust_bill (
4253 grep { $_->_date <= $time }
4254 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4256 $total_bill += $cust_bill->owed;
4258 sprintf( "%.2f", $total_bill );
4261 =item apply_payments_and_credits
4263 Applies unapplied payments and credits.
4265 In most cases, this new method should be used in place of sequential
4266 apply_payments and apply_credits methods.
4268 If there is an error, returns the error, otherwise returns false.
4272 sub apply_payments_and_credits {
4275 local $SIG{HUP} = 'IGNORE';
4276 local $SIG{INT} = 'IGNORE';
4277 local $SIG{QUIT} = 'IGNORE';
4278 local $SIG{TERM} = 'IGNORE';
4279 local $SIG{TSTP} = 'IGNORE';
4280 local $SIG{PIPE} = 'IGNORE';
4282 my $oldAutoCommit = $FS::UID::AutoCommit;
4283 local $FS::UID::AutoCommit = 0;
4286 $self->select_for_update; #mutex
4288 foreach my $cust_bill ( $self->open_cust_bill ) {
4289 my $error = $cust_bill->apply_payments_and_credits;
4291 $dbh->rollback if $oldAutoCommit;
4292 return "Error applying: $error";
4296 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4301 =item apply_credits OPTION => VALUE ...
4303 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4304 to outstanding invoice balances in chronological order (or reverse
4305 chronological order if the I<order> option is set to B<newest>) and returns the
4306 value of any remaining unapplied credits available for refund (see
4307 L<FS::cust_refund>).
4309 Dies if there is an error.
4317 local $SIG{HUP} = 'IGNORE';
4318 local $SIG{INT} = 'IGNORE';
4319 local $SIG{QUIT} = 'IGNORE';
4320 local $SIG{TERM} = 'IGNORE';
4321 local $SIG{TSTP} = 'IGNORE';
4322 local $SIG{PIPE} = 'IGNORE';
4324 my $oldAutoCommit = $FS::UID::AutoCommit;
4325 local $FS::UID::AutoCommit = 0;
4328 $self->select_for_update; #mutex
4330 unless ( $self->total_credited ) {
4331 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4335 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4336 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4338 my @invoices = $self->open_cust_bill;
4339 @invoices = sort { $b->_date <=> $a->_date } @invoices
4340 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4343 foreach my $cust_bill ( @invoices ) {
4346 if ( !defined($credit) || $credit->credited == 0) {
4347 $credit = pop @credits or last;
4350 if ($cust_bill->owed >= $credit->credited) {
4351 $amount=$credit->credited;
4353 $amount=$cust_bill->owed;
4356 my $cust_credit_bill = new FS::cust_credit_bill ( {
4357 'crednum' => $credit->crednum,
4358 'invnum' => $cust_bill->invnum,
4359 'amount' => $amount,
4361 my $error = $cust_credit_bill->insert;
4363 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4367 redo if ($cust_bill->owed > 0);
4371 my $total_credited = $self->total_credited;
4373 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4375 return $total_credited;
4378 =item apply_payments
4380 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4381 to outstanding invoice balances in chronological order.
4383 #and returns the value of any remaining unapplied payments.
4385 Dies if there is an error.
4389 sub apply_payments {
4392 local $SIG{HUP} = 'IGNORE';
4393 local $SIG{INT} = 'IGNORE';
4394 local $SIG{QUIT} = 'IGNORE';
4395 local $SIG{TERM} = 'IGNORE';
4396 local $SIG{TSTP} = 'IGNORE';
4397 local $SIG{PIPE} = 'IGNORE';
4399 my $oldAutoCommit = $FS::UID::AutoCommit;
4400 local $FS::UID::AutoCommit = 0;
4403 $self->select_for_update; #mutex
4407 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4408 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4410 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4411 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4415 foreach my $cust_bill ( @invoices ) {
4418 if ( !defined($payment) || $payment->unapplied == 0 ) {
4419 $payment = pop @payments or last;
4422 if ( $cust_bill->owed >= $payment->unapplied ) {
4423 $amount = $payment->unapplied;
4425 $amount = $cust_bill->owed;
4428 my $cust_bill_pay = new FS::cust_bill_pay ( {
4429 'paynum' => $payment->paynum,
4430 'invnum' => $cust_bill->invnum,
4431 'amount' => $amount,
4433 my $error = $cust_bill_pay->insert;
4435 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4439 redo if ( $cust_bill->owed > 0);
4443 my $total_unapplied_payments = $self->total_unapplied_payments;
4445 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4447 return $total_unapplied_payments;
4450 =item total_credited
4452 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4453 customer. See L<FS::cust_credit/credited>.
4457 sub total_credited {
4459 my $total_credit = 0;
4460 foreach my $cust_credit ( qsearch('cust_credit', {
4461 'custnum' => $self->custnum,
4463 $total_credit += $cust_credit->credited;
4465 sprintf( "%.2f", $total_credit );
4468 =item total_unapplied_payments
4470 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4471 See L<FS::cust_pay/unapplied>.
4475 sub total_unapplied_payments {
4477 my $total_unapplied = 0;
4478 foreach my $cust_pay ( qsearch('cust_pay', {
4479 'custnum' => $self->custnum,
4481 $total_unapplied += $cust_pay->unapplied;
4483 sprintf( "%.2f", $total_unapplied );
4486 =item total_unapplied_refunds
4488 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4489 customer. See L<FS::cust_refund/unapplied>.
4493 sub total_unapplied_refunds {
4495 my $total_unapplied = 0;
4496 foreach my $cust_refund ( qsearch('cust_refund', {
4497 'custnum' => $self->custnum,
4499 $total_unapplied += $cust_refund->unapplied;
4501 sprintf( "%.2f", $total_unapplied );
4506 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4507 total_credited minus total_unapplied_payments).
4515 + $self->total_unapplied_refunds
4516 - $self->total_credited
4517 - $self->total_unapplied_payments
4521 =item balance_date TIME
4523 Returns the balance for this customer, only considering invoices with date
4524 earlier than TIME (total_owed_date minus total_credited minus
4525 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4526 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4535 $self->total_owed_date($time)
4536 + $self->total_unapplied_refunds
4537 - $self->total_credited
4538 - $self->total_unapplied_payments
4542 =item in_transit_payments
4544 Returns the total of requests for payments for this customer pending in
4545 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4549 sub in_transit_payments {
4551 my $in_transit_payments = 0;
4552 foreach my $pay_batch ( qsearch('pay_batch', {
4555 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4556 'batchnum' => $pay_batch->batchnum,
4557 'custnum' => $self->custnum,
4559 $in_transit_payments += $cust_pay_batch->amount;
4562 sprintf( "%.2f", $in_transit_payments );
4565 =item paydate_monthyear
4567 Returns a two-element list consisting of the month and year of this customer's
4568 paydate (credit card expiration date for CARD customers)
4572 sub paydate_monthyear {
4574 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4576 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4583 =item invoicing_list [ ARRAYREF ]
4585 If an arguement is given, sets these email addresses as invoice recipients
4586 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4587 (except as warnings), so use check_invoicing_list first.
4589 Returns a list of email addresses (with svcnum entries expanded).
4591 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4592 check it without disturbing anything by passing nothing.
4594 This interface may change in the future.
4598 sub invoicing_list {
4599 my( $self, $arrayref ) = @_;
4602 my @cust_main_invoice;
4603 if ( $self->custnum ) {
4604 @cust_main_invoice =
4605 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4607 @cust_main_invoice = ();
4609 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4610 #warn $cust_main_invoice->destnum;
4611 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4612 #warn $cust_main_invoice->destnum;
4613 my $error = $cust_main_invoice->delete;
4614 warn $error if $error;
4617 if ( $self->custnum ) {
4618 @cust_main_invoice =
4619 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4621 @cust_main_invoice = ();
4623 my %seen = map { $_->address => 1 } @cust_main_invoice;
4624 foreach my $address ( @{$arrayref} ) {
4625 next if exists $seen{$address} && $seen{$address};
4626 $seen{$address} = 1;
4627 my $cust_main_invoice = new FS::cust_main_invoice ( {
4628 'custnum' => $self->custnum,
4631 my $error = $cust_main_invoice->insert;
4632 warn $error if $error;
4636 if ( $self->custnum ) {
4638 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4645 =item check_invoicing_list ARRAYREF
4647 Checks these arguements as valid input for the invoicing_list method. If there
4648 is an error, returns the error, otherwise returns false.
4652 sub check_invoicing_list {
4653 my( $self, $arrayref ) = @_;
4655 foreach my $address ( @$arrayref ) {
4657 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4658 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4661 my $cust_main_invoice = new FS::cust_main_invoice ( {
4662 'custnum' => $self->custnum,
4665 my $error = $self->custnum
4666 ? $cust_main_invoice->check
4667 : $cust_main_invoice->checkdest
4669 return $error if $error;
4673 return "Email address required"
4674 if $conf->exists('cust_main-require_invoicing_list_email')
4675 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4680 =item set_default_invoicing_list
4682 Sets the invoicing list to all accounts associated with this customer,
4683 overwriting any previous invoicing list.
4687 sub set_default_invoicing_list {
4689 $self->invoicing_list($self->all_emails);
4694 Returns the email addresses of all accounts provisioned for this customer.
4701 foreach my $cust_pkg ( $self->all_pkgs ) {
4702 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4704 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4705 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4707 $list{$_}=1 foreach map { $_->email } @svc_acct;
4712 =item invoicing_list_addpost
4714 Adds postal invoicing to this customer. If this customer is already configured
4715 to receive postal invoices, does nothing.
4719 sub invoicing_list_addpost {
4721 return if grep { $_ eq 'POST' } $self->invoicing_list;
4722 my @invoicing_list = $self->invoicing_list;
4723 push @invoicing_list, 'POST';
4724 $self->invoicing_list(\@invoicing_list);
4727 =item invoicing_list_emailonly
4729 Returns the list of email invoice recipients (invoicing_list without non-email
4730 destinations such as POST and FAX).
4734 sub invoicing_list_emailonly {
4736 warn "$me invoicing_list_emailonly called"
4738 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4741 =item invoicing_list_emailonly_scalar
4743 Returns the list of email invoice recipients (invoicing_list without non-email
4744 destinations such as POST and FAX) as a comma-separated scalar.
4748 sub invoicing_list_emailonly_scalar {
4750 warn "$me invoicing_list_emailonly_scalar called"
4752 join(', ', $self->invoicing_list_emailonly);
4755 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4757 Returns an array of customers referred by this customer (referral_custnum set
4758 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4759 customers referred by customers referred by this customer and so on, inclusive.
4760 The default behavior is DEPTH 1 (no recursion).
4764 sub referral_cust_main {
4766 my $depth = @_ ? shift : 1;
4767 my $exclude = @_ ? shift : {};
4770 map { $exclude->{$_->custnum}++; $_; }
4771 grep { ! $exclude->{ $_->custnum } }
4772 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4776 map { $_->referral_cust_main($depth-1, $exclude) }
4783 =item referral_cust_main_ncancelled
4785 Same as referral_cust_main, except only returns customers with uncancelled
4790 sub referral_cust_main_ncancelled {
4792 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4795 =item referral_cust_pkg [ DEPTH ]
4797 Like referral_cust_main, except returns a flat list of all unsuspended (and
4798 uncancelled) packages for each customer. The number of items in this list may
4799 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4803 sub referral_cust_pkg {
4805 my $depth = @_ ? shift : 1;
4807 map { $_->unsuspended_pkgs }
4808 grep { $_->unsuspended_pkgs }
4809 $self->referral_cust_main($depth);
4812 =item referring_cust_main
4814 Returns the single cust_main record for the customer who referred this customer
4815 (referral_custnum), or false.
4819 sub referring_cust_main {
4821 return '' unless $self->referral_custnum;
4822 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4825 =item credit AMOUNT, REASON
4827 Applies a credit to this customer. If there is an error, returns the error,
4828 otherwise returns false.
4833 my( $self, $amount, $reason, %options ) = @_;
4834 my $cust_credit = new FS::cust_credit {
4835 'custnum' => $self->custnum,
4836 'amount' => $amount,
4837 'reason' => $reason,
4839 $cust_credit->insert(%options);
4842 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4844 Creates a one-time charge for this customer. If there is an error, returns
4845 the error, otherwise returns false.
4851 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4852 my ( $taxproduct, $override );
4853 if ( ref( $_[0] ) ) {
4854 $amount = $_[0]->{amount};
4855 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4856 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4857 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4858 : '$'. sprintf("%.2f",$amount);
4859 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4860 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4861 $additional = $_[0]->{additional};
4862 $taxproduct = $_[0]->{taxproductnum};
4863 $override = { '' => $_[0]->{tax_override} };
4867 $pkg = @_ ? shift : 'One-time charge';
4868 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4869 $taxclass = @_ ? shift : '';
4873 local $SIG{HUP} = 'IGNORE';
4874 local $SIG{INT} = 'IGNORE';
4875 local $SIG{QUIT} = 'IGNORE';
4876 local $SIG{TERM} = 'IGNORE';
4877 local $SIG{TSTP} = 'IGNORE';
4878 local $SIG{PIPE} = 'IGNORE';
4880 my $oldAutoCommit = $FS::UID::AutoCommit;
4881 local $FS::UID::AutoCommit = 0;
4884 my $part_pkg = new FS::part_pkg ( {
4886 'comment' => $comment,
4890 'classnum' => $classnum ? $classnum : '',
4891 'taxclass' => $taxclass,
4892 'taxproductnum' => $taxproduct,
4895 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4896 ( 0 .. @$additional - 1 )
4898 'additional_count' => scalar(@$additional),
4899 'setup_fee' => $amount,
4902 my $error = $part_pkg->insert( options => \%options,
4903 tax_overrides => $override,
4906 $dbh->rollback if $oldAutoCommit;
4910 my $pkgpart = $part_pkg->pkgpart;
4911 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4912 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4913 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4914 $error = $type_pkgs->insert;
4916 $dbh->rollback if $oldAutoCommit;
4921 my $cust_pkg = new FS::cust_pkg ( {
4922 'custnum' => $self->custnum,
4923 'pkgpart' => $pkgpart,
4924 'quantity' => $quantity,
4927 $error = $cust_pkg->insert;
4929 $dbh->rollback if $oldAutoCommit;
4933 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4938 #=item charge_postal_fee
4940 #Applies a one time charge this customer. If there is an error,
4941 #returns the error, returns the cust_pkg charge object or false
4942 #if there was no charge.
4946 # This should be a customer event. For that to work requires that bill
4947 # also be a customer event.
4949 sub charge_postal_fee {
4952 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4953 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4955 my $cust_pkg = new FS::cust_pkg ( {
4956 'custnum' => $self->custnum,
4957 'pkgpart' => $pkgpart,
4961 my $error = $cust_pkg->insert;
4962 $error ? $error : $cust_pkg;
4967 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4973 sort { $a->_date <=> $b->_date }
4974 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4977 =item open_cust_bill
4979 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4984 sub open_cust_bill {
4986 grep { $_->owed > 0 } $self->cust_bill;
4991 Returns all the credits (see L<FS::cust_credit>) for this customer.
4997 sort { $a->_date <=> $b->_date }
4998 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
5003 Returns all the payments (see L<FS::cust_pay>) for this customer.
5009 sort { $a->_date <=> $b->_date }
5010 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
5015 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
5021 sort { $a->_date <=> $b->_date }
5022 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
5025 =item cust_pay_batch
5027 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
5031 sub cust_pay_batch {
5033 sort { $a->_date <=> $b->_date }
5034 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
5039 Returns all the refunds (see L<FS::cust_refund>) for this customer.
5045 sort { $a->_date <=> $b->_date }
5046 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
5051 Returns a name string for this customer, either "Company (Last, First)" or
5058 my $name = $self->contact;
5059 $name = $self->company. " ($name)" if $self->company;
5065 Returns a name string for this (service/shipping) contact, either
5066 "Company (Last, First)" or "Last, First".
5072 if ( $self->get('ship_last') ) {
5073 my $name = $self->ship_contact;
5074 $name = $self->ship_company. " ($name)" if $self->ship_company;
5083 Returns this customer's full (billing) contact name only, "Last, First"
5089 $self->get('last'). ', '. $self->first;
5094 Returns this customer's full (shipping) contact name only, "Last, First"
5100 $self->get('ship_last')
5101 ? $self->get('ship_last'). ', '. $self->ship_first
5107 Returns this customer's full country name
5113 code2country($self->country);
5116 =item geocode DATA_VENDOR
5118 Returns a value for the customer location as encoded by DATA_VENDOR.
5119 Currently this only makes sense for "CCH" as DATA_VENDOR.
5124 my ($self, $data_vendor) = (shift, shift); #always cch for now
5126 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5130 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5131 if $self->country eq 'US';
5133 #CCH specific location stuff
5134 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5137 my $cust_tax_location =
5139 'table' => 'cust_tax_location',
5140 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5141 'extra_sql' => $extra_sql,
5144 $geocode = $cust_tax_location->geocode
5145 if $cust_tax_location;
5154 Returns a status string for this customer, currently:
5158 =item prospect - No packages have ever been ordered
5160 =item active - One or more recurring packages is active
5162 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5164 =item suspended - All non-cancelled recurring packages are suspended
5166 =item cancelled - All recurring packages are cancelled
5172 sub status { shift->cust_status(@_); }
5176 for my $status (qw( prospect active inactive suspended cancelled )) {
5177 my $method = $status.'_sql';
5178 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5179 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5180 $sth->execute( ($self->custnum) x $numnum )
5181 or die "Error executing 'SELECT $sql': ". $sth->errstr;
5182 return $status if $sth->fetchrow_arrayref->[0];
5186 =item ucfirst_cust_status
5188 =item ucfirst_status
5190 Returns the status with the first character capitalized.
5194 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5196 sub ucfirst_cust_status {
5198 ucfirst($self->cust_status);
5203 Returns a hex triplet color string for this customer's status.
5207 use vars qw(%statuscolor);
5208 tie %statuscolor, 'Tie::IxHash',
5209 'prospect' => '7e0079', #'000000', #black? naw, purple
5210 'active' => '00CC00', #green
5211 'inactive' => '0000CC', #blue
5212 'suspended' => 'FF9900', #yellow
5213 'cancelled' => 'FF0000', #red
5216 sub statuscolor { shift->cust_statuscolor(@_); }
5218 sub cust_statuscolor {
5220 $statuscolor{$self->cust_status};
5225 Returns an array of hashes representing the customer's RT tickets.
5232 my $num = $conf->config('cust_main-max_tickets') || 10;
5235 unless ( $conf->config('ticket_system-custom_priority_field') ) {
5237 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5241 foreach my $priority (
5242 $conf->config('ticket_system-custom_priority_field-values'), ''
5244 last if scalar(@tickets) >= $num;
5246 @{ FS::TicketSystem->customer_tickets( $self->custnum,
5247 $num - scalar(@tickets),
5256 # Return services representing svc_accts in customer support packages
5257 sub support_services {
5259 my %packages = map { $_ => 1 } $conf->config('support_packages');
5261 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5262 grep { $_->part_svc->svcdb eq 'svc_acct' }
5263 map { $_->cust_svc }
5264 grep { exists $packages{ $_->pkgpart } }
5265 $self->ncancelled_pkgs;
5271 =head1 CLASS METHODS
5277 Class method that returns the list of possible status strings for customers
5278 (see L<the status method|/status>). For example:
5280 @statuses = FS::cust_main->statuses();
5285 #my $self = shift; #could be class...
5291 Returns an SQL expression identifying prospective cust_main records (customers
5292 with no packages ever ordered)
5296 use vars qw($select_count_pkgs);
5297 $select_count_pkgs =
5298 "SELECT COUNT(*) FROM cust_pkg
5299 WHERE cust_pkg.custnum = cust_main.custnum";
5301 sub select_count_pkgs_sql {
5305 sub prospect_sql { "
5306 0 = ( $select_count_pkgs )
5311 Returns an SQL expression identifying active cust_main records (customers with
5312 active recurring packages).
5317 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5323 Returns an SQL expression identifying inactive cust_main records (customers with
5324 no active recurring packages, but otherwise unsuspended/uncancelled).
5328 sub inactive_sql { "
5329 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5331 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5337 Returns an SQL expression identifying suspended cust_main records.
5342 sub suspended_sql { susp_sql(@_); }
5344 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5346 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5352 Returns an SQL expression identifying cancelled cust_main records.
5356 sub cancelled_sql { cancel_sql(@_); }
5359 my $recurring_sql = FS::cust_pkg->recurring_sql;
5360 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5363 0 < ( $select_count_pkgs )
5364 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
5365 AND 0 = ( $select_count_pkgs AND $recurring_sql
5366 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5368 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5374 =item uncancelled_sql
5376 Returns an SQL expression identifying un-cancelled cust_main records.
5380 sub uncancelled_sql { uncancel_sql(@_); }
5381 sub uncancel_sql { "
5382 ( 0 < ( $select_count_pkgs
5383 AND ( cust_pkg.cancel IS NULL
5384 OR cust_pkg.cancel = 0
5387 OR 0 = ( $select_count_pkgs )
5393 Returns an SQL fragment to retreive the balance.
5398 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5399 WHERE cust_bill.custnum = cust_main.custnum )
5400 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5401 WHERE cust_pay.custnum = cust_main.custnum )
5402 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5403 WHERE cust_credit.custnum = cust_main.custnum )
5404 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5405 WHERE cust_refund.custnum = cust_main.custnum )
5408 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5410 Returns an SQL fragment to retreive the balance for this customer, only
5411 considering invoices with date earlier than START_TIME, and optionally not
5412 later than END_TIME (total_owed_date minus total_credited minus
5413 total_unapplied_payments).
5415 Times are specified as SQL fragments or numeric
5416 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5417 L<Date::Parse> for conversion functions. The empty string can be passed
5418 to disable that time constraint completely.
5420 Available options are:
5424 =item unapplied_date
5426 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)
5431 set to true to remove all customer comparison clauses, for totals
5436 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5441 JOIN clause (typically used with the total option)
5447 sub balance_date_sql {
5448 my( $class, $start, $end, %opt ) = @_;
5450 my $owed = FS::cust_bill->owed_sql;
5451 my $unapp_refund = FS::cust_refund->unapplied_sql;
5452 my $unapp_credit = FS::cust_credit->unapplied_sql;
5453 my $unapp_pay = FS::cust_pay->unapplied_sql;
5455 my $j = $opt{'join'} || '';
5457 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5458 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5459 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5460 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5462 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5463 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5464 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5465 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5470 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5472 Helper method for balance_date_sql; name (and usage) subject to change
5473 (suggestions welcome).
5475 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5476 cust_refund, cust_credit or cust_pay).
5478 If TABLE is "cust_bill" or the unapplied_date option is true, only
5479 considers records with date earlier than START_TIME, and optionally not
5480 later than END_TIME .
5484 sub _money_table_where {
5485 my( $class, $table, $start, $end, %opt ) = @_;
5488 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5489 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5490 push @where, "$table._date <= $start" if defined($start) && length($start);
5491 push @where, "$table._date > $end" if defined($end) && length($end);
5493 push @where, @{$opt{'where'}} if $opt{'where'};
5494 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5500 =item search_sql HASHREF
5504 Returns a qsearch hash expression to search for parameters specified in HREF.
5505 Valid parameters are
5513 =item cancelled_pkgs
5519 listref of start date, end date
5525 =item current_balance
5527 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5531 =item flattened_pkgs
5540 my ($class, $params) = @_;
5551 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5553 "cust_main.agentnum = $1";
5560 #prospect active inactive suspended cancelled
5561 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5562 my $method = $params->{'status'}. '_sql';
5563 #push @where, $class->$method();
5564 push @where, FS::cust_main->$method();
5568 # parse cancelled package checkbox
5573 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5574 unless $params->{'cancelled_pkgs'};
5580 foreach my $field (qw( signupdate )) {
5582 next unless exists($params->{$field});
5584 my($beginning, $ending) = @{$params->{$field}};
5587 "cust_main.$field IS NOT NULL",
5588 "cust_main.$field >= $beginning",
5589 "cust_main.$field <= $ending";
5591 $orderby ||= "ORDER BY cust_main.$field";
5599 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5601 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5608 #my $balance_sql = $class->balance_sql();
5609 my $balance_sql = FS::cust_main->balance_sql();
5611 push @where, map { s/current_balance/$balance_sql/; $_ }
5612 @{ $params->{'current_balance'} };
5618 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
5620 "cust_main.custbatch = '$1'";
5624 # setup queries, subs, etc. for the search
5627 $orderby ||= 'ORDER BY custnum';
5629 # here is the agent virtualization
5630 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5632 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5634 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5636 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5638 my $select = join(', ',
5639 'cust_main.custnum',
5640 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5643 my(@extra_headers) = ();
5644 my(@extra_fields) = ();
5646 if ($params->{'flattened_pkgs'}) {
5648 if ($dbh->{Driver}->{Name} eq 'Pg') {
5650 $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";
5652 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5653 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5654 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5656 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5657 "omitting packing information from report.";
5660 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";
5662 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5663 $sth->execute() or die $sth->errstr;
5664 my $headerrow = $sth->fetchrow_arrayref;
5665 my $headercount = $headerrow ? $headerrow->[0] : 0;
5666 while($headercount) {
5667 unshift @extra_headers, "Package ". $headercount;
5668 unshift @extra_fields, eval q!sub {my $c = shift;
5669 my @a = split '\|', $c->magic;
5670 my $p = $a[!.--$headercount. q!];
5678 'table' => 'cust_main',
5679 'select' => $select,
5681 'extra_sql' => $extra_sql,
5682 'order_by' => $orderby,
5683 'count_query' => $count_query,
5684 'extra_headers' => \@extra_headers,
5685 'extra_fields' => \@extra_fields,
5690 =item email_search_sql HASHREF
5694 Emails a notice to the specified customers.
5696 Valid parameters are those of the L<search_sql> method, plus the following:
5718 Optional job queue job for status updates.
5722 Returns an error message, or false for success.
5724 If an error occurs during any email, stops the enture send and returns that
5725 error. Presumably if you're getting SMTP errors aborting is better than
5726 retrying everything.
5730 sub email_search_sql {
5731 my($class, $params) = @_;
5733 my $from = delete $params->{from};
5734 my $subject = delete $params->{subject};
5735 my $html_body = delete $params->{html_body};
5736 my $text_body = delete $params->{text_body};
5738 my $job = delete $params->{'job'};
5740 my $sql_query = $class->search_sql($params);
5742 my $count_query = delete($sql_query->{'count_query'});
5743 my $count_sth = dbh->prepare($count_query)
5744 or die "Error preparing $count_query: ". dbh->errstr;
5746 or die "Error executing $count_query: ". $count_sth->errstr;
5747 my $count_arrayref = $count_sth->fetchrow_arrayref;
5748 my $num_cust = $count_arrayref->[0];
5750 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5751 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5754 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5756 #eventually order+limit magic to reduce memory use?
5757 foreach my $cust_main ( qsearch($sql_query) ) {
5759 my $to = $cust_main->invoicing_list_emailonly_scalar;
5762 my $error = send_email(
5766 'subject' => $subject,
5767 'html_body' => $html_body,
5768 'text_body' => $text_body,
5771 return $error if $error;
5773 if ( $job ) { #progressbar foo
5775 if ( time - $min_sec > $last ) {
5776 my $error = $job->update_statustext(
5777 int( 100 * $num / $num_cust )
5779 die $error if $error;
5789 use Storable qw(thaw);
5792 sub process_email_search_sql {
5794 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5796 my $param = thaw(decode_base64(shift));
5797 warn Dumper($param) if $DEBUG;
5799 $param->{'job'} = $job;
5801 my $error = FS::cust_main->email_search_sql( $param );
5802 die $error if $error;
5806 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5808 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5809 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5810 appropriate ship_ field is also searched).
5812 Additional options are the same as FS::Record::qsearch
5817 my( $self, $fuzzy, $hash, @opt) = @_;
5822 check_and_rebuild_fuzzyfiles();
5823 foreach my $field ( keys %$fuzzy ) {
5825 my $all = $self->all_X($field);
5826 next unless scalar(@$all);
5829 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5832 foreach ( keys %match ) {
5833 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5834 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5837 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5840 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5842 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5850 Returns a masked version of the named field
5855 my ($self,$field) = @_;
5859 'x'x(length($self->getfield($field))-4).
5860 substr($self->getfield($field), (length($self->getfield($field))-4));
5870 =item smart_search OPTION => VALUE ...
5872 Accepts the following options: I<search>, the string to search for. The string
5873 will be searched for as a customer number, phone number, name or company name,
5874 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5875 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5876 skip fuzzy matching when an exact match is found.
5878 Any additional options are treated as an additional qualifier on the search
5881 Returns a (possibly empty) array of FS::cust_main objects.
5888 #here is the agent virtualization
5889 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5893 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5894 my $search = delete $options{'search'};
5895 ( my $alphanum_search = $search ) =~ s/\W//g;
5897 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5899 #false laziness w/Record::ut_phone
5900 my $phonen = "$1-$2-$3";
5901 $phonen .= " x$4" if $4;
5903 push @cust_main, qsearch( {
5904 'table' => 'cust_main',
5905 'hashref' => { %options },
5906 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5908 join(' OR ', map "$_ = '$phonen'",
5909 qw( daytime night fax
5910 ship_daytime ship_night ship_fax )
5913 " AND $agentnums_sql", #agent virtualization
5916 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5917 #try looking for matches with extensions unless one was specified
5919 push @cust_main, qsearch( {
5920 'table' => 'cust_main',
5921 'hashref' => { %options },
5922 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5924 join(' OR ', map "$_ LIKE '$phonen\%'",
5926 ship_daytime ship_night )
5929 " AND $agentnums_sql", #agent virtualization
5934 # custnum search (also try agent_custid), with some tweaking options if your
5935 # legacy cust "numbers" have letters
5936 } elsif ( $search =~ /^\s*(\d+)\s*$/
5937 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5938 && $search =~ /^\s*(\w\w?\d+)\s*$/
5943 push @cust_main, qsearch( {
5944 'table' => 'cust_main',
5945 'hashref' => { 'custnum' => $1, %options },
5946 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5949 push @cust_main, qsearch( {
5950 'table' => 'cust_main',
5951 'hashref' => { 'agent_custid' => $1, %options },
5952 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5955 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5957 my($company, $last, $first) = ( $1, $2, $3 );
5959 # "Company (Last, First)"
5960 #this is probably something a browser remembered,
5961 #so just do an exact search
5963 foreach my $prefix ( '', 'ship_' ) {
5964 push @cust_main, qsearch( {
5965 'table' => 'cust_main',
5966 'hashref' => { $prefix.'first' => $first,
5967 $prefix.'last' => $last,
5968 $prefix.'company' => $company,
5971 'extra_sql' => " AND $agentnums_sql",
5975 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5976 # try (ship_){last,company}
5980 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5981 # # full strings the browser remembers won't work
5982 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5984 use Lingua::EN::NameParse;
5985 my $NameParse = new Lingua::EN::NameParse(
5987 allow_reversed => 1,
5990 my($last, $first) = ( '', '' );
5991 #maybe disable this too and just rely on NameParse?
5992 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5994 ($last, $first) = ( $1, $2 );
5996 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5997 } elsif ( ! $NameParse->parse($value) ) {
5999 my %name = $NameParse->components;
6000 $first = $name{'given_name_1'};
6001 $last = $name{'surname_1'};
6005 if ( $first && $last ) {
6007 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
6010 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6012 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
6013 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
6016 push @cust_main, qsearch( {
6017 'table' => 'cust_main',
6018 'hashref' => \%options,
6019 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6022 # or it just be something that was typed in... (try that in a sec)
6026 my $q_value = dbh->quote($value);
6029 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6030 $sql .= " ( LOWER(last) = $q_value
6031 OR LOWER(company) = $q_value
6032 OR LOWER(ship_last) = $q_value
6033 OR LOWER(ship_company) = $q_value
6036 push @cust_main, qsearch( {
6037 'table' => 'cust_main',
6038 'hashref' => \%options,
6039 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6042 #no exact match, trying substring/fuzzy
6043 #always do substring & fuzzy (unless they're explicity config'ed off)
6044 #getting complaints searches are not returning enough
6045 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
6047 #still some false laziness w/search_sql (was search/cust_main.cgi)
6052 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
6053 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
6056 if ( $first && $last ) {
6059 { 'first' => { op=>'ILIKE', value=>"%$first%" },
6060 'last' => { op=>'ILIKE', value=>"%$last%" },
6062 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
6063 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
6070 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
6071 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
6075 foreach my $hashref ( @hashrefs ) {
6077 push @cust_main, qsearch( {
6078 'table' => 'cust_main',
6079 'hashref' => { %$hashref,
6082 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6091 " AND $agentnums_sql", #extra_sql #agent virtualization
6094 if ( $first && $last ) {
6095 push @cust_main, FS::cust_main->fuzzy_search(
6096 { 'last' => $last, #fuzzy hashref
6097 'first' => $first }, #
6101 foreach my $field ( 'last', 'company' ) {
6103 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6108 #eliminate duplicates
6110 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6120 Accepts the following options: I<email>, the email address to search for. The
6121 email address will be searched for as an email invoice destination and as an
6124 #Any additional options are treated as an additional qualifier on the search
6125 #(i.e. I<agentnum>).
6127 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6137 my $email = delete $options{'email'};
6139 #we're only being used by RT at the moment... no agent virtualization yet
6140 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6144 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6146 my ( $user, $domain ) = ( $1, $2 );
6148 warn "$me smart_search: searching for $user in domain $domain"
6154 'table' => 'cust_main_invoice',
6155 'hashref' => { 'dest' => $email },
6162 map $_->cust_svc->cust_pkg,
6164 'table' => 'svc_acct',
6165 'hashref' => { 'username' => $user, },
6167 'AND ( SELECT domain FROM svc_domain
6168 WHERE svc_acct.domsvc = svc_domain.svcnum
6169 ) = '. dbh->quote($domain),
6175 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6177 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6184 =item check_and_rebuild_fuzzyfiles
6188 use vars qw(@fuzzyfields);
6189 @fuzzyfields = ( 'last', 'first', 'company' );
6191 sub check_and_rebuild_fuzzyfiles {
6192 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6193 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6196 =item rebuild_fuzzyfiles
6200 sub rebuild_fuzzyfiles {
6202 use Fcntl qw(:flock);
6204 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6205 mkdir $dir, 0700 unless -d $dir;
6207 foreach my $fuzzy ( @fuzzyfields ) {
6209 open(LOCK,">>$dir/cust_main.$fuzzy")
6210 or die "can't open $dir/cust_main.$fuzzy: $!";
6212 or die "can't lock $dir/cust_main.$fuzzy: $!";
6214 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6215 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6217 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6218 my $sth = dbh->prepare("SELECT $field FROM cust_main".
6219 " WHERE $field != '' AND $field IS NOT NULL");
6220 $sth->execute or die $sth->errstr;
6222 while ( my $row = $sth->fetchrow_arrayref ) {
6223 print CACHE $row->[0]. "\n";
6228 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6230 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6241 my( $self, $field ) = @_;
6242 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6243 open(CACHE,"<$dir/cust_main.$field")
6244 or die "can't open $dir/cust_main.$field: $!";
6245 my @array = map { chomp; $_; } <CACHE>;
6250 =item append_fuzzyfiles LASTNAME COMPANY
6254 sub append_fuzzyfiles {
6255 #my( $first, $last, $company ) = @_;
6257 &check_and_rebuild_fuzzyfiles;
6259 use Fcntl qw(:flock);
6261 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6263 foreach my $field (qw( first last company )) {
6268 open(CACHE,">>$dir/cust_main.$field")
6269 or die "can't open $dir/cust_main.$field: $!";
6270 flock(CACHE,LOCK_EX)
6271 or die "can't lock $dir/cust_main.$field: $!";
6273 print CACHE "$value\n";
6275 flock(CACHE,LOCK_UN)
6276 or die "can't unlock $dir/cust_main.$field: $!";
6285 =item process_batch_import
6287 Load a batch import as a queued JSRPC job
6291 use Storable qw(thaw);
6294 sub process_batch_import {
6297 my $param = thaw(decode_base64(shift));
6298 warn Dumper($param) if $DEBUG;
6300 my $files = $param->{'uploaded_files'}
6301 or die "No files provided.\n";
6303 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
6305 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
6306 my $file = $dir. $files{'file'};
6309 if ( $file =~ /\.(\w+)$/i ) {
6313 warn "can't parse file type from filename $file; defaulting to CSV";
6318 FS::cust_main::batch_import( {
6322 custbatch => $param->{custbatch},
6323 agentnum => $param->{'agentnum'},
6324 refnum => $param->{'refnum'},
6325 pkgpart => $param->{'pkgpart'},
6326 #'fields' => [qw( cust_pkg.setup dayphone first last address1 address2
6327 # city state zip comments )],
6328 'format' => $param->{'format'},
6333 die "$error\n" if $error;
6341 #some false laziness w/cdr.pm now
6345 my $job = $param->{job};
6347 my $filename = $param->{file};
6348 my $type = $param->{type} || 'csv';
6350 my $custbatch = $param->{custbatch};
6352 my $agentnum = $param->{agentnum};
6353 my $refnum = $param->{refnum};
6354 my $pkgpart = $param->{pkgpart};
6356 my $format = $param->{'format'};
6360 if ( $format eq 'simple' ) {
6361 @fields = qw( cust_pkg.setup dayphone first last
6362 address1 address2 city state zip comments );
6364 } elsif ( $format eq 'extended' ) {
6365 @fields = qw( agent_custid refnum
6366 last first address1 address2 city state zip country
6368 ship_last ship_first ship_address1 ship_address2
6369 ship_city ship_state ship_zip ship_country
6370 payinfo paycvv paydate
6373 svc_acct.username svc_acct._password
6376 } elsif ( $format eq 'extended-plus_company' ) {
6377 @fields = qw( agent_custid refnum
6378 last first company address1 address2 city state zip country
6380 ship_last ship_first ship_company ship_address1 ship_address2
6381 ship_city ship_state ship_zip ship_country
6382 payinfo paycvv paydate
6385 svc_acct.username svc_acct._password
6389 die "unknown format $format";
6395 if ( $type eq 'csv' ) {
6397 eval "use Text::CSV_XS;";
6400 $parser = new Text::CSV_XS;
6402 @buffer = split(/\r?\n/, slurp($filename) );
6403 $count = scalar(@buffer);
6405 } elsif ( $type eq 'xls' ) {
6407 eval "use Spreadsheet::ParseExcel;";
6410 my $excel = new Spreadsheet::ParseExcel::Workbook->Parse($filename);
6411 $parser = $excel->{Worksheet}[0]; #first sheet
6413 $count = $parser->{MaxRow} || $parser->{MinRow};
6417 die "Unknown file type $type\n";
6422 local $SIG{HUP} = 'IGNORE';
6423 local $SIG{INT} = 'IGNORE';
6424 local $SIG{QUIT} = 'IGNORE';
6425 local $SIG{TERM} = 'IGNORE';
6426 local $SIG{TSTP} = 'IGNORE';
6427 local $SIG{PIPE} = 'IGNORE';
6429 my $oldAutoCommit = $FS::UID::AutoCommit;
6430 local $FS::UID::AutoCommit = 0;
6435 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
6439 if ( $type eq 'csv' ) {
6441 last unless scalar(@buffer);
6442 $line = shift(@buffer);
6444 $parser->parse($line) or do {
6445 $dbh->rollback if $oldAutoCommit;
6446 return "can't parse: ". $parser->error_input();
6448 @columns = $parser->fields();
6450 } elsif ( $type eq 'xls' ) {
6452 last if $row > ($parser->{MaxRow} || $parser->{MinRow});
6454 my @row = @{ $parser->{Cells}[$row] };
6455 @columns = map $_->{Val}, @row;
6458 #warn $z++. ": $_\n" for @columns;
6461 die "Unknown file type $type\n";
6464 #warn join('-',@columns);
6467 custbatch => $custbatch,
6468 agentnum => $agentnum,
6470 country => $conf->config('countrydefault') || 'US',
6471 payby => $payby, #default
6472 paydate => '12/2037', #default
6474 my $billtime = time;
6475 my %cust_pkg = ( pkgpart => $pkgpart );
6477 foreach my $field ( @fields ) {
6479 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
6481 #$cust_pkg{$1} = str2time( shift @$columns );
6482 if ( $1 eq 'pkgpart' ) {
6483 $cust_pkg{$1} = shift @columns;
6484 } elsif ( $1 eq 'setup' ) {
6485 $billtime = str2time(shift @columns);
6487 $cust_pkg{$1} = str2time( shift @columns );
6490 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
6492 $svc_acct{$1} = shift @columns;
6496 #refnum interception
6497 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
6499 my $referral = $columns[0];
6500 my %hash = ( 'referral' => $referral,
6501 'agentnum' => $agentnum,
6505 my $part_referral = qsearchs('part_referral', \%hash )
6506 || new FS::part_referral \%hash;
6508 unless ( $part_referral->refnum ) {
6509 my $error = $part_referral->insert;
6511 $dbh->rollback if $oldAutoCommit;
6512 return "can't auto-insert advertising source: $referral: $error";
6516 $columns[0] = $part_referral->refnum;
6519 my $value = shift @columns;
6520 $cust_main{$field} = $value if length($value);
6524 $cust_main{'payby'} = 'CARD'
6525 if defined $cust_main{'payinfo'}
6526 && length $cust_main{'payinfo'};
6528 my $invoicing_list = $cust_main{'invoicing_list'}
6529 ? [ delete $cust_main{'invoicing_list'} ]
6532 my $cust_main = new FS::cust_main ( \%cust_main );
6535 tie my %hash, 'Tie::RefHash'; #this part is important
6537 if ( $cust_pkg{'pkgpart'} ) {
6538 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
6541 if ( $svc_acct{'username'} ) {
6542 my $part_pkg = $cust_pkg->part_pkg;
6543 unless ( $part_pkg ) {
6544 $dbh->rollback if $oldAutoCommit;
6545 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
6547 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
6548 push @svc_acct, new FS::svc_acct ( \%svc_acct )
6551 $hash{$cust_pkg} = \@svc_acct;
6554 my $error = $cust_main->insert( \%hash, $invoicing_list );
6557 $dbh->rollback if $oldAutoCommit;
6558 return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
6561 if ( $format eq 'simple' ) {
6563 #false laziness w/bill.cgi
6564 $error = $cust_main->bill( 'time' => $billtime );
6566 $dbh->rollback if $oldAutoCommit;
6567 return "can't bill customer for $line: $error";
6570 $error = $cust_main->apply_payments_and_credits;
6572 $dbh->rollback if $oldAutoCommit;
6573 return "can't bill customer for $line: $error";
6576 $error = $cust_main->collect();
6578 $dbh->rollback if $oldAutoCommit;
6579 return "can't collect customer for $line: $error";
6586 if ( $job && time - $min_sec > $last ) { #progress bar
6587 $job->update_statustext( int(100 * $row / $count) );
6593 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
6595 return "Empty file!" unless $row;
6607 #warn join('-',keys %$param);
6608 my $fh = $param->{filehandle};
6609 my @fields = @{$param->{fields}};
6611 eval "use Text::CSV_XS;";
6614 my $csv = new Text::CSV_XS;
6621 local $SIG{HUP} = 'IGNORE';
6622 local $SIG{INT} = 'IGNORE';
6623 local $SIG{QUIT} = 'IGNORE';
6624 local $SIG{TERM} = 'IGNORE';
6625 local $SIG{TSTP} = 'IGNORE';
6626 local $SIG{PIPE} = 'IGNORE';
6628 my $oldAutoCommit = $FS::UID::AutoCommit;
6629 local $FS::UID::AutoCommit = 0;
6632 #while ( $columns = $csv->getline($fh) ) {
6634 while ( defined($line=<$fh>) ) {
6636 $csv->parse($line) or do {
6637 $dbh->rollback if $oldAutoCommit;
6638 return "can't parse: ". $csv->error_input();
6641 my @columns = $csv->fields();
6642 #warn join('-',@columns);
6645 foreach my $field ( @fields ) {
6646 $row{$field} = shift @columns;
6649 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6650 unless ( $cust_main ) {
6651 $dbh->rollback if $oldAutoCommit;
6652 return "unknown custnum $row{'custnum'}";
6655 if ( $row{'amount'} > 0 ) {
6656 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6658 $dbh->rollback if $oldAutoCommit;
6662 } elsif ( $row{'amount'} < 0 ) {
6663 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6666 $dbh->rollback if $oldAutoCommit;
6676 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6678 return "Empty file!" unless $imported;
6684 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6686 Sends a templated email notification to the customer (see L<Text::Template>).
6688 OPTIONS is a hash and may include
6690 I<from> - the email sender (default is invoice_from)
6692 I<to> - comma-separated scalar or arrayref of recipients
6693 (default is invoicing_list)
6695 I<subject> - The subject line of the sent email notification
6696 (default is "Notice from company_name")
6698 I<extra_fields> - a hashref of name/value pairs which will be substituted
6701 The following variables are vavailable in the template.
6703 I<$first> - the customer first name
6704 I<$last> - the customer last name
6705 I<$company> - the customer company
6706 I<$payby> - a description of the method of payment for the customer
6707 # would be nice to use FS::payby::shortname
6708 I<$payinfo> - the account information used to collect for this customer
6709 I<$expdate> - the expiration of the customer payment in seconds from epoch
6714 my ($customer, $template, %options) = @_;
6716 return unless $conf->exists($template);
6718 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6719 $from = $options{from} if exists($options{from});
6721 my $to = join(',', $customer->invoicing_list_emailonly);
6722 $to = $options{to} if exists($options{to});
6724 my $subject = "Notice from " . $conf->config('company_name')
6725 if $conf->exists('company_name');
6726 $subject = $options{subject} if exists($options{subject});
6728 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6729 SOURCE => [ map "$_\n",
6730 $conf->config($template)]
6732 or die "can't create new Text::Template object: Text::Template::ERROR";
6733 $notify_template->compile()
6734 or die "can't compile template: Text::Template::ERROR";
6736 $FS::notify_template::_template::company_name = $conf->config('company_name');
6737 $FS::notify_template::_template::company_address =
6738 join("\n", $conf->config('company_address') ). "\n";
6740 my $paydate = $customer->paydate || '2037-12-31';
6741 $FS::notify_template::_template::first = $customer->first;
6742 $FS::notify_template::_template::last = $customer->last;
6743 $FS::notify_template::_template::company = $customer->company;
6744 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6745 my $payby = $customer->payby;
6746 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6747 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6749 #credit cards expire at the end of the month/year of their exp date
6750 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6751 $FS::notify_template::_template::payby = 'credit card';
6752 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6753 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6755 }elsif ($payby eq 'COMP') {
6756 $FS::notify_template::_template::payby = 'complimentary account';
6758 $FS::notify_template::_template::payby = 'current method';
6760 $FS::notify_template::_template::expdate = $expire_time;
6762 for (keys %{$options{extra_fields}}){
6764 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6767 send_email(from => $from,
6769 subject => $subject,
6770 body => $notify_template->fill_in( PACKAGE =>
6771 'FS::notify_template::_template' ),
6776 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6778 Generates a templated notification to the customer (see L<Text::Template>).
6780 OPTIONS is a hash and may include
6782 I<extra_fields> - a hashref of name/value pairs which will be substituted
6783 into the template. These values may override values mentioned below
6784 and those from the customer record.
6786 The following variables are available in the template instead of or in addition
6787 to the fields of the customer record.
6789 I<$payby> - a description of the method of payment for the customer
6790 # would be nice to use FS::payby::shortname
6791 I<$payinfo> - the masked account information used to collect for this customer
6792 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6793 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6797 sub generate_letter {
6798 my ($self, $template, %options) = @_;
6800 return unless $conf->exists($template);
6802 my $letter_template = new Text::Template
6804 SOURCE => [ map "$_\n", $conf->config($template)],
6805 DELIMITERS => [ '[@--', '--@]' ],
6807 or die "can't create new Text::Template object: Text::Template::ERROR";
6809 $letter_template->compile()
6810 or die "can't compile template: Text::Template::ERROR";
6812 my %letter_data = map { $_ => $self->$_ } $self->fields;
6813 $letter_data{payinfo} = $self->mask_payinfo;
6815 #my $paydate = $self->paydate || '2037-12-31';
6816 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6818 my $payby = $self->payby;
6819 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6820 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6822 #credit cards expire at the end of the month/year of their exp date
6823 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6824 $letter_data{payby} = 'credit card';
6825 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6826 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6828 }elsif ($payby eq 'COMP') {
6829 $letter_data{payby} = 'complimentary account';
6831 $letter_data{payby} = 'current method';
6833 $letter_data{expdate} = $expire_time;
6835 for (keys %{$options{extra_fields}}){
6836 $letter_data{$_} = $options{extra_fields}->{$_};
6839 unless(exists($letter_data{returnaddress})){
6840 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6841 $self->agent_template)
6843 if ( length($retadd) ) {
6844 $letter_data{returnaddress} = $retadd;
6845 } elsif ( grep /\S/, $conf->config('company_address') ) {
6846 $letter_data{returnaddress} =
6847 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6848 $conf->config('company_address')
6851 $letter_data{returnaddress} = '~';
6855 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6857 $letter_data{company_name} = $conf->config('company_name');
6859 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6860 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6864 ) or die "can't open temp file: $!\n";
6866 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6868 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6872 =item print_ps TEMPLATE
6874 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6880 my $file = $self->generate_letter(@_);
6881 FS::Misc::generate_ps($file);
6884 =item print TEMPLATE
6886 Prints the filled in template.
6888 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6892 sub queueable_print {
6895 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6896 or die "invalid customer number: " . $opt{custvnum};
6898 my $error = $self->print( $opt{template} );
6899 die $error if $error;
6903 my ($self, $template) = (shift, shift);
6904 do_print [ $self->print_ps($template) ];
6907 sub agent_template {
6909 $self->_agent_plandata('agent_templatename');
6912 sub agent_invoice_from {
6914 $self->_agent_plandata('agent_invoice_from');
6917 sub _agent_plandata {
6918 my( $self, $option ) = @_;
6920 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6921 #agent-specific Conf
6923 use FS::part_event::Condition;
6925 my $agentnum = $self->agentnum;
6928 if ( driver_name =~ /^Pg/i ) {
6930 } elsif ( driver_name =~ /^mysql/i ) {
6933 die "don't know how to use regular expressions in ". driver_name. " databases";
6936 my $part_event_option =
6938 'select' => 'part_event_option.*',
6939 'table' => 'part_event_option',
6941 LEFT JOIN part_event USING ( eventpart )
6942 LEFT JOIN part_event_option AS peo_agentnum
6943 ON ( part_event.eventpart = peo_agentnum.eventpart
6944 AND peo_agentnum.optionname = 'agentnum'
6945 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6947 LEFT JOIN part_event_option AS peo_cust_bill_age
6948 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6949 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6952 #'hashref' => { 'optionname' => $option },
6953 #'hashref' => { 'part_event_option.optionname' => $option },
6955 " WHERE part_event_option.optionname = ". dbh->quote($option).
6956 " AND action = 'cust_bill_send_agent' ".
6957 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6958 " AND peo_agentnum.optionname = 'agentnum' ".
6959 " AND agentnum IS NULL OR agentnum = $agentnum ".
6961 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6963 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6965 , part_event.weight".
6969 unless ( $part_event_option ) {
6970 return $self->agent->invoice_template || ''
6971 if $option eq 'agent_templatename';
6975 $part_event_option->optionvalue;
6980 ## actual sub, not a method, designed to be called from the queue.
6981 ## sets up the customer, and calls the bill_and_collect
6982 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6983 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6984 $cust_main->bill_and_collect(
6995 The delete method should possibly take an FS::cust_main object reference
6996 instead of a scalar customer number.
6998 Bill and collect options should probably be passed as references instead of a
7001 There should probably be a configuration file with a list of allowed credit
7004 No multiple currency support (probably a larger project than just this module).
7006 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
7008 Birthdates rely on negative epoch values.
7010 The payby for card/check batches is broken. With mixed batching, bad
7013 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
7017 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
7018 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
7019 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.