4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5 $import $skip_fuzzyfiles $ignore_expired_card );
6 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 eval "use Time::Local;";
12 die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
13 if $] < 5.006 && !defined($Time::Local::VERSION);
14 #eval "use Time::Local qw(timelocal timelocal_nocheck);";
15 eval "use Time::Local qw(timelocal_nocheck);";
17 use Digest::MD5 qw(md5_base64);
21 use String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
24 use FS::UID qw( getotaker dbh );
25 use FS::Record qw( qsearchs qsearch dbdef );
26 use FS::Misc qw( send_email );
27 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
33 use FS::cust_pay_void;
36 use FS::part_referral;
37 use FS::cust_main_county;
39 use FS::cust_main_invoice;
40 use FS::cust_credit_bill;
41 use FS::cust_bill_pay;
42 use FS::prepay_credit;
45 use FS::part_bill_event qw(due_events);
46 use FS::cust_bill_event;
47 use FS::cust_tax_exempt;
48 use FS::cust_tax_exempt_pkg;
50 use FS::payment_gateway;
51 use FS::agent_payment_gateway;
53 use FS::payinfo_Mixin;
55 @ISA = qw( FS::Record FS::payinfo_Mixin );
57 @EXPORT_OK = qw( smart_search );
59 $realtime_bop_decline_quiet = 0;
61 # 1 is mostly method/subroutine entry and options
62 # 2 traces progress of some operations
63 # 3 is even more information including possibly sensitive data
65 $me = '[FS::cust_main]';
69 $ignore_expired_card = 0;
71 @encrypted_fields = ('payinfo', 'paycvv');
73 #ask FS::UID to run this stuff for us later
74 #$FS::UID::callback{'FS::cust_main'} = sub {
75 install_callback FS::UID sub {
77 #yes, need it for stuff below (prolly should be cached)
82 my ( $hashref, $cache ) = @_;
83 if ( exists $hashref->{'pkgnum'} ) {
84 #@{ $self->{'_pkgnum'} } = ();
85 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
86 $self->{'_pkgnum'} = $subcache;
87 #push @{ $self->{'_pkgnum'} },
88 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
94 FS::cust_main - Object methods for cust_main records
100 $record = new FS::cust_main \%hash;
101 $record = new FS::cust_main { 'column' => 'value' };
103 $error = $record->insert;
105 $error = $new_record->replace($old_record);
107 $error = $record->delete;
109 $error = $record->check;
111 @cust_pkg = $record->all_pkgs;
113 @cust_pkg = $record->ncancelled_pkgs;
115 @cust_pkg = $record->suspended_pkgs;
117 $error = $record->bill;
118 $error = $record->bill %options;
119 $error = $record->bill 'time' => $time;
121 $error = $record->collect;
122 $error = $record->collect %options;
123 $error = $record->collect 'invoice_time' => $time,
128 An FS::cust_main object represents a customer. FS::cust_main inherits from
129 FS::Record. The following fields are currently supported:
133 =item custnum - primary key (assigned automatically for new customers)
135 =item agentnum - agent (see L<FS::agent>)
137 =item refnum - Advertising source (see L<FS::part_referral>)
143 =item ss - social security number (optional)
145 =item company - (optional)
149 =item address2 - (optional)
153 =item county - (optional, see L<FS::cust_main_county>)
155 =item state - (see L<FS::cust_main_county>)
159 =item country - (see L<FS::cust_main_county>)
161 =item daytime - phone (optional)
163 =item night - phone (optional)
165 =item fax - phone (optional)
167 =item ship_first - name
169 =item ship_last - name
171 =item ship_company - (optional)
175 =item ship_address2 - (optional)
179 =item ship_county - (optional, see L<FS::cust_main_county>)
181 =item ship_state - (see L<FS::cust_main_county>)
185 =item ship_country - (see L<FS::cust_main_county>)
187 =item ship_daytime - phone (optional)
189 =item ship_night - phone (optional)
191 =item ship_fax - phone (optional)
193 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
195 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
197 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
201 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
203 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
205 =item paystart_month - start date month (maestro/solo cards only)
207 =item paystart_year - start date year (maestro/solo cards only)
209 =item payissue - issue number (maestro/solo cards only)
211 =item payname - name on card or billing name
213 =item payip - IP address from which payment information was received
215 =item tax - tax exempt, empty or `Y'
217 =item otaker - order taker (assigned automatically, see L<FS::UID>)
219 =item comments - comments (optional)
221 =item referral_custnum - referring customer number
223 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
233 Creates a new customer. To add the customer to the database, see L<"insert">.
235 Note that this stores the hash reference, not a distinct copy of the hash it
236 points to. You can ask the object for a copy with the I<hash> method.
240 sub table { 'cust_main'; }
242 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
244 Adds this customer to the database. If there is an error, returns the error,
245 otherwise returns false.
247 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
248 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
249 are inserted atomicly, or the transaction is rolled back. Passing an empty
250 hash reference is equivalent to not supplying this parameter. There should be
251 a better explanation of this, but until then, here's an example:
254 tie %hash, 'Tie::RefHash'; #this part is important
256 $cust_pkg => [ $svc_acct ],
259 $cust_main->insert( \%hash );
261 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
262 be set as the invoicing list (see L<"invoicing_list">). Errors return as
263 expected and rollback the entire transaction; it is not necessary to call
264 check_invoicing_list first. The invoicing_list is set after the records in the
265 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
266 invoicing_list destination to the newly-created svc_acct. Here's an example:
268 $cust_main->insert( {}, [ $email, 'POST' ] );
270 Currently available options are: I<depend_jobnum> and I<noexport>.
272 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
273 on the supplied jobnum (they will not run until the specific job completes).
274 This can be used to defer provisioning until some action completes (such
275 as running the customer's credit card successfully).
277 The I<noexport> option is deprecated. If I<noexport> is set true, no
278 provisioning jobs (exports) are scheduled. (You can schedule them later with
279 the B<reexport> method.)
285 my $cust_pkgs = @_ ? shift : {};
286 my $invoicing_list = @_ ? shift : '';
288 warn "$me insert called with options ".
289 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
292 local $SIG{HUP} = 'IGNORE';
293 local $SIG{INT} = 'IGNORE';
294 local $SIG{QUIT} = 'IGNORE';
295 local $SIG{TERM} = 'IGNORE';
296 local $SIG{TSTP} = 'IGNORE';
297 local $SIG{PIPE} = 'IGNORE';
299 my $oldAutoCommit = $FS::UID::AutoCommit;
300 local $FS::UID::AutoCommit = 0;
303 my $prepay_identifier = '';
304 my( $amount, $seconds ) = ( 0, 0 );
306 if ( $self->payby eq 'PREPAY' ) {
308 $self->payby('BILL');
309 $prepay_identifier = $self->payinfo;
312 warn " looking up prepaid card $prepay_identifier\n"
315 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
317 $dbh->rollback if $oldAutoCommit;
318 #return "error applying prepaid card (transaction rolled back): $error";
322 $payby = 'PREP' if $amount;
324 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
327 $self->payby('BILL');
328 $amount = $self->paid;
332 warn " inserting $self\n"
335 $self->signupdate(time) unless $self->signupdate;
337 my $error = $self->SUPER::insert;
339 $dbh->rollback if $oldAutoCommit;
340 #return "inserting cust_main record (transaction rolled back): $error";
344 warn " setting invoicing list\n"
347 if ( $invoicing_list ) {
348 $error = $self->check_invoicing_list( $invoicing_list );
350 $dbh->rollback if $oldAutoCommit;
351 return "checking invoicing_list (transaction rolled back): $error";
353 $self->invoicing_list( $invoicing_list );
356 if ( $conf->config('cust_main-skeleton_tables')
357 && $conf->config('cust_main-skeleton_custnum') ) {
359 warn " inserting skeleton records\n"
362 my $error = $self->start_copy_skel;
364 $dbh->rollback if $oldAutoCommit;
370 warn " ordering packages\n"
373 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
375 $dbh->rollback if $oldAutoCommit;
380 $dbh->rollback if $oldAutoCommit;
381 return "No svc_acct record to apply pre-paid time";
385 warn " inserting initial $payby payment of $amount\n"
387 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
389 $dbh->rollback if $oldAutoCommit;
390 return "inserting payment (transaction rolled back): $error";
394 unless ( $import || $skip_fuzzyfiles ) {
395 warn " queueing fuzzyfiles update\n"
397 $error = $self->queue_fuzzyfiles_update;
399 $dbh->rollback if $oldAutoCommit;
400 return "updating fuzzy search cache: $error";
404 warn " insert complete; committing transaction\n"
407 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
412 sub start_copy_skel {
415 #'mg_user_preference' => {},
416 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
417 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
418 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
419 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
420 my @tables = eval($conf->config_binary('cust_main-skeleton_tables'));
423 _copy_skel( 'cust_main', #tablename
424 $conf->config('cust_main-skeleton_custnum'), #sourceid
425 $self->custnum, #destid
426 @tables, #child tables
430 #recursive subroutine, not a method
432 my( $table, $sourceid, $destid, %child_tables ) = @_;
435 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
436 ( $table, $primary_key ) = ( $1, $2 );
438 my $dbdef_table = dbdef->table($table);
439 $primary_key = $dbdef_table->primary_key
440 or return "$table has no primary key".
441 " (or do you need to run dbdef-create?)";
444 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
445 join (', ', keys %child_tables). "\n"
448 foreach my $child_table_def ( keys %child_tables ) {
452 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
453 ( $child_table, $child_pkey ) = ( $1, $2 );
455 $child_table = $child_table_def;
457 $child_pkey = dbdef->table($child_table)->primary_key;
458 # or return "$table has no primary key".
459 # " (or do you need to run dbdef-create?)\n";
463 if ( keys %{ $child_tables{$child_table_def} } ) {
465 return "$child_table has no primary key".
466 " (run dbdef-create or try specifying it?)\n"
469 #false laziness w/Record::insert and only works on Pg
470 #refactor the proper last-inserted-id stuff out of Record::insert if this
471 # ever gets use for anything besides a quick kludge for one customer
472 my $default = dbdef->table($child_table)->column($child_pkey)->default;
473 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
474 or return "can't parse $child_table.$child_pkey default value ".
475 " for sequence name: $default";
480 my @sel_columns = grep { $_ ne $primary_key }
481 dbdef->table($child_table)->columns;
482 my $sel_columns = join(', ', @sel_columns );
484 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
485 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
486 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
488 my $sel_st = "SELECT $sel_columns FROM $child_table".
489 " WHERE $primary_key = $sourceid";
492 my $sel_sth = dbh->prepare( $sel_st )
493 or return dbh->errstr;
495 $sel_sth->execute or return $sel_sth->errstr;
497 while ( my $row = $sel_sth->fetchrow_hashref ) {
499 warn " selected row: ".
500 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
504 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
505 my $ins_sth =dbh->prepare($statement)
506 or return dbh->errstr;
507 my @param = ( $destid, map $row->{$_}, @ins_columns );
508 warn " $statement: [ ". join(', ', @param). " ]\n"
510 $ins_sth->execute( @param )
511 or return $ins_sth->errstr;
513 #next unless keys %{ $child_tables{$child_table} };
514 next unless $sequence;
516 #another section of that laziness
517 my $seq_sql = "SELECT currval('$sequence')";
518 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
519 $seq_sth->execute or return $seq_sth->errstr;
520 my $insertid = $seq_sth->fetchrow_arrayref->[0];
522 # don't drink soap! recurse! recurse! okay!
524 _copy_skel( $child_table_def,
525 $row->{$child_pkey}, #sourceid
527 %{ $child_tables{$child_table_def} },
529 return $error if $error;
539 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
541 Like the insert method on an existing record, this method orders a package
542 and included services atomicaly. Pass a Tie::RefHash data structure to this
543 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
544 be a better explanation of this, but until then, here's an example:
547 tie %hash, 'Tie::RefHash'; #this part is important
549 $cust_pkg => [ $svc_acct ],
552 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
554 Services can be new, in which case they are inserted, or existing unaudited
555 services, in which case they are linked to the newly-created package.
557 Currently available options are: I<depend_jobnum> and I<noexport>.
559 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
560 on the supplied jobnum (they will not run until the specific job completes).
561 This can be used to defer provisioning until some action completes (such
562 as running the customer's credit card successfully).
564 The I<noexport> option is deprecated. If I<noexport> is set true, no
565 provisioning jobs (exports) are scheduled. (You can schedule them later with
566 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
567 on the cust_main object is not recommended, as existing services will also be
574 my $cust_pkgs = shift;
577 my %svc_options = ();
578 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
579 if exists $options{'depend_jobnum'};
580 warn "$me order_pkgs called with options ".
581 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
584 local $SIG{HUP} = 'IGNORE';
585 local $SIG{INT} = 'IGNORE';
586 local $SIG{QUIT} = 'IGNORE';
587 local $SIG{TERM} = 'IGNORE';
588 local $SIG{TSTP} = 'IGNORE';
589 local $SIG{PIPE} = 'IGNORE';
591 my $oldAutoCommit = $FS::UID::AutoCommit;
592 local $FS::UID::AutoCommit = 0;
595 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
597 foreach my $cust_pkg ( keys %$cust_pkgs ) {
598 $cust_pkg->custnum( $self->custnum );
599 my $error = $cust_pkg->insert;
601 $dbh->rollback if $oldAutoCommit;
602 return "inserting cust_pkg (transaction rolled back): $error";
604 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
605 if ( $svc_something->svcnum ) {
606 my $old_cust_svc = $svc_something->cust_svc;
607 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
608 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
609 $error = $new_cust_svc->replace($old_cust_svc);
611 $svc_something->pkgnum( $cust_pkg->pkgnum );
612 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
613 $svc_something->seconds( $svc_something->seconds + $$seconds );
616 $error = $svc_something->insert(%svc_options);
619 $dbh->rollback if $oldAutoCommit;
620 #return "inserting svc_ (transaction rolled back): $error";
626 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
630 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
632 Recharges this (existing) customer with the specified prepaid card (see
633 L<FS::prepay_credit>), specified either by I<identifier> or as an
634 FS::prepay_credit object. If there is an error, returns the error, otherwise
637 Optionally, four scalar references can be passed as well. They will have their
638 values filled in with the amount, number of seconds, and number of upload and
639 download bytes applied by this prepaid
644 sub recharge_prepay {
645 my( $self, $prepay_credit, $amountref, $secondsref,
646 $upbytesref, $downbytesref, $totalbytesref ) = @_;
648 local $SIG{HUP} = 'IGNORE';
649 local $SIG{INT} = 'IGNORE';
650 local $SIG{QUIT} = 'IGNORE';
651 local $SIG{TERM} = 'IGNORE';
652 local $SIG{TSTP} = 'IGNORE';
653 local $SIG{PIPE} = 'IGNORE';
655 my $oldAutoCommit = $FS::UID::AutoCommit;
656 local $FS::UID::AutoCommit = 0;
659 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
661 my $error = $self->get_prepay($prepay_credit, \$amount,
662 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
663 || $self->increment_seconds($seconds)
664 || $self->increment_upbytes($upbytes)
665 || $self->increment_downbytes($downbytes)
666 || $self->increment_totalbytes($totalbytes)
667 || $self->insert_cust_pay_prepay( $amount,
669 ? $prepay_credit->identifier
674 $dbh->rollback if $oldAutoCommit;
678 if ( defined($amountref) ) { $$amountref = $amount; }
679 if ( defined($secondsref) ) { $$secondsref = $seconds; }
680 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
681 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
682 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
684 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
689 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
691 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
692 specified either by I<identifier> or as an FS::prepay_credit object.
694 References to I<amount> and I<seconds> scalars should be passed as arguments
695 and will be incremented by the values of the prepaid card.
697 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
698 check or set this customer's I<agentnum>.
700 If there is an error, returns the error, otherwise returns false.
706 my( $self, $prepay_credit, $amountref, $secondsref,
707 $upref, $downref, $totalref) = @_;
709 local $SIG{HUP} = 'IGNORE';
710 local $SIG{INT} = 'IGNORE';
711 local $SIG{QUIT} = 'IGNORE';
712 local $SIG{TERM} = 'IGNORE';
713 local $SIG{TSTP} = 'IGNORE';
714 local $SIG{PIPE} = 'IGNORE';
716 my $oldAutoCommit = $FS::UID::AutoCommit;
717 local $FS::UID::AutoCommit = 0;
720 unless ( ref($prepay_credit) ) {
722 my $identifier = $prepay_credit;
724 $prepay_credit = qsearchs(
726 { 'identifier' => $prepay_credit },
731 unless ( $prepay_credit ) {
732 $dbh->rollback if $oldAutoCommit;
733 return "Invalid prepaid card: ". $identifier;
738 if ( $prepay_credit->agentnum ) {
739 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
740 $dbh->rollback if $oldAutoCommit;
741 return "prepaid card not valid for agent ". $self->agentnum;
743 $self->agentnum($prepay_credit->agentnum);
746 my $error = $prepay_credit->delete;
748 $dbh->rollback if $oldAutoCommit;
749 return "removing prepay_credit (transaction rolled back): $error";
752 $$amountref += $prepay_credit->amount;
753 $$secondsref += $prepay_credit->seconds;
754 $$upref += $prepay_credit->upbytes;
755 $$downref += $prepay_credit->downbytes;
756 $$totalref += $prepay_credit->totalbytes;
758 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
763 =item increment_upbytes SECONDS
765 Updates this customer's single or primary account (see L<FS::svc_acct>) by
766 the specified number of upbytes. If there is an error, returns the error,
767 otherwise returns false.
771 sub increment_upbytes {
772 _increment_column( shift, 'upbytes', @_);
775 =item increment_downbytes SECONDS
777 Updates this customer's single or primary account (see L<FS::svc_acct>) by
778 the specified number of downbytes. If there is an error, returns the error,
779 otherwise returns false.
783 sub increment_downbytes {
784 _increment_column( shift, 'downbytes', @_);
787 =item increment_totalbytes SECONDS
789 Updates this customer's single or primary account (see L<FS::svc_acct>) by
790 the specified number of totalbytes. If there is an error, returns the error,
791 otherwise returns false.
795 sub increment_totalbytes {
796 _increment_column( shift, 'totalbytes', @_);
799 =item increment_seconds SECONDS
801 Updates this customer's single or primary account (see L<FS::svc_acct>) by
802 the specified number of seconds. If there is an error, returns the error,
803 otherwise returns false.
807 sub increment_seconds {
808 _increment_column( shift, 'seconds', @_);
811 =item _increment_column AMOUNT
813 Updates this customer's single or primary account (see L<FS::svc_acct>) by
814 the specified number of seconds or bytes. If there is an error, returns
815 the error, otherwise returns false.
819 sub _increment_column {
820 my( $self, $column, $amount ) = @_;
821 warn "$me increment_column called: $column, $amount\n"
824 return '' unless $amount;
826 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
827 $self->ncancelled_pkgs;
830 return 'No packages with primary or single services found'.
831 ' to apply pre-paid time';
832 } elsif ( scalar(@cust_pkg) > 1 ) {
833 #maybe have a way to specify the package/account?
834 return 'Multiple packages found to apply pre-paid time';
837 my $cust_pkg = $cust_pkg[0];
838 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
842 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
845 return 'No account found to apply pre-paid time';
846 } elsif ( scalar(@cust_svc) > 1 ) {
847 return 'Multiple accounts found to apply pre-paid time';
850 my $svc_acct = $cust_svc[0]->svc_x;
851 warn " found service svcnum ". $svc_acct->pkgnum.
852 ' ('. $svc_acct->email. ")\n"
855 $column = "increment_$column";
856 $svc_acct->$column($amount);
860 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
862 Inserts a prepayment in the specified amount for this customer. An optional
863 second argument can specify the prepayment identifier for tracking purposes.
864 If there is an error, returns the error, otherwise returns false.
868 sub insert_cust_pay_prepay {
869 shift->insert_cust_pay('PREP', @_);
872 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
874 Inserts a cash payment in the specified amount for this customer. An optional
875 second argument can specify the payment identifier for tracking purposes.
876 If there is an error, returns the error, otherwise returns false.
880 sub insert_cust_pay_cash {
881 shift->insert_cust_pay('CASH', @_);
884 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
886 Inserts a Western Union payment in the specified amount for this customer. An
887 optional second argument can specify the prepayment identifier for tracking
888 purposes. If there is an error, returns the error, otherwise returns false.
892 sub insert_cust_pay_west {
893 shift->insert_cust_pay('WEST', @_);
896 sub insert_cust_pay {
897 my( $self, $payby, $amount ) = splice(@_, 0, 3);
898 my $payinfo = scalar(@_) ? shift : '';
900 my $cust_pay = new FS::cust_pay {
901 'custnum' => $self->custnum,
902 'paid' => sprintf('%.2f', $amount),
903 #'_date' => #date the prepaid card was purchased???
905 'payinfo' => $payinfo,
913 This method is deprecated. See the I<depend_jobnum> option to the insert and
914 order_pkgs methods for a better way to defer provisioning.
916 Re-schedules all exports by calling the B<reexport> method of all associated
917 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
918 otherwise returns false.
925 carp "WARNING: FS::cust_main::reexport is deprectated; ".
926 "use the depend_jobnum option to insert or order_pkgs to delay export";
928 local $SIG{HUP} = 'IGNORE';
929 local $SIG{INT} = 'IGNORE';
930 local $SIG{QUIT} = 'IGNORE';
931 local $SIG{TERM} = 'IGNORE';
932 local $SIG{TSTP} = 'IGNORE';
933 local $SIG{PIPE} = 'IGNORE';
935 my $oldAutoCommit = $FS::UID::AutoCommit;
936 local $FS::UID::AutoCommit = 0;
939 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
940 my $error = $cust_pkg->reexport;
942 $dbh->rollback if $oldAutoCommit;
947 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
952 =item delete NEW_CUSTNUM
954 This deletes the customer. If there is an error, returns the error, otherwise
957 This will completely remove all traces of the customer record. This is not
958 what you want when a customer cancels service; for that, cancel all of the
959 customer's packages (see L</cancel>).
961 If the customer has any uncancelled packages, you need to pass a new (valid)
962 customer number for those packages to be transferred to. Cancelled packages
963 will be deleted. Did I mention that this is NOT what you want when a customer
964 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
966 You can't delete a customer with invoices (see L<FS::cust_bill>),
967 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
968 refunds (see L<FS::cust_refund>).
975 local $SIG{HUP} = 'IGNORE';
976 local $SIG{INT} = 'IGNORE';
977 local $SIG{QUIT} = 'IGNORE';
978 local $SIG{TERM} = 'IGNORE';
979 local $SIG{TSTP} = 'IGNORE';
980 local $SIG{PIPE} = 'IGNORE';
982 my $oldAutoCommit = $FS::UID::AutoCommit;
983 local $FS::UID::AutoCommit = 0;
986 if ( $self->cust_bill ) {
987 $dbh->rollback if $oldAutoCommit;
988 return "Can't delete a customer with invoices";
990 if ( $self->cust_credit ) {
991 $dbh->rollback if $oldAutoCommit;
992 return "Can't delete a customer with credits";
994 if ( $self->cust_pay ) {
995 $dbh->rollback if $oldAutoCommit;
996 return "Can't delete a customer with payments";
998 if ( $self->cust_refund ) {
999 $dbh->rollback if $oldAutoCommit;
1000 return "Can't delete a customer with refunds";
1003 my @cust_pkg = $self->ncancelled_pkgs;
1005 my $new_custnum = shift;
1006 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1007 $dbh->rollback if $oldAutoCommit;
1008 return "Invalid new customer number: $new_custnum";
1010 foreach my $cust_pkg ( @cust_pkg ) {
1011 my %hash = $cust_pkg->hash;
1012 $hash{'custnum'} = $new_custnum;
1013 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1014 my $error = $new_cust_pkg->replace($cust_pkg,
1015 options => { $cust_pkg->options },
1018 $dbh->rollback if $oldAutoCommit;
1023 my @cancelled_cust_pkg = $self->all_pkgs;
1024 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1025 my $error = $cust_pkg->delete;
1027 $dbh->rollback if $oldAutoCommit;
1032 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1033 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1035 my $error = $cust_main_invoice->delete;
1037 $dbh->rollback if $oldAutoCommit;
1042 my $error = $self->SUPER::delete;
1044 $dbh->rollback if $oldAutoCommit;
1048 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1053 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1055 Replaces the OLD_RECORD with this one in the database. If there is an error,
1056 returns the error, otherwise returns false.
1058 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1059 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1060 expected and rollback the entire transaction; it is not necessary to call
1061 check_invoicing_list first. Here's an example:
1063 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1071 warn "$me replace called\n"
1074 local $SIG{HUP} = 'IGNORE';
1075 local $SIG{INT} = 'IGNORE';
1076 local $SIG{QUIT} = 'IGNORE';
1077 local $SIG{TERM} = 'IGNORE';
1078 local $SIG{TSTP} = 'IGNORE';
1079 local $SIG{PIPE} = 'IGNORE';
1081 # We absolutely have to have an old vs. new record to make this work.
1082 if (!defined($old)) {
1083 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1086 my $curuser = $FS::CurrentUser::CurrentUser;
1087 if ( $self->payby eq 'COMP'
1088 && $self->payby ne $old->payby
1089 && ! $curuser->access_right('Complimentary customer')
1092 return "You are not permitted to create complimentary accounts.";
1095 local($ignore_expired_card) = 1
1096 if $old->payby =~ /^(CARD|DCRD)$/
1097 && $self->payby =~ /^(CARD|DCRD)$/
1098 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1100 my $oldAutoCommit = $FS::UID::AutoCommit;
1101 local $FS::UID::AutoCommit = 0;
1104 my $error = $self->SUPER::replace($old);
1107 $dbh->rollback if $oldAutoCommit;
1111 if ( @param ) { # INVOICING_LIST_ARYREF
1112 my $invoicing_list = shift @param;
1113 $error = $self->check_invoicing_list( $invoicing_list );
1115 $dbh->rollback if $oldAutoCommit;
1118 $self->invoicing_list( $invoicing_list );
1121 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1122 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1123 # card/check/lec info has changed, want to retry realtime_ invoice events
1124 my $error = $self->retry_realtime;
1126 $dbh->rollback if $oldAutoCommit;
1131 unless ( $import || $skip_fuzzyfiles ) {
1132 $error = $self->queue_fuzzyfiles_update;
1134 $dbh->rollback if $oldAutoCommit;
1135 return "updating fuzzy search cache: $error";
1139 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1144 =item queue_fuzzyfiles_update
1146 Used by insert & replace to update the fuzzy search cache
1150 sub queue_fuzzyfiles_update {
1153 local $SIG{HUP} = 'IGNORE';
1154 local $SIG{INT} = 'IGNORE';
1155 local $SIG{QUIT} = 'IGNORE';
1156 local $SIG{TERM} = 'IGNORE';
1157 local $SIG{TSTP} = 'IGNORE';
1158 local $SIG{PIPE} = 'IGNORE';
1160 my $oldAutoCommit = $FS::UID::AutoCommit;
1161 local $FS::UID::AutoCommit = 0;
1164 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1165 my $error = $queue->insert( map $self->getfield($_),
1166 qw(first last company)
1169 $dbh->rollback if $oldAutoCommit;
1170 return "queueing job (transaction rolled back): $error";
1173 if ( $self->ship_last ) {
1174 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1175 $error = $queue->insert( map $self->getfield("ship_$_"),
1176 qw(first last company)
1179 $dbh->rollback if $oldAutoCommit;
1180 return "queueing job (transaction rolled back): $error";
1184 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1191 Checks all fields to make sure this is a valid customer record. If there is
1192 an error, returns the error, otherwise returns false. Called by the insert
1193 and replace methods.
1200 warn "$me check BEFORE: \n". $self->_dump
1204 $self->ut_numbern('custnum')
1205 || $self->ut_number('agentnum')
1206 || $self->ut_textn('agent_custid')
1207 || $self->ut_number('refnum')
1208 || $self->ut_name('last')
1209 || $self->ut_name('first')
1210 || $self->ut_snumbern('birthdate')
1211 || $self->ut_snumbern('signupdate')
1212 || $self->ut_textn('company')
1213 || $self->ut_text('address1')
1214 || $self->ut_textn('address2')
1215 || $self->ut_text('city')
1216 || $self->ut_textn('county')
1217 || $self->ut_textn('state')
1218 || $self->ut_country('country')
1219 || $self->ut_anything('comments')
1220 || $self->ut_numbern('referral_custnum')
1222 #barf. need message catalogs. i18n. etc.
1223 $error .= "Please select an advertising source."
1224 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1225 return $error if $error;
1227 return "Unknown agent"
1228 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1230 return "Unknown refnum"
1231 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1233 return "Unknown referring custnum: ". $self->referral_custnum
1234 unless ! $self->referral_custnum
1235 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1237 if ( $self->ss eq '' ) {
1242 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1243 or return "Illegal social security number: ". $self->ss;
1244 $self->ss("$1-$2-$3");
1248 # bad idea to disable, causes billing to fail because of no tax rates later
1249 # unless ( $import ) {
1250 unless ( qsearch('cust_main_county', {
1251 'country' => $self->country,
1254 return "Unknown state/county/country: ".
1255 $self->state. "/". $self->county. "/". $self->country
1256 unless qsearch('cust_main_county',{
1257 'state' => $self->state,
1258 'county' => $self->county,
1259 'country' => $self->country,
1265 $self->ut_phonen('daytime', $self->country)
1266 || $self->ut_phonen('night', $self->country)
1267 || $self->ut_phonen('fax', $self->country)
1268 || $self->ut_zip('zip', $self->country)
1270 return $error if $error;
1273 last first company address1 address2 city county state zip
1274 country daytime night fax
1277 if ( defined $self->dbdef_table->column('ship_last') ) {
1278 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1280 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1284 $self->ut_name('ship_last')
1285 || $self->ut_name('ship_first')
1286 || $self->ut_textn('ship_company')
1287 || $self->ut_text('ship_address1')
1288 || $self->ut_textn('ship_address2')
1289 || $self->ut_text('ship_city')
1290 || $self->ut_textn('ship_county')
1291 || $self->ut_textn('ship_state')
1292 || $self->ut_country('ship_country')
1294 return $error if $error;
1296 #false laziness with above
1297 unless ( qsearchs('cust_main_county', {
1298 'country' => $self->ship_country,
1301 return "Unknown ship_state/ship_county/ship_country: ".
1302 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1303 unless qsearch('cust_main_county',{
1304 'state' => $self->ship_state,
1305 'county' => $self->ship_county,
1306 'country' => $self->ship_country,
1312 $self->ut_phonen('ship_daytime', $self->ship_country)
1313 || $self->ut_phonen('ship_night', $self->ship_country)
1314 || $self->ut_phonen('ship_fax', $self->ship_country)
1315 || $self->ut_zip('ship_zip', $self->ship_country)
1317 return $error if $error;
1319 } else { # ship_ info eq billing info, so don't store dup info in database
1320 $self->setfield("ship_$_", '')
1321 foreach qw( last first company address1 address2 city county state zip
1322 country daytime night fax );
1326 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1327 # or return "Illegal payby: ". $self->payby;
1329 FS::payby->can_payby($self->table, $self->payby)
1330 or return "Illegal payby: ". $self->payby;
1332 $error = $self->ut_numbern('paystart_month')
1333 || $self->ut_numbern('paystart_year')
1334 || $self->ut_numbern('payissue')
1336 return $error if $error;
1338 if ( $self->payip eq '' ) {
1341 $error = $self->ut_ip('payip');
1342 return $error if $error;
1345 # If it is encrypted and the private key is not availaible then we can't
1346 # check the credit card.
1348 my $check_payinfo = 1;
1350 if ($self->is_encrypted($self->payinfo)) {
1354 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1356 my $payinfo = $self->payinfo;
1357 $payinfo =~ s/\D//g;
1358 $payinfo =~ /^(\d{13,16})$/
1359 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1361 $self->payinfo($payinfo);
1363 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1365 return gettext('unknown_card_type')
1366 if cardtype($self->payinfo) eq "Unknown";
1368 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1370 return 'Banned credit card: banned on '.
1371 time2str('%a %h %o at %r', $ban->_date).
1372 ' by '. $ban->otaker.
1373 ' (ban# '. $ban->bannum. ')';
1376 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1377 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1378 $self->paycvv =~ /^(\d{4})$/
1379 or return "CVV2 (CID) for American Express cards is four digits.";
1382 $self->paycvv =~ /^(\d{3})$/
1383 or return "CVV2 (CVC2/CID) is three digits.";
1390 my $cardtype = cardtype($payinfo);
1391 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1393 return "Start date or issue number is required for $cardtype cards"
1394 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1396 return "Start month must be between 1 and 12"
1397 if $self->paystart_month
1398 and $self->paystart_month < 1 || $self->paystart_month > 12;
1400 return "Start year must be 1990 or later"
1401 if $self->paystart_year
1402 and $self->paystart_year < 1990;
1404 return "Issue number must be beween 1 and 99"
1406 and $self->payissue < 1 || $self->payissue > 99;
1409 $self->paystart_month('');
1410 $self->paystart_year('');
1411 $self->payissue('');
1414 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1416 my $payinfo = $self->payinfo;
1417 $payinfo =~ s/[^\d\@]//g;
1418 if ( $conf->exists('echeck-nonus') ) {
1419 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1420 $payinfo = "$1\@$2";
1422 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1423 $payinfo = "$1\@$2";
1425 $self->payinfo($payinfo);
1428 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1430 return 'Banned ACH account: banned on '.
1431 time2str('%a %h %o at %r', $ban->_date).
1432 ' by '. $ban->otaker.
1433 ' (ban# '. $ban->bannum. ')';
1436 } elsif ( $self->payby eq 'LECB' ) {
1438 my $payinfo = $self->payinfo;
1439 $payinfo =~ s/\D//g;
1440 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1442 $self->payinfo($payinfo);
1445 } elsif ( $self->payby eq 'BILL' ) {
1447 $error = $self->ut_textn('payinfo');
1448 return "Illegal P.O. number: ". $self->payinfo if $error;
1451 } elsif ( $self->payby eq 'COMP' ) {
1453 my $curuser = $FS::CurrentUser::CurrentUser;
1454 if ( ! $self->custnum
1455 && ! $curuser->access_right('Complimentary customer')
1458 return "You are not permitted to create complimentary accounts."
1461 $error = $self->ut_textn('payinfo');
1462 return "Illegal comp account issuer: ". $self->payinfo if $error;
1465 } elsif ( $self->payby eq 'PREPAY' ) {
1467 my $payinfo = $self->payinfo;
1468 $payinfo =~ s/\W//g; #anything else would just confuse things
1469 $self->payinfo($payinfo);
1470 $error = $self->ut_alpha('payinfo');
1471 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1472 return "Unknown prepayment identifier"
1473 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1478 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1479 return "Expiration date required"
1480 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1484 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1485 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1486 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1487 ( $m, $y ) = ( $3, "20$2" );
1489 return "Illegal expiration date: ". $self->paydate;
1491 $self->paydate("$y-$m-01");
1492 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1493 return gettext('expired_card')
1495 && !$ignore_expired_card
1496 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1499 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1500 ( ! $conf->exists('require_cardname')
1501 || $self->payby !~ /^(CARD|DCRD)$/ )
1503 $self->payname( $self->first. " ". $self->getfield('last') );
1505 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1506 or return gettext('illegal_name'). " payname: ". $self->payname;
1510 foreach my $flag (qw( tax spool_cdr )) {
1511 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1515 $self->otaker(getotaker) unless $self->otaker;
1517 warn "$me check AFTER: \n". $self->_dump
1520 $self->SUPER::check;
1525 Returns all packages (see L<FS::cust_pkg>) for this customer.
1532 return $self->num_pkgs unless wantarray;
1535 if ( $self->{'_pkgnum'} ) {
1536 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1538 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1541 sort sort_packages @cust_pkg;
1544 =item ncancelled_pkgs
1546 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1550 sub ncancelled_pkgs {
1553 return $self->num_ncancelled_pkgs unless wantarray;
1556 if ( $self->{'_pkgnum'} ) {
1558 @cust_pkg = grep { ! $_->getfield('cancel') }
1559 values %{ $self->{'_pkgnum'}->cache };
1564 qsearch( 'cust_pkg', {
1565 'custnum' => $self->custnum,
1569 qsearch( 'cust_pkg', {
1570 'custnum' => $self->custnum,
1575 sort sort_packages @cust_pkg;
1579 # This should be generalized to use config options to determine order.
1581 if ( $a->get('cancel') and $b->get('cancel') ) {
1582 $a->pkgnum <=> $b->pkgnum;
1583 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1584 return -1 if $b->get('cancel');
1585 return 1 if $a->get('cancel');
1588 $a->pkgnum <=> $b->pkgnum;
1592 =item suspended_pkgs
1594 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1598 sub suspended_pkgs {
1600 grep { $_->susp } $self->ncancelled_pkgs;
1603 =item unflagged_suspended_pkgs
1605 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1606 customer (thouse packages without the `manual_flag' set).
1610 sub unflagged_suspended_pkgs {
1612 return $self->suspended_pkgs
1613 unless dbdef->table('cust_pkg')->column('manual_flag');
1614 grep { ! $_->manual_flag } $self->suspended_pkgs;
1617 =item unsuspended_pkgs
1619 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1624 sub unsuspended_pkgs {
1626 grep { ! $_->susp } $self->ncancelled_pkgs;
1629 =item num_cancelled_pkgs
1631 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1636 sub num_cancelled_pkgs {
1637 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1640 sub num_ncancelled_pkgs {
1641 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1645 my( $self, $sql ) = @_;
1646 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1647 my $sth = dbh->prepare(
1648 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1649 ) or die dbh->errstr;
1650 $sth->execute($self->custnum) or die $sth->errstr;
1651 $sth->fetchrow_arrayref->[0];
1656 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1657 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1658 on success or a list of errors.
1664 grep { $_->unsuspend } $self->suspended_pkgs;
1669 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1671 Returns a list: an empty list on success or a list of errors.
1677 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1680 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1682 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1683 PKGPARTs (see L<FS::part_pkg>).
1685 Returns a list: an empty list on success or a list of errors.
1689 sub suspend_if_pkgpart {
1691 my (@pkgparts, %opt);
1692 if (ref($_[0]) eq 'HASH'){
1693 @pkgparts = @{$_[0]{pkgparts}};
1698 grep { $_->suspend(%opt) }
1699 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1700 $self->unsuspended_pkgs;
1703 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1705 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1706 listed PKGPARTs (see L<FS::part_pkg>).
1708 Returns a list: an empty list on success or a list of errors.
1712 sub suspend_unless_pkgpart {
1714 my (@pkgparts, %opt);
1715 if (ref($_[0]) eq 'HASH'){
1716 @pkgparts = @{$_[0]{pkgparts}};
1721 grep { $_->suspend(%opt) }
1722 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1723 $self->unsuspended_pkgs;
1726 =item cancel [ OPTION => VALUE ... ]
1728 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1730 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1732 I<quiet> can be set true to supress email cancellation notices.
1734 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1736 I<ban> can be set true to ban this customer's credit card or ACH information,
1739 Always returns a list: an empty list on success or a list of errors.
1747 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1749 #should try decryption (we might have the private key)
1750 # and if not maybe queue a job for the server that does?
1751 return ( "Can't (yet) ban encrypted credit cards" )
1752 if $self->is_encrypted($self->payinfo);
1754 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1755 my $error = $ban->insert;
1756 return ( $error ) if $error;
1760 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1763 sub _banned_pay_hashref {
1774 'payby' => $payby2ban{$self->payby},
1775 'payinfo' => md5_base64($self->payinfo),
1776 #don't ever *search* on reason! #'reason' =>
1782 Returns all notes (see L<FS::cust_main_note>) for this customer.
1789 qsearch( 'cust_main_note',
1790 { 'custnum' => $self->custnum },
1792 'ORDER BY _DATE DESC'
1798 Returns the agent (see L<FS::agent>) for this customer.
1804 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1809 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1810 conjunction with the collect method.
1812 Options are passed as name-value pairs.
1814 Currently available options are:
1816 resetup - if set true, re-charges setup fees.
1818 time - bills the customer as if it were that time. Specified as a UNIX
1819 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1820 L<Date::Parse> for conversion functions. For example:
1824 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1827 If there is an error, returns the error, otherwise returns false.
1832 my( $self, %options ) = @_;
1833 return '' if $self->payby eq 'COMP';
1834 warn "$me bill customer ". $self->custnum. "\n"
1837 my $time = $options{'time'} || time;
1842 local $SIG{HUP} = 'IGNORE';
1843 local $SIG{INT} = 'IGNORE';
1844 local $SIG{QUIT} = 'IGNORE';
1845 local $SIG{TERM} = 'IGNORE';
1846 local $SIG{TSTP} = 'IGNORE';
1847 local $SIG{PIPE} = 'IGNORE';
1849 my $oldAutoCommit = $FS::UID::AutoCommit;
1850 local $FS::UID::AutoCommit = 0;
1853 $self->select_for_update; #mutex
1855 #create a new invoice
1856 #(we'll remove it later if it doesn't actually need to be generated [contains
1857 # no line items] and we're inside a transaciton so nothing else will see it)
1858 my $cust_bill = new FS::cust_bill ( {
1859 'custnum' => $self->custnum,
1861 #'charged' => $charged,
1864 $error = $cust_bill->insert;
1866 $dbh->rollback if $oldAutoCommit;
1867 return "can't create invoice for customer #". $self->custnum. ": $error";
1869 my $invnum = $cust_bill->invnum;
1872 # find the packages which are due for billing, find out how much they are
1873 # & generate invoice database.
1876 my( $total_setup, $total_recur ) = ( 0, 0 );
1878 my @precommit_hooks = ();
1880 foreach my $cust_pkg (
1881 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1884 #NO!! next if $cust_pkg->cancel;
1885 next if $cust_pkg->getfield('cancel');
1887 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1889 #? to avoid use of uninitialized value errors... ?
1890 $cust_pkg->setfield('bill', '')
1891 unless defined($cust_pkg->bill);
1893 my $part_pkg = $cust_pkg->part_pkg;
1895 my %hash = $cust_pkg->hash;
1896 my $old_cust_pkg = new FS::cust_pkg \%hash;
1905 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1907 warn " bill setup\n" if $DEBUG > 1;
1909 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
1911 $dbh->rollback if $oldAutoCommit;
1912 return "$@ running calc_setup for $cust_pkg\n";
1915 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1919 # bill recurring fee
1924 if ( $part_pkg->getfield('freq') ne '0' &&
1925 ! $cust_pkg->getfield('susp') &&
1926 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1929 warn " bill recur\n" if $DEBUG > 1;
1931 # XXX shared with $recur_prog
1932 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1934 #over two params! lets at least switch to a hashref for the rest...
1935 my %param = ( 'precommit_hooks' => \@precommit_hooks, );
1937 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
1939 $dbh->rollback if $oldAutoCommit;
1940 return "$@ running calc_recur for $cust_pkg\n";
1943 #change this bit to use Date::Manip? CAREFUL with timezones (see
1944 # mailing list archive)
1945 my ($sec,$min,$hour,$mday,$mon,$year) =
1946 (localtime($sdate) )[0,1,2,3,4,5];
1948 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1949 # only for figuring next bill date, nothing else, so, reset $sdate again
1951 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1952 $cust_pkg->last_bill($sdate)
1953 if $cust_pkg->dbdef_table->column('last_bill');
1955 if ( $part_pkg->freq =~ /^\d+$/ ) {
1956 $mon += $part_pkg->freq;
1957 until ( $mon < 12 ) { $mon -= 12; $year++; }
1958 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1960 $mday += $weeks * 7;
1961 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1964 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
1968 $dbh->rollback if $oldAutoCommit;
1969 return "unparsable frequency: ". $part_pkg->freq;
1971 $cust_pkg->setfield('bill',
1972 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1975 warn "\$setup is undefined" unless defined($setup);
1976 warn "\$recur is undefined" unless defined($recur);
1977 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1980 # If $cust_pkg has been modified, update it and create cust_bill_pkg records
1983 if ( $cust_pkg->modified ) { # hmmm.. and if the options are modified?
1985 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
1988 $error=$cust_pkg->replace($old_cust_pkg,
1989 options => { $cust_pkg->options },
1991 if ( $error ) { #just in case
1992 $dbh->rollback if $oldAutoCommit;
1993 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1996 $setup = sprintf( "%.2f", $setup );
1997 $recur = sprintf( "%.2f", $recur );
1998 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1999 $dbh->rollback if $oldAutoCommit;
2000 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2002 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2003 $dbh->rollback if $oldAutoCommit;
2004 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2007 if ( $setup != 0 || $recur != 0 ) {
2009 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2011 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2012 'invnum' => $invnum,
2013 'pkgnum' => $cust_pkg->pkgnum,
2017 'edate' => $cust_pkg->bill,
2018 'details' => \@details,
2020 $error = $cust_bill_pkg->insert;
2022 $dbh->rollback if $oldAutoCommit;
2023 return "can't create invoice line item for invoice #$invnum: $error";
2025 $total_setup += $setup;
2026 $total_recur += $recur;
2032 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2035 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2038 my %taxhash = map { $_ => $self->get("$prefix$_") }
2039 qw( state county country );
2041 $taxhash{'taxclass'} = $part_pkg->taxclass;
2043 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2046 $taxhash{'taxclass'} = '';
2047 @taxes = qsearch( 'cust_main_county', \%taxhash );
2050 #one more try at a whole-country tax rate
2052 $taxhash{$_} = '' foreach qw( state county );
2053 @taxes = qsearch( 'cust_main_county', \%taxhash );
2056 # maybe eliminate this entirely, along with all the 0% records
2058 $dbh->rollback if $oldAutoCommit;
2060 "fatal: can't find tax rate for state/county/country/taxclass ".
2061 join('/', ( map $self->get("$prefix$_"),
2062 qw(state county country)
2064 $part_pkg->taxclass ). "\n";
2067 foreach my $tax ( @taxes ) {
2069 my $taxable_charged = 0;
2070 $taxable_charged += $setup
2071 unless $part_pkg->setuptax =~ /^Y$/i
2072 || $tax->setuptax =~ /^Y$/i;
2073 $taxable_charged += $recur
2074 unless $part_pkg->recurtax =~ /^Y$/i
2075 || $tax->recurtax =~ /^Y$/i;
2076 next unless $taxable_charged;
2078 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2079 #my ($mon,$year) = (localtime($sdate) )[4,5];
2080 my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2082 my $freq = $part_pkg->freq || 1;
2083 if ( $freq !~ /(\d+)$/ ) {
2084 $dbh->rollback if $oldAutoCommit;
2085 return "daily/weekly package definitions not (yet?)".
2086 " compatible with monthly tax exemptions";
2088 my $taxable_per_month =
2089 sprintf("%.2f", $taxable_charged / $freq );
2091 #call the whole thing off if this customer has any old
2092 #exemption records...
2093 my @cust_tax_exempt =
2094 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2095 if ( @cust_tax_exempt ) {
2096 $dbh->rollback if $oldAutoCommit;
2098 'this customer still has old-style tax exemption records; '.
2099 'run bin/fs-migrate-cust_tax_exempt?';
2102 foreach my $which_month ( 1 .. $freq ) {
2104 #maintain the new exemption table now
2107 FROM cust_tax_exempt_pkg
2108 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2109 LEFT JOIN cust_bill USING ( invnum )
2115 my $sth = dbh->prepare($sql) or do {
2116 $dbh->rollback if $oldAutoCommit;
2117 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2125 $dbh->rollback if $oldAutoCommit;
2126 return "fatal: can't lookup exising exemption: ". dbh->errstr;
2128 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2130 my $remaining_exemption =
2131 $tax->exempt_amount - $existing_exemption;
2132 if ( $remaining_exemption > 0 ) {
2133 my $addl = $remaining_exemption > $taxable_per_month
2134 ? $taxable_per_month
2135 : $remaining_exemption;
2136 $taxable_charged -= $addl;
2138 my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2139 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2140 'taxnum' => $tax->taxnum,
2141 'year' => 1900+$year,
2143 'amount' => sprintf("%.2f", $addl ),
2145 $error = $cust_tax_exempt_pkg->insert;
2147 $dbh->rollback if $oldAutoCommit;
2148 return "fatal: can't insert cust_tax_exempt_pkg: $error";
2150 } # if $remaining_exemption > 0
2154 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2155 until ( $mon < 13 ) { $mon -= 12; $year++; }
2157 } #foreach $which_month
2159 } #if $tax->exempt_amount
2161 $taxable_charged = sprintf( "%.2f", $taxable_charged);
2163 #$tax += $taxable_charged * $cust_main_county->tax / 100
2164 $tax{ $tax->taxname || 'Tax' } +=
2165 $taxable_charged * $tax->tax / 100
2167 } #foreach my $tax ( @taxes )
2169 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2171 } #if $setup != 0 || $recur != 0
2173 } #if $cust_pkg->modified
2175 } #foreach my $cust_pkg
2177 unless ( $cust_bill->cust_bill_pkg ) {
2178 $cust_bill->delete; #don't create an invoice w/o line items
2179 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2183 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2185 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2186 my $tax = sprintf("%.2f", $tax{$taxname} );
2187 $charged = sprintf( "%.2f", $charged+$tax );
2189 my $cust_bill_pkg = new FS::cust_bill_pkg ({
2190 'invnum' => $invnum,
2196 'itemdesc' => $taxname,
2198 $error = $cust_bill_pkg->insert;
2200 $dbh->rollback if $oldAutoCommit;
2201 return "can't create invoice line item for invoice #$invnum: $error";
2203 $total_setup += $tax;
2207 $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2208 $error = $cust_bill->replace;
2210 $dbh->rollback if $oldAutoCommit;
2211 return "can't update charged for invoice #$invnum: $error";
2214 foreach my $hook ( @precommit_hooks ) {
2216 &{$hook}; #($self) ?
2219 $dbh->rollback if $oldAutoCommit;
2220 return "$@ running precommit hook $hook\n";
2224 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2228 =item collect OPTIONS
2230 (Attempt to) collect money for this customer's outstanding invoices (see
2231 L<FS::cust_bill>). Usually used after the bill method.
2233 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2234 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2235 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2237 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2238 and the invoice events web interface.
2240 If there is an error, returns the error, otherwise returns false.
2242 Options are passed as name-value pairs.
2244 Currently available options are:
2246 invoice_time - Use this time when deciding when to print invoices and
2247 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>
2248 for conversion functions.
2250 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2253 quiet - set true to surpress email card/ACH decline notices.
2255 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2258 payby - allows for one time override of normal customer billing method
2263 my( $self, %options ) = @_;
2264 my $invoice_time = $options{'invoice_time'} || time;
2267 local $SIG{HUP} = 'IGNORE';
2268 local $SIG{INT} = 'IGNORE';
2269 local $SIG{QUIT} = 'IGNORE';
2270 local $SIG{TERM} = 'IGNORE';
2271 local $SIG{TSTP} = 'IGNORE';
2272 local $SIG{PIPE} = 'IGNORE';
2274 my $oldAutoCommit = $FS::UID::AutoCommit;
2275 local $FS::UID::AutoCommit = 0;
2278 $self->select_for_update; #mutex
2280 my $balance = $self->balance;
2281 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2283 unless ( $balance > 0 ) { #redundant?????
2284 $dbh->rollback if $oldAutoCommit; #hmm
2288 if ( exists($options{'retry_card'}) ) {
2289 carp 'retry_card option passed to collect is deprecated; use retry';
2290 $options{'retry'} ||= $options{'retry_card'};
2292 if ( exists($options{'retry'}) && $options{'retry'} ) {
2293 my $error = $self->retry_realtime;
2295 $dbh->rollback if $oldAutoCommit;
2301 if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2302 $extra_sql = " AND freq = '1m' ";
2304 $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2307 foreach my $cust_bill ( $self->open_cust_bill ) {
2309 # don't try to charge for the same invoice if it's already in a batch
2310 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2312 last if $self->balance <= 0;
2314 warn " invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2317 foreach my $part_bill_event ( due_events ( $cust_bill,
2318 exists($options{'payby'})
2324 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
2325 || $self->balance <= 0; # or if balance<=0
2328 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2329 warn " do_event " . $cust_bill . " ". (%options) . "\n"
2332 if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2333 # gah, even with transactions.
2334 $dbh->commit if $oldAutoCommit; #well.
2343 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2348 =item retry_realtime
2350 Schedules realtime / batch credit card / electronic check / LEC billing
2351 events for for retry. Useful if card information has changed or manual
2352 retry is desired. The 'collect' method must be called to actually retry
2355 Implementation details: For each of this customer's open invoices, changes
2356 the status of the first "done" (with statustext error) realtime processing
2361 sub retry_realtime {
2364 local $SIG{HUP} = 'IGNORE';
2365 local $SIG{INT} = 'IGNORE';
2366 local $SIG{QUIT} = 'IGNORE';
2367 local $SIG{TERM} = 'IGNORE';
2368 local $SIG{TSTP} = 'IGNORE';
2369 local $SIG{PIPE} = 'IGNORE';
2371 my $oldAutoCommit = $FS::UID::AutoCommit;
2372 local $FS::UID::AutoCommit = 0;
2375 foreach my $cust_bill (
2376 grep { $_->cust_bill_event }
2377 $self->open_cust_bill
2379 my @cust_bill_event =
2380 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2382 #$_->part_bill_event->plan eq 'realtime-card'
2383 $_->part_bill_event->eventcode =~
2384 /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2385 && $_->status eq 'done'
2388 $cust_bill->cust_bill_event;
2389 next unless @cust_bill_event;
2390 my $error = $cust_bill_event[0]->retry;
2392 $dbh->rollback if $oldAutoCommit;
2393 return "error scheduling invoice event for retry: $error";
2398 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2403 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2405 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2406 via a Business::OnlinePayment realtime gateway. See
2407 L<http://420.am/business-onlinepayment> for supported gateways.
2409 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2411 Available options are: I<description>, I<invnum>, I<quiet>
2413 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2414 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2415 if set, will override the value from the customer record.
2417 I<description> is a free-text field passed to the gateway. It defaults to
2418 "Internet services".
2420 If an I<invnum> is specified, this payment (if successful) is applied to the
2421 specified invoice. If you don't specify an I<invnum> you might want to
2422 call the B<apply_payments> method.
2424 I<quiet> can be set true to surpress email decline notices.
2426 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2431 my( $self, $method, $amount, %options ) = @_;
2433 warn "$me realtime_bop: $method $amount\n";
2434 warn " $_ => $options{$_}\n" foreach keys %options;
2437 $options{'description'} ||= 'Internet services';
2439 eval "use Business::OnlinePayment";
2442 my $payinfo = exists($options{'payinfo'})
2443 ? $options{'payinfo'}
2451 if ( $options{'invnum'} ) {
2452 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2453 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2455 map { $_->part_pkg->taxclass }
2457 map { $_->cust_pkg }
2458 $cust_bill->cust_bill_pkg;
2459 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2460 #different taxclasses
2461 $taxclass = $taxclasses[0];
2465 #look for an agent gateway override first
2467 if ( $method eq 'CC' ) {
2468 $cardtype = cardtype($payinfo);
2469 } elsif ( $method eq 'ECHECK' ) {
2472 $cardtype = $method;
2476 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2477 cardtype => $cardtype,
2478 taxclass => $taxclass, } )
2479 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2481 taxclass => $taxclass, } )
2482 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2483 cardtype => $cardtype,
2485 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2487 taxclass => '', } );
2489 my $payment_gateway = '';
2490 my( $processor, $login, $password, $action, @bop_options );
2491 if ( $override ) { #use a payment gateway override
2493 $payment_gateway = $override->payment_gateway;
2495 $processor = $payment_gateway->gateway_module;
2496 $login = $payment_gateway->gateway_username;
2497 $password = $payment_gateway->gateway_password;
2498 $action = $payment_gateway->gateway_action;
2499 @bop_options = $payment_gateway->options;
2501 } else { #use the standard settings from the config
2503 ( $processor, $login, $password, $action, @bop_options ) =
2504 $self->default_payment_gateway($method);
2512 my $address = exists($options{'address1'})
2513 ? $options{'address1'}
2515 my $address2 = exists($options{'address2'})
2516 ? $options{'address2'}
2518 $address .= ", ". $address2 if length($address2);
2520 my $o_payname = exists($options{'payname'})
2521 ? $options{'payname'}
2523 my($payname, $payfirst, $paylast);
2524 if ( $o_payname && $method ne 'ECHECK' ) {
2525 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2526 or return "Illegal payname $payname";
2527 ($payfirst, $paylast) = ($1, $2);
2529 $payfirst = $self->getfield('first');
2530 $paylast = $self->getfield('last');
2531 $payname = "$payfirst $paylast";
2534 # invoicing_list_emailonly instead? push one? which one?
2535 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
2536 if ( $conf->exists('emailinvoiceautoalways')
2537 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
2538 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2539 push @invoicing_list, $self->all_emails;
2542 my $email = ($conf->exists('business-onlinepayment-email-override'))
2543 ? $conf->config('business-onlinepayment-email-override')
2544 : $invoicing_list[0];
2548 my $payip = exists($options{'payip'})
2551 $content{customer_ip} = $payip
2554 $content{invoice_number} = $options{'invnum'}
2555 if exists($options{'invnum'}) && length($options{'invnum'});
2557 if ( $method eq 'CC' ) {
2559 $content{card_number} = $payinfo;
2560 my $paydate = exists($options{'paydate'})
2561 ? $options{'paydate'}
2563 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2564 $content{expiration} = "$2/$1";
2566 my $paycvv = exists($options{'paycvv'})
2567 ? $options{'paycvv'}
2569 $content{cvv2} = $self->paycvv
2572 my $paystart_month = exists($options{'paystart_month'})
2573 ? $options{'paystart_month'}
2574 : $self->paystart_month;
2576 my $paystart_year = exists($options{'paystart_year'})
2577 ? $options{'paystart_year'}
2578 : $self->paystart_year;
2580 $content{card_start} = "$paystart_month/$paystart_year"
2581 if $paystart_month && $paystart_year;
2583 my $payissue = exists($options{'payissue'})
2584 ? $options{'payissue'}
2586 $content{issue_number} = $payissue if $payissue;
2588 $content{recurring_billing} = 'YES'
2589 if qsearch('cust_pay', { 'custnum' => $self->custnum,
2591 'payinfo' => $payinfo,
2593 || qsearch('cust_pay', { 'custnum' => $self->custnum,
2595 'paymask' => $self->mask_payinfo('CARD', $payinfo),
2599 } elsif ( $method eq 'ECHECK' ) {
2600 ( $content{account_number}, $content{routing_code} ) =
2601 split('@', $payinfo);
2602 $content{bank_name} = $o_payname;
2603 $content{account_type} = 'CHECKING';
2604 $content{account_name} = $payname;
2605 $content{customer_org} = $self->company ? 'B' : 'I';
2606 $content{customer_ssn} = exists($options{'ss'})
2609 } elsif ( $method eq 'LEC' ) {
2610 $content{phone} = $payinfo;
2614 # run transaction(s)
2617 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2619 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2620 $transaction->content(
2623 'password' => $password,
2624 'action' => $action1,
2625 'description' => $options{'description'},
2626 'amount' => $amount,
2627 #'invoice_number' => $options{'invnum'},
2628 'customer_id' => $self->custnum,
2629 'last_name' => $paylast,
2630 'first_name' => $payfirst,
2632 'address' => $address,
2633 'city' => ( exists($options{'city'})
2636 'state' => ( exists($options{'state'})
2639 'zip' => ( exists($options{'zip'})
2642 'country' => ( exists($options{'country'})
2643 ? $options{'country'}
2645 'referer' => 'http://cleanwhisker.420.am/',
2647 'phone' => $self->daytime || $self->night,
2650 $transaction->submit();
2652 if ( $transaction->is_success() && $action2 ) {
2653 my $auth = $transaction->authorization;
2654 my $ordernum = $transaction->can('order_number')
2655 ? $transaction->order_number
2659 new Business::OnlinePayment( $processor, @bop_options );
2666 password => $password,
2667 order_number => $ordernum,
2669 authorization => $auth,
2670 description => $options{'description'},
2673 foreach my $field (qw( authorization_source_code returned_ACI
2674 transaction_identifier validation_code
2675 transaction_sequence_num local_transaction_date
2676 local_transaction_time AVS_result_code )) {
2677 $capture{$field} = $transaction->$field() if $transaction->can($field);
2680 $capture->content( %capture );
2684 unless ( $capture->is_success ) {
2685 my $e = "Authorization successful but capture failed, custnum #".
2686 $self->custnum. ': '. $capture->result_code.
2687 ": ". $capture->error_message;
2695 # remove paycvv after initial transaction
2698 #false laziness w/misc/process/payment.cgi - check both to make sure working
2700 if ( defined $self->dbdef_table->column('paycvv')
2701 && length($self->paycvv)
2702 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2704 my $error = $self->remove_cvv;
2706 warn "WARNING: error removing cvv: $error\n";
2714 if ( $transaction->is_success() ) {
2716 my %method2payby = (
2723 if ( $payment_gateway ) { # agent override
2724 $paybatch = $payment_gateway->gatewaynum. '-';
2727 $paybatch .= "$processor:". $transaction->authorization;
2729 $paybatch .= ':'. $transaction->order_number
2730 if $transaction->can('order_number')
2731 && length($transaction->order_number);
2733 my $cust_pay = new FS::cust_pay ( {
2734 'custnum' => $self->custnum,
2735 'invnum' => $options{'invnum'},
2738 'payby' => $method2payby{$method},
2739 'payinfo' => $payinfo,
2740 'paybatch' => $paybatch,
2742 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
2744 $cust_pay->invnum(''); #try again with no specific invnum
2745 my $error2 = $cust_pay->insert( $options{'manual'} ?
2746 ( 'manual' => 1 ) : ()
2749 # gah, even with transactions.
2750 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2751 "error inserting payment ($processor): $error2".
2752 " (previously tried insert with invnum #$options{'invnum'}" .
2758 return ''; #no error
2762 my $perror = "$processor error: ". $transaction->error_message;
2764 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2765 && $conf->exists('emaildecline')
2766 && grep { $_ ne 'POST' } $self->invoicing_list
2767 && ! grep { $transaction->error_message =~ /$_/ }
2768 $conf->config('emaildecline-exclude')
2770 my @templ = $conf->config('declinetemplate');
2771 my $template = new Text::Template (
2773 SOURCE => [ map "$_\n", @templ ],
2774 ) or return "($perror) can't create template: $Text::Template::ERROR";
2775 $template->compile()
2776 or return "($perror) can't compile template: $Text::Template::ERROR";
2778 my $templ_hash = { error => $transaction->error_message };
2780 my $error = send_email(
2781 'from' => $conf->config('invoice_from'),
2782 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2783 'subject' => 'Your payment could not be processed',
2784 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2787 $perror .= " (also received error sending decline notification: $error)"
2797 =item default_payment_gateway
2801 sub default_payment_gateway {
2802 my( $self, $method ) = @_;
2804 die "Real-time processing not enabled\n"
2805 unless $conf->exists('business-onlinepayment');
2808 my $bop_config = 'business-onlinepayment';
2809 $bop_config .= '-ach'
2810 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2811 my ( $processor, $login, $password, $action, @bop_options ) =
2812 $conf->config($bop_config);
2813 $action ||= 'normal authorization';
2814 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2815 die "No real-time processor is enabled - ".
2816 "did you set the business-onlinepayment configuration value?\n"
2819 ( $processor, $login, $password, $action, @bop_options )
2824 Removes the I<paycvv> field from the database directly.
2826 If there is an error, returns the error, otherwise returns false.
2832 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2833 or return dbh->errstr;
2834 $sth->execute($self->custnum)
2835 or return $sth->errstr;
2840 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2842 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2843 via a Business::OnlinePayment realtime gateway. See
2844 L<http://420.am/business-onlinepayment> for supported gateways.
2846 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2848 Available options are: I<amount>, I<reason>, I<paynum>
2850 Most gateways require a reference to an original payment transaction to refund,
2851 so you probably need to specify a I<paynum>.
2853 I<amount> defaults to the original amount of the payment if not specified.
2855 I<reason> specifies a reason for the refund.
2857 Implementation note: If I<amount> is unspecified or equal to the amount of the
2858 orignal payment, first an attempt is made to "void" the transaction via
2859 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2860 the normal attempt is made to "refund" ("credit") the transaction via the
2861 gateway is attempted.
2863 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2864 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2865 #if set, will override the value from the customer record.
2867 #If an I<invnum> is specified, this payment (if successful) is applied to the
2868 #specified invoice. If you don't specify an I<invnum> you might want to
2869 #call the B<apply_payments> method.
2873 #some false laziness w/realtime_bop, not enough to make it worth merging
2874 #but some useful small subs should be pulled out
2875 sub realtime_refund_bop {
2876 my( $self, $method, %options ) = @_;
2878 warn "$me realtime_refund_bop: $method refund\n";
2879 warn " $_ => $options{$_}\n" foreach keys %options;
2882 eval "use Business::OnlinePayment";
2886 # look up the original payment and optionally a gateway for that payment
2890 my $amount = $options{'amount'};
2892 my( $processor, $login, $password, @bop_options ) ;
2893 my( $auth, $order_number ) = ( '', '', '' );
2895 if ( $options{'paynum'} ) {
2897 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
2898 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2899 or return "Unknown paynum $options{'paynum'}";
2900 $amount ||= $cust_pay->paid;
2902 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-]*)(:([\w\-]+))?$/
2903 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2904 $cust_pay->paybatch;
2905 my $gatewaynum = '';
2906 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
2908 if ( $gatewaynum ) { #gateway for the payment to be refunded
2910 my $payment_gateway =
2911 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
2912 die "payment gateway $gatewaynum not found"
2913 unless $payment_gateway;
2915 $processor = $payment_gateway->gateway_module;
2916 $login = $payment_gateway->gateway_username;
2917 $password = $payment_gateway->gateway_password;
2918 @bop_options = $payment_gateway->options;
2920 } else { #try the default gateway
2922 my( $conf_processor, $unused_action );
2923 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
2924 $self->default_payment_gateway($method);
2926 return "processor of payment $options{'paynum'} $processor does not".
2927 " match default processor $conf_processor"
2928 unless $processor eq $conf_processor;
2933 } else { # didn't specify a paynum, so look for agent gateway overrides
2934 # like a normal transaction
2937 if ( $method eq 'CC' ) {
2938 $cardtype = cardtype($self->payinfo);
2939 } elsif ( $method eq 'ECHECK' ) {
2942 $cardtype = $method;
2945 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2946 cardtype => $cardtype,
2948 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2950 taxclass => '', } );
2952 if ( $override ) { #use a payment gateway override
2954 my $payment_gateway = $override->payment_gateway;
2956 $processor = $payment_gateway->gateway_module;
2957 $login = $payment_gateway->gateway_username;
2958 $password = $payment_gateway->gateway_password;
2959 #$action = $payment_gateway->gateway_action;
2960 @bop_options = $payment_gateway->options;
2962 } else { #use the standard settings from the config
2965 ( $processor, $login, $password, $unused_action, @bop_options ) =
2966 $self->default_payment_gateway($method);
2971 return "neither amount nor paynum specified" unless $amount;
2976 'password' => $password,
2977 'order_number' => $order_number,
2978 'amount' => $amount,
2979 'referer' => 'http://cleanwhisker.420.am/',
2981 $content{authorization} = $auth
2982 if length($auth); #echeck/ACH transactions have an order # but no auth
2983 #(at least with authorize.net)
2985 #first try void if applicable
2986 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2987 warn " attempting void\n" if $DEBUG > 1;
2988 my $void = new Business::OnlinePayment( $processor, @bop_options );
2989 $void->content( 'action' => 'void', %content );
2991 if ( $void->is_success ) {
2992 my $error = $cust_pay->void($options{'reason'});
2994 # gah, even with transactions.
2995 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2996 "error voiding payment: $error";
3000 warn " void successful\n" if $DEBUG > 1;
3005 warn " void unsuccessful, trying refund\n"
3009 my $address = $self->address1;
3010 $address .= ", ". $self->address2 if $self->address2;
3012 my($payname, $payfirst, $paylast);
3013 if ( $self->payname && $method ne 'ECHECK' ) {
3014 $payname = $self->payname;
3015 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3016 or return "Illegal payname $payname";
3017 ($payfirst, $paylast) = ($1, $2);
3019 $payfirst = $self->getfield('first');
3020 $paylast = $self->getfield('last');
3021 $payname = "$payfirst $paylast";
3024 # invoicing_list_emailonly instead? push one? which one?
3025 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
3026 if ( $conf->exists('emailinvoiceautoalways')
3027 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3028 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3029 push @invoicing_list, $self->all_emails;
3032 my $email = ($conf->exists('business-onlinepayment-email-override'))
3033 ? $conf->config('business-onlinepayment-email-override')
3034 : $invoicing_list[0];
3036 my $payip = exists($options{'payip'})
3039 $content{customer_ip} = $payip
3043 if ( $method eq 'CC' ) {
3046 $content{card_number} = $payinfo = $cust_pay->payinfo;
3047 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3048 #$content{expiration} = "$2/$1";
3050 $content{card_number} = $payinfo = $self->payinfo;
3051 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3052 $content{expiration} = "$2/$1";
3055 } elsif ( $method eq 'ECHECK' ) {
3056 ( $content{account_number}, $content{routing_code} ) =
3057 split('@', $payinfo = $self->payinfo);
3058 $content{bank_name} = $self->payname;
3059 $content{account_type} = 'CHECKING';
3060 $content{account_name} = $payname;
3061 $content{customer_org} = $self->company ? 'B' : 'I';
3062 $content{customer_ssn} = $self->ss;
3063 } elsif ( $method eq 'LEC' ) {
3064 $content{phone} = $payinfo = $self->payinfo;
3068 my $refund = new Business::OnlinePayment( $processor, @bop_options );
3069 my %sub_content = $refund->content(
3070 'action' => 'credit',
3071 'customer_id' => $self->custnum,
3072 'last_name' => $paylast,
3073 'first_name' => $payfirst,
3075 'address' => $address,
3076 'city' => $self->city,
3077 'state' => $self->state,
3078 'zip' => $self->zip,
3079 'country' => $self->country,
3081 'phone' => $self->daytime || $self->night,
3084 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
3088 return "$processor error: ". $refund->error_message
3089 unless $refund->is_success();
3091 my %method2payby = (
3097 my $paybatch = "$processor:". $refund->authorization;
3098 $paybatch .= ':'. $refund->order_number
3099 if $refund->can('order_number') && $refund->order_number;
3101 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3102 my @cust_bill_pay = $cust_pay->cust_bill_pay;
3103 last unless @cust_bill_pay;
3104 my $cust_bill_pay = pop @cust_bill_pay;
3105 my $error = $cust_bill_pay->delete;
3109 my $cust_refund = new FS::cust_refund ( {
3110 'custnum' => $self->custnum,
3111 'paynum' => $options{'paynum'},
3112 'refund' => $amount,
3114 'payby' => $method2payby{$method},
3115 'payinfo' => $payinfo,
3116 'paybatch' => $paybatch,
3117 'reason' => $options{'reason'} || 'card or ACH refund',
3119 my $error = $cust_refund->insert;
3121 $cust_refund->paynum(''); #try again with no specific paynum
3122 my $error2 = $cust_refund->insert;
3124 # gah, even with transactions.
3125 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3126 "error inserting refund ($processor): $error2".
3127 " (previously tried insert with paynum #$options{'paynum'}" .
3140 Returns the total owed for this customer on all invoices
3141 (see L<FS::cust_bill/owed>).
3147 $self->total_owed_date(2145859200); #12/31/2037
3150 =item total_owed_date TIME
3152 Returns the total owed for this customer on all invoices with date earlier than
3153 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3154 see L<Time::Local> and L<Date::Parse> for conversion functions.
3158 sub total_owed_date {
3162 foreach my $cust_bill (
3163 grep { $_->_date <= $time }
3164 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3166 $total_bill += $cust_bill->owed;
3168 sprintf( "%.2f", $total_bill );
3171 =item apply_payments_and_credits
3173 Applies unapplied payments and credits.
3175 In most cases, this new method should be used in place of sequential
3176 apply_payments and apply_credits methods.
3180 sub apply_payments_and_credits {
3183 foreach my $cust_bill ( $self->open_cust_bill ) {
3184 $cust_bill->apply_payments_and_credits;
3189 =item apply_credits OPTION => VALUE ...
3191 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3192 to outstanding invoice balances in chronological order (or reverse
3193 chronological order if the I<order> option is set to B<newest>) and returns the
3194 value of any remaining unapplied credits available for refund (see
3195 L<FS::cust_refund>).
3203 return 0 unless $self->total_credited;
3205 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3206 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3208 my @invoices = $self->open_cust_bill;
3209 @invoices = sort { $b->_date <=> $a->_date } @invoices
3210 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3213 foreach my $cust_bill ( @invoices ) {
3216 if ( !defined($credit) || $credit->credited == 0) {
3217 $credit = pop @credits or last;
3220 if ($cust_bill->owed >= $credit->credited) {
3221 $amount=$credit->credited;
3223 $amount=$cust_bill->owed;
3226 my $cust_credit_bill = new FS::cust_credit_bill ( {
3227 'crednum' => $credit->crednum,
3228 'invnum' => $cust_bill->invnum,
3229 'amount' => $amount,
3231 my $error = $cust_credit_bill->insert;
3232 die $error if $error;
3234 redo if ($cust_bill->owed > 0);
3238 return $self->total_credited;
3241 =item apply_payments
3243 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3244 to outstanding invoice balances in chronological order.
3246 #and returns the value of any remaining unapplied payments.
3250 sub apply_payments {
3255 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3256 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3258 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3259 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3263 foreach my $cust_bill ( @invoices ) {
3266 if ( !defined($payment) || $payment->unapplied == 0 ) {
3267 $payment = pop @payments or last;
3270 if ( $cust_bill->owed >= $payment->unapplied ) {
3271 $amount = $payment->unapplied;
3273 $amount = $cust_bill->owed;
3276 my $cust_bill_pay = new FS::cust_bill_pay ( {
3277 'paynum' => $payment->paynum,
3278 'invnum' => $cust_bill->invnum,
3279 'amount' => $amount,
3281 my $error = $cust_bill_pay->insert;
3282 die $error if $error;
3284 redo if ( $cust_bill->owed > 0);
3288 return $self->total_unapplied_payments;
3291 =item total_credited
3293 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3294 customer. See L<FS::cust_credit/credited>.
3298 sub total_credited {
3300 my $total_credit = 0;
3301 foreach my $cust_credit ( qsearch('cust_credit', {
3302 'custnum' => $self->custnum,
3304 $total_credit += $cust_credit->credited;
3306 sprintf( "%.2f", $total_credit );
3309 =item total_unapplied_payments
3311 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3312 See L<FS::cust_pay/unapplied>.
3316 sub total_unapplied_payments {
3318 my $total_unapplied = 0;
3319 foreach my $cust_pay ( qsearch('cust_pay', {
3320 'custnum' => $self->custnum,
3322 $total_unapplied += $cust_pay->unapplied;
3324 sprintf( "%.2f", $total_unapplied );
3329 Returns the balance for this customer (total_owed minus total_credited
3330 minus total_unapplied_payments).
3337 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
3341 =item balance_date TIME
3343 Returns the balance for this customer, only considering invoices with date
3344 earlier than TIME (total_owed_date minus total_credited minus
3345 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3346 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3355 $self->total_owed_date($time)
3356 - $self->total_credited
3357 - $self->total_unapplied_payments
3361 =item in_transit_payments
3363 Returns the total of requests for payments for this customer pending in
3364 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3368 sub in_transit_payments {
3370 my $in_transit_payments = 0;
3371 foreach my $pay_batch ( qsearch('pay_batch', {
3374 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3375 'batchnum' => $pay_batch->batchnum,
3376 'custnum' => $self->custnum,
3378 $in_transit_payments += $cust_pay_batch->amount;
3381 sprintf( "%.2f", $in_transit_payments );
3384 =item paydate_monthyear
3386 Returns a two-element list consisting of the month and year of this customer's
3387 paydate (credit card expiration date for CARD customers)
3391 sub paydate_monthyear {
3393 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3395 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3402 =item invoicing_list [ ARRAYREF ]
3404 If an arguement is given, sets these email addresses as invoice recipients
3405 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3406 (except as warnings), so use check_invoicing_list first.
3408 Returns a list of email addresses (with svcnum entries expanded).
3410 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3411 check it without disturbing anything by passing nothing.
3413 This interface may change in the future.
3417 sub invoicing_list {
3418 my( $self, $arrayref ) = @_;
3421 my @cust_main_invoice;
3422 if ( $self->custnum ) {
3423 @cust_main_invoice =
3424 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3426 @cust_main_invoice = ();
3428 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3429 #warn $cust_main_invoice->destnum;
3430 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3431 #warn $cust_main_invoice->destnum;
3432 my $error = $cust_main_invoice->delete;
3433 warn $error if $error;
3436 if ( $self->custnum ) {
3437 @cust_main_invoice =
3438 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3440 @cust_main_invoice = ();
3442 my %seen = map { $_->address => 1 } @cust_main_invoice;
3443 foreach my $address ( @{$arrayref} ) {
3444 next if exists $seen{$address} && $seen{$address};
3445 $seen{$address} = 1;
3446 my $cust_main_invoice = new FS::cust_main_invoice ( {
3447 'custnum' => $self->custnum,
3450 my $error = $cust_main_invoice->insert;
3451 warn $error if $error;
3455 if ( $self->custnum ) {
3457 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3464 =item check_invoicing_list ARRAYREF
3466 Checks these arguements as valid input for the invoicing_list method. If there
3467 is an error, returns the error, otherwise returns false.
3471 sub check_invoicing_list {
3472 my( $self, $arrayref ) = @_;
3473 foreach my $address ( @{$arrayref} ) {
3475 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3476 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3479 my $cust_main_invoice = new FS::cust_main_invoice ( {
3480 'custnum' => $self->custnum,
3483 my $error = $self->custnum
3484 ? $cust_main_invoice->check
3485 : $cust_main_invoice->checkdest
3487 return $error if $error;
3492 =item set_default_invoicing_list
3494 Sets the invoicing list to all accounts associated with this customer,
3495 overwriting any previous invoicing list.
3499 sub set_default_invoicing_list {
3501 $self->invoicing_list($self->all_emails);
3506 Returns the email addresses of all accounts provisioned for this customer.
3513 foreach my $cust_pkg ( $self->all_pkgs ) {
3514 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3516 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3517 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3519 $list{$_}=1 foreach map { $_->email } @svc_acct;
3524 =item invoicing_list_addpost
3526 Adds postal invoicing to this customer. If this customer is already configured
3527 to receive postal invoices, does nothing.
3531 sub invoicing_list_addpost {
3533 return if grep { $_ eq 'POST' } $self->invoicing_list;
3534 my @invoicing_list = $self->invoicing_list;
3535 push @invoicing_list, 'POST';
3536 $self->invoicing_list(\@invoicing_list);
3539 =item invoicing_list_emailonly
3541 Returns the list of email invoice recipients (invoicing_list without non-email
3542 destinations such as POST and FAX).
3546 sub invoicing_list_emailonly {
3548 warn "$me invoicing_list_emailonly called"
3550 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3553 =item invoicing_list_emailonly_scalar
3555 Returns the list of email invoice recipients (invoicing_list without non-email
3556 destinations such as POST and FAX) as a comma-separated scalar.
3560 sub invoicing_list_emailonly_scalar {
3562 warn "$me invoicing_list_emailonly_scalar called"
3564 join(', ', $self->invoicing_list_emailonly);
3567 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3569 Returns an array of customers referred by this customer (referral_custnum set
3570 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3571 customers referred by customers referred by this customer and so on, inclusive.
3572 The default behavior is DEPTH 1 (no recursion).
3576 sub referral_cust_main {
3578 my $depth = @_ ? shift : 1;
3579 my $exclude = @_ ? shift : {};
3582 map { $exclude->{$_->custnum}++; $_; }
3583 grep { ! $exclude->{ $_->custnum } }
3584 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3588 map { $_->referral_cust_main($depth-1, $exclude) }
3595 =item referral_cust_main_ncancelled
3597 Same as referral_cust_main, except only returns customers with uncancelled
3602 sub referral_cust_main_ncancelled {
3604 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3607 =item referral_cust_pkg [ DEPTH ]
3609 Like referral_cust_main, except returns a flat list of all unsuspended (and
3610 uncancelled) packages for each customer. The number of items in this list may
3611 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3615 sub referral_cust_pkg {
3617 my $depth = @_ ? shift : 1;
3619 map { $_->unsuspended_pkgs }
3620 grep { $_->unsuspended_pkgs }
3621 $self->referral_cust_main($depth);
3624 =item referring_cust_main
3626 Returns the single cust_main record for the customer who referred this customer
3627 (referral_custnum), or false.
3631 sub referring_cust_main {
3633 return '' unless $self->referral_custnum;
3634 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3637 =item credit AMOUNT, REASON
3639 Applies a credit to this customer. If there is an error, returns the error,
3640 otherwise returns false.
3645 my( $self, $amount, $reason ) = @_;
3646 my $cust_credit = new FS::cust_credit {
3647 'custnum' => $self->custnum,
3648 'amount' => $amount,
3649 'reason' => $reason,
3651 $cust_credit->insert;
3654 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3656 Creates a one-time charge for this customer. If there is an error, returns
3657 the error, otherwise returns false.
3663 my ( $amount, $pkg, $comment, $taxclass, $additional );
3664 if ( ref( $_[0] ) ) {
3665 $amount = $_[0]->{amount};
3666 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3667 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3668 : '$'. sprintf("%.2f",$amount);
3669 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3670 $additional = $_[0]->{additional};
3673 $pkg = @_ ? shift : 'One-time charge';
3674 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3675 $taxclass = @_ ? shift : '';
3679 local $SIG{HUP} = 'IGNORE';
3680 local $SIG{INT} = 'IGNORE';
3681 local $SIG{QUIT} = 'IGNORE';
3682 local $SIG{TERM} = 'IGNORE';
3683 local $SIG{TSTP} = 'IGNORE';
3684 local $SIG{PIPE} = 'IGNORE';
3686 my $oldAutoCommit = $FS::UID::AutoCommit;
3687 local $FS::UID::AutoCommit = 0;
3690 my $part_pkg = new FS::part_pkg ( {
3692 'comment' => $comment,
3696 'taxclass' => $taxclass,
3699 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3700 ( 0 .. @$additional - 1 )
3702 'additional_count' => scalar(@$additional),
3703 'setup_fee' => $amount,
3706 my $error = $part_pkg->insert( options => \%options );
3708 $dbh->rollback if $oldAutoCommit;
3712 my $pkgpart = $part_pkg->pkgpart;
3713 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3714 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3715 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3716 $error = $type_pkgs->insert;
3718 $dbh->rollback if $oldAutoCommit;
3723 my $cust_pkg = new FS::cust_pkg ( {
3724 'custnum' => $self->custnum,
3725 'pkgpart' => $pkgpart,
3728 $error = $cust_pkg->insert;
3730 $dbh->rollback if $oldAutoCommit;
3734 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3741 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3747 sort { $a->_date <=> $b->_date }
3748 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3751 =item open_cust_bill
3753 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3758 sub open_cust_bill {
3760 grep { $_->owed > 0 } $self->cust_bill;
3765 Returns all the credits (see L<FS::cust_credit>) for this customer.
3771 sort { $a->_date <=> $b->_date }
3772 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3777 Returns all the payments (see L<FS::cust_pay>) for this customer.
3783 sort { $a->_date <=> $b->_date }
3784 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3789 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3795 sort { $a->_date <=> $b->_date }
3796 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3802 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3808 sort { $a->_date <=> $b->_date }
3809 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3812 =item select_for_update
3814 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
3819 sub select_for_update {
3821 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
3826 Returns a name string for this customer, either "Company (Last, First)" or
3833 my $name = $self->contact;
3834 $name = $self->company. " ($name)" if $self->company;
3840 Returns a name string for this (service/shipping) contact, either
3841 "Company (Last, First)" or "Last, First".
3847 if ( $self->get('ship_last') ) {
3848 my $name = $self->ship_contact;
3849 $name = $self->ship_company. " ($name)" if $self->ship_company;
3858 Returns this customer's full (billing) contact name only, "Last, First"
3864 $self->get('last'). ', '. $self->first;
3869 Returns this customer's full (shipping) contact name only, "Last, First"
3875 $self->get('ship_last')
3876 ? $self->get('ship_last'). ', '. $self->ship_first
3882 Returns this customer's full country name
3888 code2country($self->country);
3893 Returns a status string for this customer, currently:
3897 =item prospect - No packages have ever been ordered
3899 =item active - One or more recurring packages is active
3901 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3903 =item suspended - All non-cancelled recurring packages are suspended
3905 =item cancelled - All recurring packages are cancelled
3913 for my $status (qw( prospect active inactive suspended cancelled )) {
3914 my $method = $status.'_sql';
3915 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3916 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3917 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3918 return $status if $sth->fetchrow_arrayref->[0];
3924 Returns a hex triplet color string for this customer's status.
3928 use vars qw(%statuscolor);
3930 'prospect' => '7e0079', #'000000', #black? naw, purple
3931 'active' => '00CC00', #green
3932 'inactive' => '0000CC', #blue
3933 'suspended' => 'FF9900', #yellow
3934 'cancelled' => 'FF0000', #red
3939 $statuscolor{$self->status};
3944 =head1 CLASS METHODS
3950 Returns an SQL expression identifying prospective cust_main records (customers
3951 with no packages ever ordered)
3955 use vars qw($select_count_pkgs);
3956 $select_count_pkgs =
3957 "SELECT COUNT(*) FROM cust_pkg
3958 WHERE cust_pkg.custnum = cust_main.custnum";
3960 sub select_count_pkgs_sql {
3964 sub prospect_sql { "
3965 0 = ( $select_count_pkgs )
3970 Returns an SQL expression identifying active cust_main records (customers with
3971 no active recurring packages, but otherwise unsuspended/uncancelled).
3976 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
3982 Returns an SQL expression identifying inactive cust_main records (customers with
3983 active recurring packages).
3987 sub inactive_sql { "
3988 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
3990 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
3996 Returns an SQL expression identifying suspended cust_main records.
4001 sub suspended_sql { susp_sql(@_); }
4003 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
4005 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4011 Returns an SQL expression identifying cancelled cust_main records.
4015 sub cancelled_sql { cancel_sql(@_); }
4018 my $recurring_sql = FS::cust_pkg->recurring_sql;
4019 #my $recurring_sql = "
4020 # '0' != ( select freq from part_pkg
4021 # where cust_pkg.pkgpart = part_pkg.pkgpart )
4025 0 < ( $select_count_pkgs )
4026 AND 0 = ( $select_count_pkgs AND $recurring_sql
4027 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4033 =item uncancelled_sql
4035 Returns an SQL expression identifying un-cancelled cust_main records.
4039 sub uncancelled_sql { uncancel_sql(@_); }
4040 sub uncancel_sql { "
4041 ( 0 < ( $select_count_pkgs
4042 AND ( cust_pkg.cancel IS NULL
4043 OR cust_pkg.cancel = 0
4046 OR 0 = ( $select_count_pkgs )
4050 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
4052 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
4053 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
4054 appropriate ship_ field is also searched).
4056 Additional options are the same as FS::Record::qsearch
4061 my( $self, $fuzzy, $hash, @opt) = @_;
4066 check_and_rebuild_fuzzyfiles();
4067 foreach my $field ( keys %$fuzzy ) {
4069 my $all = $self->all_X($field);
4070 next unless scalar(@$all);
4073 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
4076 foreach ( keys %match ) {
4077 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
4078 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
4081 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
4084 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
4086 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
4098 =item smart_search OPTION => VALUE ...
4100 Accepts the following options: I<search>, the string to search for. The string
4101 will be searched for as a customer number, phone number, name or company name,
4102 as an exact, or, in some cases, a substring or fuzzy match (see the source code
4103 for the exact heuristics used).
4105 Any additional options are treated as an additional qualifier on the search
4108 Returns a (possibly empty) array of FS::cust_main objects.
4115 #here is the agent virtualization
4116 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
4120 my $search = delete $options{'search'};
4121 ( my $alphanum_search = $search ) =~ s/\W//g;
4123 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
4125 #false laziness w/Record::ut_phone
4126 my $phonen = "$1-$2-$3";
4127 $phonen .= " x$4" if $4;
4129 push @cust_main, qsearch( {
4130 'table' => 'cust_main',
4131 'hashref' => { %options },
4132 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4134 join(' OR ', map "$_ = '$phonen'",
4135 qw( daytime night fax
4136 ship_daytime ship_night ship_fax )
4139 " AND $agentnums_sql", #agent virtualization
4142 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
4143 #try looking for matches with extensions unless one was specified
4145 push @cust_main, qsearch( {
4146 'table' => 'cust_main',
4147 'hashref' => { %options },
4148 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
4150 join(' OR ', map "$_ LIKE '$phonen\%'",
4152 ship_daytime ship_night )
4155 " AND $agentnums_sql", #agent virtualization
4160 } elsif ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
4162 push @cust_main, qsearch( {
4163 'table' => 'cust_main',
4164 'hashref' => { 'custnum' => $1, %options },
4165 'extra_sql' => " AND $agentnums_sql", #agent virtualization
4168 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
4170 my($company, $last, $first) = ( $1, $2, $3 );
4172 # "Company (Last, First)"
4173 #this is probably something a browser remembered,
4174 #so just do an exact search
4176 foreach my $prefix ( '', 'ship_' ) {
4177 push @cust_main, qsearch( {
4178 'table' => 'cust_main',
4179 'hashref' => { $prefix.'first' => $first,
4180 $prefix.'last' => $last,
4181 $prefix.'company' => $company,
4184 'extra_sql' => " AND $agentnums_sql",
4188 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
4189 # try (ship_){last,company}
4193 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
4194 # # full strings the browser remembers won't work
4195 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
4197 use Lingua::EN::NameParse;
4198 my $NameParse = new Lingua::EN::NameParse(
4200 allow_reversed => 1,
4203 my($last, $first) = ( '', '' );
4204 #maybe disable this too and just rely on NameParse?
4205 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
4207 ($last, $first) = ( $1, $2 );
4209 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
4210 } elsif ( ! $NameParse->parse($value) ) {
4212 my %name = $NameParse->components;
4213 $first = $name{'given_name_1'};
4214 $last = $name{'surname_1'};
4218 if ( $first && $last ) {
4220 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
4223 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4225 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
4226 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
4229 push @cust_main, qsearch( {
4230 'table' => 'cust_main',
4231 'hashref' => \%options,
4232 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4235 # or it just be something that was typed in... (try that in a sec)
4239 my $q_value = dbh->quote($value);
4242 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
4243 $sql .= " ( LOWER(last) = $q_value
4244 OR LOWER(company) = $q_value
4245 OR LOWER(ship_last) = $q_value
4246 OR LOWER(ship_company) = $q_value
4249 push @cust_main, qsearch( {
4250 'table' => 'cust_main',
4251 'hashref' => \%options,
4252 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
4255 #always do substring & fuzzy,
4256 #getting complains searches are not returning enough
4257 #unless ( @cust_main ) { #no exact match, trying substring/fuzzy
4259 #still some false laziness w/ search/cust_main.cgi
4264 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
4265 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
4268 if ( $first && $last ) {
4271 { 'first' => { op=>'ILIKE', value=>"%$first%" },
4272 'last' => { op=>'ILIKE', value=>"%$last%" },
4274 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
4275 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
4282 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
4283 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
4287 foreach my $hashref ( @hashrefs ) {
4289 push @cust_main, qsearch( {
4290 'table' => 'cust_main',
4291 'hashref' => { %$hashref,
4294 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
4303 " AND $agentnums_sql", #extra_sql #agent virtualization
4306 if ( $first && $last ) {
4307 push @cust_main, FS::cust_main->fuzzy_search(
4308 { 'last' => $last, #fuzzy hashref
4309 'first' => $first }, #
4313 foreach my $field ( 'last', 'company' ) {
4315 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
4320 #eliminate duplicates
4322 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
4330 =item check_and_rebuild_fuzzyfiles
4334 use vars qw(@fuzzyfields);
4335 @fuzzyfields = ( 'last', 'first', 'company' );
4337 sub check_and_rebuild_fuzzyfiles {
4338 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4339 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
4342 =item rebuild_fuzzyfiles
4346 sub rebuild_fuzzyfiles {
4348 use Fcntl qw(:flock);
4350 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4351 mkdir $dir, 0700 unless -d $dir;
4353 foreach my $fuzzy ( @fuzzyfields ) {
4355 open(LOCK,">>$dir/cust_main.$fuzzy")
4356 or die "can't open $dir/cust_main.$fuzzy: $!";
4358 or die "can't lock $dir/cust_main.$fuzzy: $!";
4360 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
4361 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
4363 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
4364 my $sth = dbh->prepare("SELECT $field FROM cust_main".
4365 " WHERE $field != '' AND $field IS NOT NULL");
4366 $sth->execute or die $sth->errstr;
4368 while ( my $row = $sth->fetchrow_arrayref ) {
4369 print CACHE $row->[0]. "\n";
4374 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
4376 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
4387 my( $self, $field ) = @_;
4388 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4389 open(CACHE,"<$dir/cust_main.$field")
4390 or die "can't open $dir/cust_main.$field: $!";
4391 my @array = map { chomp; $_; } <CACHE>;
4396 =item append_fuzzyfiles LASTNAME COMPANY
4400 sub append_fuzzyfiles {
4401 #my( $first, $last, $company ) = @_;
4403 &check_and_rebuild_fuzzyfiles;
4405 use Fcntl qw(:flock);
4407 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
4409 foreach my $field (qw( first last company )) {
4414 open(CACHE,">>$dir/cust_main.$field")
4415 or die "can't open $dir/cust_main.$field: $!";
4416 flock(CACHE,LOCK_EX)
4417 or die "can't lock $dir/cust_main.$field: $!";
4419 print CACHE "$value\n";
4421 flock(CACHE,LOCK_UN)
4422 or die "can't unlock $dir/cust_main.$field: $!";
4437 #warn join('-',keys %$param);
4438 my $fh = $param->{filehandle};
4439 my $agentnum = $param->{agentnum};
4441 my $refnum = $param->{refnum};
4442 my $pkgpart = $param->{pkgpart};
4444 #my @fields = @{$param->{fields}};
4445 my $format = $param->{'format'};
4448 if ( $format eq 'simple' ) {
4449 @fields = qw( cust_pkg.setup dayphone first last
4450 address1 address2 city state zip comments );
4452 } elsif ( $format eq 'extended' ) {
4453 @fields = qw( agent_custid refnum
4454 last first address1 address2 city state zip country
4456 ship_last ship_first ship_address1 ship_address2
4457 ship_city ship_state ship_zip ship_country
4458 payinfo paycvv paydate
4461 svc_acct.username svc_acct._password
4465 die "unknown format $format";
4468 eval "use Text::CSV_XS;";
4471 my $csv = new Text::CSV_XS;
4478 local $SIG{HUP} = 'IGNORE';
4479 local $SIG{INT} = 'IGNORE';
4480 local $SIG{QUIT} = 'IGNORE';
4481 local $SIG{TERM} = 'IGNORE';
4482 local $SIG{TSTP} = 'IGNORE';
4483 local $SIG{PIPE} = 'IGNORE';
4485 my $oldAutoCommit = $FS::UID::AutoCommit;
4486 local $FS::UID::AutoCommit = 0;
4489 #while ( $columns = $csv->getline($fh) ) {
4491 while ( defined($line=<$fh>) ) {
4493 $csv->parse($line) or do {
4494 $dbh->rollback if $oldAutoCommit;
4495 return "can't parse: ". $csv->error_input();
4498 my @columns = $csv->fields();
4499 #warn join('-',@columns);
4502 agentnum => $agentnum,
4504 country => $conf->config('countrydefault') || 'US',
4505 payby => $payby, #default
4506 paydate => '12/2037', #default
4508 my $billtime = time;
4509 my %cust_pkg = ( pkgpart => $pkgpart );
4511 foreach my $field ( @fields ) {
4513 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|expire|cancel)$/ ) {
4515 #$cust_pkg{$1} = str2time( shift @$columns );
4516 if ( $1 eq 'pkgpart' ) {
4517 $cust_pkg{$1} = shift @columns;
4518 } elsif ( $1 eq 'setup' ) {
4519 $billtime = str2time(shift @columns);
4521 $cust_pkg{$1} = str2time( shift @columns );
4524 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
4526 $svc_acct{$1} = shift @columns;
4530 #refnum interception
4531 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
4533 my $referral = $columns[0];
4534 my %hash = ( 'referral' => $referral,
4535 'agentnum' => $agentnum,
4539 my $part_referral = qsearchs('part_referral', \%hash )
4540 || new FS::part_referral \%hash;
4542 unless ( $part_referral->refnum ) {
4543 my $error = $part_referral->insert;
4545 $dbh->rollback if $oldAutoCommit;
4546 return "can't auto-insert advertising source: $referral: $error";
4550 $columns[0] = $part_referral->refnum;
4553 #$cust_main{$field} = shift @$columns;
4554 $cust_main{$field} = shift @columns;
4558 $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
4560 my $invoicing_list = $cust_main{'invoicing_list'}
4561 ? [ delete $cust_main{'invoicing_list'} ]
4564 my $cust_main = new FS::cust_main ( \%cust_main );
4567 tie my %hash, 'Tie::RefHash'; #this part is important
4569 if ( $cust_pkg{'pkgpart'} ) {
4570 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
4573 if ( $svc_acct{'username'} ) {
4574 my $part_pkg = $cust_pkg->part_pkg;
4575 unless ( $part_pkg ) {
4576 $dbh->rollback if $oldAutoCommit;
4577 return "unknown pkgnum ". $cust_pkg{'pkgpart'};
4579 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
4580 push @svc_acct, new FS::svc_acct ( \%svc_acct )
4583 $hash{$cust_pkg} = \@svc_acct;
4586 my $error = $cust_main->insert( \%hash, $invoicing_list );
4589 $dbh->rollback if $oldAutoCommit;
4590 return "can't insert customer for $line: $error";
4593 if ( $format eq 'simple' ) {
4595 #false laziness w/bill.cgi
4596 $error = $cust_main->bill( 'time' => $billtime );
4598 $dbh->rollback if $oldAutoCommit;
4599 return "can't bill customer for $line: $error";
4602 $cust_main->apply_payments_and_credits;
4604 $error = $cust_main->collect();
4606 $dbh->rollback if $oldAutoCommit;
4607 return "can't collect customer for $line: $error";
4615 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4617 return "Empty file!" unless $imported;
4629 #warn join('-',keys %$param);
4630 my $fh = $param->{filehandle};
4631 my @fields = @{$param->{fields}};
4633 eval "use Text::CSV_XS;";
4636 my $csv = new Text::CSV_XS;
4643 local $SIG{HUP} = 'IGNORE';
4644 local $SIG{INT} = 'IGNORE';
4645 local $SIG{QUIT} = 'IGNORE';
4646 local $SIG{TERM} = 'IGNORE';
4647 local $SIG{TSTP} = 'IGNORE';
4648 local $SIG{PIPE} = 'IGNORE';
4650 my $oldAutoCommit = $FS::UID::AutoCommit;
4651 local $FS::UID::AutoCommit = 0;
4654 #while ( $columns = $csv->getline($fh) ) {
4656 while ( defined($line=<$fh>) ) {
4658 $csv->parse($line) or do {
4659 $dbh->rollback if $oldAutoCommit;
4660 return "can't parse: ". $csv->error_input();
4663 my @columns = $csv->fields();
4664 #warn join('-',@columns);
4667 foreach my $field ( @fields ) {
4668 $row{$field} = shift @columns;
4671 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
4672 unless ( $cust_main ) {
4673 $dbh->rollback if $oldAutoCommit;
4674 return "unknown custnum $row{'custnum'}";
4677 if ( $row{'amount'} > 0 ) {
4678 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4680 $dbh->rollback if $oldAutoCommit;
4684 } elsif ( $row{'amount'} < 0 ) {
4685 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4688 $dbh->rollback if $oldAutoCommit;
4698 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4700 return "Empty file!" unless $imported;
4706 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4708 Sends a templated email notification to the customer (see L<Text::Template).
4710 OPTIONS is a hash and may include
4712 I<from> - the email sender (default is invoice_from)
4714 I<to> - comma-separated scalar or arrayref of recipients
4715 (default is invoicing_list)
4717 I<subject> - The subject line of the sent email notification
4718 (default is "Notice from company_name")
4720 I<extra_fields> - a hashref of name/value pairs which will be substituted
4723 The following variables are vavailable in the template.
4725 I<$first> - the customer first name
4726 I<$last> - the customer last name
4727 I<$company> - the customer company
4728 I<$payby> - a description of the method of payment for the customer
4729 # would be nice to use FS::payby::shortname
4730 I<$payinfo> - the account information used to collect for this customer
4731 I<$expdate> - the expiration of the customer payment in seconds from epoch
4736 my ($customer, $template, %options) = @_;
4738 return unless $conf->exists($template);
4740 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
4741 $from = $options{from} if exists($options{from});
4743 my $to = join(',', $customer->invoicing_list_emailonly);
4744 $to = $options{to} if exists($options{to});
4746 my $subject = "Notice from " . $conf->config('company_name')
4747 if $conf->exists('company_name');
4748 $subject = $options{subject} if exists($options{subject});
4750 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4751 SOURCE => [ map "$_\n",
4752 $conf->config($template)]
4754 or die "can't create new Text::Template object: Text::Template::ERROR";
4755 $notify_template->compile()
4756 or die "can't compile template: Text::Template::ERROR";
4758 my $paydate = $customer->paydate;
4759 $FS::notify_template::_template::first = $customer->first;
4760 $FS::notify_template::_template::last = $customer->last;
4761 $FS::notify_template::_template::company = $customer->company;
4762 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
4763 my $payby = $customer->payby;
4764 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4765 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4767 #credit cards expire at the end of the month/year of their exp date
4768 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4769 $FS::notify_template::_template::payby = 'credit card';
4770 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4771 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4773 }elsif ($payby eq 'COMP') {
4774 $FS::notify_template::_template::payby = 'complimentary account';
4776 $FS::notify_template::_template::payby = 'current method';
4778 $FS::notify_template::_template::expdate = $expire_time;
4780 for (keys %{$options{extra_fields}}){
4782 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4785 send_email(from => $from,
4787 subject => $subject,
4788 body => $notify_template->fill_in( PACKAGE =>
4789 'FS::notify_template::_template' ),
4800 The delete method should possibly take an FS::cust_main object reference
4801 instead of a scalar customer number.
4803 Bill and collect options should probably be passed as references instead of a
4806 There should probably be a configuration file with a list of allowed credit
4809 No multiple currency support (probably a larger project than just this module).
4811 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4813 Birthdates rely on negative epoch values.
4817 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4818 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4819 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.