be polite! don't spew debugging info unless its asked for.
[freeside.git] / FS / FS / cust_main.pm
1 package FS::cust_main;
2
3 require 5.006;
4 use strict;
5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6              $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
8 use Safe;
9 use Carp;
10 use Exporter;
11 use Time::Local qw(timelocal_nocheck);
12 use Data::Dumper;
13 use Tie::IxHash;
14 use Digest::MD5 qw(md5_base64);
15 use Date::Format;
16 use Date::Parse;
17 #use Date::Manip;
18 use String::Approx qw(amatch);
19 use Business::CreditCard 0.28;
20 use Locale::Country;
21 use Data::Dumper;
22 use FS::UID qw( getotaker dbh );
23 use FS::Record qw( qsearchs qsearch dbdef );
24 use FS::Misc qw( send_email generate_ps do_print );
25 use FS::Msgcat qw(gettext);
26 use FS::cust_pkg;
27 use FS::cust_svc;
28 use FS::cust_bill;
29 use FS::cust_bill_pkg;
30 use FS::cust_pay;
31 use FS::cust_pay_void;
32 use FS::cust_pay_batch;
33 use FS::cust_credit;
34 use FS::cust_refund;
35 use FS::part_referral;
36 use FS::cust_main_county;
37 use FS::agent;
38 use FS::cust_main_invoice;
39 use FS::cust_credit_bill;
40 use FS::cust_bill_pay;
41 use FS::prepay_credit;
42 use FS::queue;
43 use FS::part_pkg;
44 use FS::part_event;
45 use FS::part_event_condition;
46 #use FS::cust_event;
47 use FS::cust_tax_exempt;
48 use FS::cust_tax_exempt_pkg;
49 use FS::type_pkgs;
50 use FS::payment_gateway;
51 use FS::agent_payment_gateway;
52 use FS::banned_pay;
53 use FS::payinfo_Mixin;
54 use FS::TicketSystem;
55
56 @ISA = qw( FS::Record FS::payinfo_Mixin );
57
58 @EXPORT_OK = qw( smart_search );
59
60 $realtime_bop_decline_quiet = 0;
61
62 # 1 is mostly method/subroutine entry and options
63 # 2 traces progress of some operations
64 # 3 is even more information including possibly sensitive data
65 $DEBUG = 0;
66 $me = '[FS::cust_main]';
67
68 $import = 0;
69 $skip_fuzzyfiles = 0;
70 $ignore_expired_card = 0;
71
72 @encrypted_fields = ('payinfo', 'paycvv');
73 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
74
75 #ask FS::UID to run this stuff for us later
76 #$FS::UID::callback{'FS::cust_main'} = sub { 
77 install_callback FS::UID sub { 
78   $conf = new FS::Conf;
79   #yes, need it for stuff below (prolly should be cached)
80 };
81
82 sub _cache {
83   my $self = shift;
84   my ( $hashref, $cache ) = @_;
85   if ( exists $hashref->{'pkgnum'} ) {
86     #@{ $self->{'_pkgnum'} } = ();
87     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
88     $self->{'_pkgnum'} = $subcache;
89     #push @{ $self->{'_pkgnum'} },
90     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
91   }
92 }
93
94 =head1 NAME
95
96 FS::cust_main - Object methods for cust_main records
97
98 =head1 SYNOPSIS
99
100   use FS::cust_main;
101
102   $record = new FS::cust_main \%hash;
103   $record = new FS::cust_main { 'column' => 'value' };
104
105   $error = $record->insert;
106
107   $error = $new_record->replace($old_record);
108
109   $error = $record->delete;
110
111   $error = $record->check;
112
113   @cust_pkg = $record->all_pkgs;
114
115   @cust_pkg = $record->ncancelled_pkgs;
116
117   @cust_pkg = $record->suspended_pkgs;
118
119   $error = $record->bill;
120   $error = $record->bill %options;
121   $error = $record->bill 'time' => $time;
122
123   $error = $record->collect;
124   $error = $record->collect %options;
125   $error = $record->collect 'invoice_time'   => $time,
126                           ;
127
128 =head1 DESCRIPTION
129
130 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
131 FS::Record.  The following fields are currently supported:
132
133 =over 4
134
135 =item custnum - primary key (assigned automatically for new customers)
136
137 =item agentnum - agent (see L<FS::agent>)
138
139 =item refnum - Advertising source (see L<FS::part_referral>)
140
141 =item first - name
142
143 =item last - name
144
145 =item ss - social security number (optional)
146
147 =item company - (optional)
148
149 =item address1
150
151 =item address2 - (optional)
152
153 =item city
154
155 =item county - (optional, see L<FS::cust_main_county>)
156
157 =item state - (see L<FS::cust_main_county>)
158
159 =item zip
160
161 =item country - (see L<FS::cust_main_county>)
162
163 =item daytime - phone (optional)
164
165 =item night - phone (optional)
166
167 =item fax - phone (optional)
168
169 =item ship_first - name
170
171 =item ship_last - name
172
173 =item ship_company - (optional)
174
175 =item ship_address1
176
177 =item ship_address2 - (optional)
178
179 =item ship_city
180
181 =item ship_county - (optional, see L<FS::cust_main_county>)
182
183 =item ship_state - (see L<FS::cust_main_county>)
184
185 =item ship_zip
186
187 =item ship_country - (see L<FS::cust_main_county>)
188
189 =item ship_daytime - phone (optional)
190
191 =item ship_night - phone (optional)
192
193 =item ship_fax - phone (optional)
194
195 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
196
197 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
198
199 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
200
201 =item paycvv
202
203 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
204
205 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
206
207 =item paystart_month - start date month (maestro/solo cards only)
208
209 =item paystart_year - start date year (maestro/solo cards only)
210
211 =item payissue - issue number (maestro/solo cards only)
212
213 =item payname - name on card or billing name
214
215 =item payip - IP address from which payment information was received
216
217 =item tax - tax exempt, empty or `Y'
218
219 =item otaker - order taker (assigned automatically, see L<FS::UID>)
220
221 =item comments - comments (optional)
222
223 =item referral_custnum - referring customer number
224
225 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
226
227 =back
228
229 =head1 METHODS
230
231 =over 4
232
233 =item new HASHREF
234
235 Creates a new customer.  To add the customer to the database, see L<"insert">.
236
237 Note that this stores the hash reference, not a distinct copy of the hash it
238 points to.  You can ask the object for a copy with the I<hash> method.
239
240 =cut
241
242 sub table { 'cust_main'; }
243
244 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
245
246 Adds this customer to the database.  If there is an error, returns the error,
247 otherwise returns false.
248
249 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
250 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
251 are inserted atomicly, or the transaction is rolled back.  Passing an empty
252 hash reference is equivalent to not supplying this parameter.  There should be
253 a better explanation of this, but until then, here's an example:
254
255   use Tie::RefHash;
256   tie %hash, 'Tie::RefHash'; #this part is important
257   %hash = (
258     $cust_pkg => [ $svc_acct ],
259     ...
260   );
261   $cust_main->insert( \%hash );
262
263 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
264 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
265 expected and rollback the entire transaction; it is not necessary to call 
266 check_invoicing_list first.  The invoicing_list is set after the records in the
267 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
268 invoicing_list destination to the newly-created svc_acct.  Here's an example:
269
270   $cust_main->insert( {}, [ $email, 'POST' ] );
271
272 Currently available options are: I<depend_jobnum> and I<noexport>.
273
274 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
275 on the supplied jobnum (they will not run until the specific job completes).
276 This can be used to defer provisioning until some action completes (such
277 as running the customer's credit card successfully).
278
279 The I<noexport> option is deprecated.  If I<noexport> is set true, no
280 provisioning jobs (exports) are scheduled.  (You can schedule them later with
281 the B<reexport> method.)
282
283 =cut
284
285 sub insert {
286   my $self = shift;
287   my $cust_pkgs = @_ ? shift : {};
288   my $invoicing_list = @_ ? shift : '';
289   my %options = @_;
290   warn "$me insert called with options ".
291        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
292     if $DEBUG;
293
294   local $SIG{HUP} = 'IGNORE';
295   local $SIG{INT} = 'IGNORE';
296   local $SIG{QUIT} = 'IGNORE';
297   local $SIG{TERM} = 'IGNORE';
298   local $SIG{TSTP} = 'IGNORE';
299   local $SIG{PIPE} = 'IGNORE';
300
301   my $oldAutoCommit = $FS::UID::AutoCommit;
302   local $FS::UID::AutoCommit = 0;
303   my $dbh = dbh;
304
305   my $prepay_identifier = '';
306   my( $amount, $seconds ) = ( 0, 0 );
307   my $payby = '';
308   if ( $self->payby eq 'PREPAY' ) {
309
310     $self->payby('BILL');
311     $prepay_identifier = $self->payinfo;
312     $self->payinfo('');
313
314     warn "  looking up prepaid card $prepay_identifier\n"
315       if $DEBUG > 1;
316
317     my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
318     if ( $error ) {
319       $dbh->rollback if $oldAutoCommit;
320       #return "error applying prepaid card (transaction rolled back): $error";
321       return $error;
322     }
323
324     $payby = 'PREP' if $amount;
325
326   } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
327
328     $payby = $1;
329     $self->payby('BILL');
330     $amount = $self->paid;
331
332   }
333
334   warn "  inserting $self\n"
335     if $DEBUG > 1;
336
337   $self->signupdate(time) unless $self->signupdate;
338
339   my $error = $self->SUPER::insert;
340   if ( $error ) {
341     $dbh->rollback if $oldAutoCommit;
342     #return "inserting cust_main record (transaction rolled back): $error";
343     return $error;
344   }
345
346   warn "  setting invoicing list\n"
347     if $DEBUG > 1;
348
349   if ( $invoicing_list ) {
350     $error = $self->check_invoicing_list( $invoicing_list );
351     if ( $error ) {
352       $dbh->rollback if $oldAutoCommit;
353       #return "checking invoicing_list (transaction rolled back): $error";
354       return $error;
355     }
356     $self->invoicing_list( $invoicing_list );
357   }
358
359   if (    $conf->config('cust_main-skeleton_tables')
360        && $conf->config('cust_main-skeleton_custnum') ) {
361
362     warn "  inserting skeleton records\n"
363       if $DEBUG > 1;
364
365     my $error = $self->start_copy_skel;
366     if ( $error ) {
367       $dbh->rollback if $oldAutoCommit;
368       return $error;
369     }
370
371   }
372
373   warn "  ordering packages\n"
374     if $DEBUG > 1;
375
376   $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
377   if ( $error ) {
378     $dbh->rollback if $oldAutoCommit;
379     return $error;
380   }
381
382   if ( $seconds ) {
383     $dbh->rollback if $oldAutoCommit;
384     return "No svc_acct record to apply pre-paid time";
385   }
386
387   if ( $amount ) {
388     warn "  inserting initial $payby payment of $amount\n"
389       if $DEBUG > 1;
390     $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
391     if ( $error ) {
392       $dbh->rollback if $oldAutoCommit;
393       return "inserting payment (transaction rolled back): $error";
394     }
395   }
396
397   unless ( $import || $skip_fuzzyfiles ) {
398     warn "  queueing fuzzyfiles update\n"
399       if $DEBUG > 1;
400     $error = $self->queue_fuzzyfiles_update;
401     if ( $error ) {
402       $dbh->rollback if $oldAutoCommit;
403       return "updating fuzzy search cache: $error";
404     }
405   }
406
407   warn "  insert complete; committing transaction\n"
408     if $DEBUG > 1;
409
410   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
411   '';
412
413 }
414
415 sub start_copy_skel {
416   my $self = shift;
417
418   #'mg_user_preference' => {},
419   #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
420   #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
421   #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
422   #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
423   my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
424   die $@ if $@;
425
426   _copy_skel( 'cust_main',                                 #tablename
427               $conf->config('cust_main-skeleton_custnum'), #sourceid
428               $self->custnum,                              #destid
429               @tables,                                     #child tables
430             );
431 }
432
433 #recursive subroutine, not a method
434 sub _copy_skel {
435   my( $table, $sourceid, $destid, %child_tables ) = @_;
436
437   my $primary_key;
438   if ( $table =~ /^(\w+)\.(\w+)$/ ) {
439     ( $table, $primary_key ) = ( $1, $2 );
440   } else {
441     my $dbdef_table = dbdef->table($table);
442     $primary_key = $dbdef_table->primary_key
443       or return "$table has no primary key".
444                 " (or do you need to run dbdef-create?)";
445   }
446
447   warn "  _copy_skel: $table.$primary_key $sourceid to $destid for ".
448        join (', ', keys %child_tables). "\n"
449     if $DEBUG > 2;
450
451   foreach my $child_table_def ( keys %child_tables ) {
452
453     my $child_table;
454     my $child_pkey = '';
455     if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
456       ( $child_table, $child_pkey ) = ( $1, $2 );
457     } else {
458       $child_table = $child_table_def;
459
460       $child_pkey = dbdef->table($child_table)->primary_key;
461       #  or return "$table has no primary key".
462       #            " (or do you need to run dbdef-create?)\n";
463     }
464
465     my $sequence = '';
466     if ( keys %{ $child_tables{$child_table_def} } ) {
467
468       return "$child_table has no primary key".
469              " (run dbdef-create or try specifying it?)\n"
470         unless $child_pkey;
471
472       #false laziness w/Record::insert and only works on Pg
473       #refactor the proper last-inserted-id stuff out of Record::insert if this
474       # ever gets use for anything besides a quick kludge for one customer
475       my $default = dbdef->table($child_table)->column($child_pkey)->default;
476       $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
477         or return "can't parse $child_table.$child_pkey default value ".
478                   " for sequence name: $default";
479       $sequence = $1;
480
481     }
482   
483     my @sel_columns = grep { $_ ne $primary_key }
484                            dbdef->table($child_table)->columns;
485     my $sel_columns = join(', ', @sel_columns );
486
487     my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
488     my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
489     my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
490
491     my $sel_st = "SELECT $sel_columns FROM $child_table".
492                  " WHERE $primary_key = $sourceid";
493     warn "    $sel_st\n"
494       if $DEBUG > 2;
495     my $sel_sth = dbh->prepare( $sel_st )
496       or return dbh->errstr;
497   
498     $sel_sth->execute or return $sel_sth->errstr;
499
500     while ( my $row = $sel_sth->fetchrow_hashref ) {
501
502       warn "    selected row: ".
503            join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
504         if $DEBUG > 2;
505
506       my $statement =
507         "INSERT INTO $child_table $ins_columns VALUES $placeholders";
508       my $ins_sth =dbh->prepare($statement)
509           or return dbh->errstr;
510       my @param = ( $destid, map $row->{$_}, @ins_columns );
511       warn "    $statement: [ ". join(', ', @param). " ]\n"
512         if $DEBUG > 2;
513       $ins_sth->execute( @param )
514         or return $ins_sth->errstr;
515
516       #next unless keys %{ $child_tables{$child_table} };
517       next unless $sequence;
518       
519       #another section of that laziness
520       my $seq_sql = "SELECT currval('$sequence')";
521       my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
522       $seq_sth->execute or return $seq_sth->errstr;
523       my $insertid = $seq_sth->fetchrow_arrayref->[0];
524   
525       # don't drink soap!  recurse!  recurse!  okay!
526       my $error =
527         _copy_skel( $child_table_def,
528                     $row->{$child_pkey}, #sourceid
529                     $insertid, #destid
530                     %{ $child_tables{$child_table_def} },
531                   );
532       return $error if $error;
533
534     }
535
536   }
537
538   return '';
539
540 }
541
542 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
543
544 Like the insert method on an existing record, this method orders a package
545 and included services atomicaly.  Pass a Tie::RefHash data structure to this
546 method containing FS::cust_pkg and FS::svc_I<tablename> objects.  There should
547 be a better explanation of this, but until then, here's an example:
548
549   use Tie::RefHash;
550   tie %hash, 'Tie::RefHash'; #this part is important
551   %hash = (
552     $cust_pkg => [ $svc_acct ],
553     ...
554   );
555   $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
556
557 Services can be new, in which case they are inserted, or existing unaudited
558 services, in which case they are linked to the newly-created package.
559
560 Currently available options are: I<depend_jobnum> and I<noexport>.
561
562 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
563 on the supplied jobnum (they will not run until the specific job completes).
564 This can be used to defer provisioning until some action completes (such
565 as running the customer's credit card successfully).
566
567 The I<noexport> option is deprecated.  If I<noexport> is set true, no
568 provisioning jobs (exports) are scheduled.  (You can schedule them later with
569 the B<reexport> method for each cust_pkg object.  Using the B<reexport> method
570 on the cust_main object is not recommended, as existing services will also be
571 reexported.)
572
573 =cut
574
575 sub order_pkgs {
576   my $self = shift;
577   my $cust_pkgs = shift;
578   my $seconds = shift;
579   my %options = @_;
580   my %svc_options = ();
581   $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
582     if exists $options{'depend_jobnum'};
583   warn "$me order_pkgs called with options ".
584        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
585     if $DEBUG;
586
587   local $SIG{HUP} = 'IGNORE';
588   local $SIG{INT} = 'IGNORE';
589   local $SIG{QUIT} = 'IGNORE';
590   local $SIG{TERM} = 'IGNORE';
591   local $SIG{TSTP} = 'IGNORE';
592   local $SIG{PIPE} = 'IGNORE';
593
594   my $oldAutoCommit = $FS::UID::AutoCommit;
595   local $FS::UID::AutoCommit = 0;
596   my $dbh = dbh;
597
598   local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
599
600   foreach my $cust_pkg ( keys %$cust_pkgs ) {
601     $cust_pkg->custnum( $self->custnum );
602     my $error = $cust_pkg->insert;
603     if ( $error ) {
604       $dbh->rollback if $oldAutoCommit;
605       return "inserting cust_pkg (transaction rolled back): $error";
606     }
607     foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
608       if ( $svc_something->svcnum ) {
609         my $old_cust_svc = $svc_something->cust_svc;
610         my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
611         $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
612         $error = $new_cust_svc->replace($old_cust_svc);
613       } else {
614         $svc_something->pkgnum( $cust_pkg->pkgnum );
615         if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
616           $svc_something->seconds( $svc_something->seconds + $$seconds );
617           $$seconds = 0;
618         }
619         $error = $svc_something->insert(%svc_options);
620       }
621       if ( $error ) {
622         $dbh->rollback if $oldAutoCommit;
623         #return "inserting svc_ (transaction rolled back): $error";
624         return $error;
625       }
626     }
627   }
628
629   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
630   ''; #no error
631 }
632
633 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
634
635 Recharges this (existing) customer with the specified prepaid card (see
636 L<FS::prepay_credit>), specified either by I<identifier> or as an
637 FS::prepay_credit object.  If there is an error, returns the error, otherwise
638 returns false.
639
640 Optionally, four scalar references can be passed as well.  They will have their
641 values filled in with the amount, number of seconds, and number of upload and
642 download bytes applied by this prepaid
643 card.
644
645 =cut
646
647 sub recharge_prepay { 
648   my( $self, $prepay_credit, $amountref, $secondsref, 
649       $upbytesref, $downbytesref, $totalbytesref ) = @_;
650
651   local $SIG{HUP} = 'IGNORE';
652   local $SIG{INT} = 'IGNORE';
653   local $SIG{QUIT} = 'IGNORE';
654   local $SIG{TERM} = 'IGNORE';
655   local $SIG{TSTP} = 'IGNORE';
656   local $SIG{PIPE} = 'IGNORE';
657
658   my $oldAutoCommit = $FS::UID::AutoCommit;
659   local $FS::UID::AutoCommit = 0;
660   my $dbh = dbh;
661
662   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
663
664   my $error = $self->get_prepay($prepay_credit, \$amount,
665                                 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
666            || $self->increment_seconds($seconds)
667            || $self->increment_upbytes($upbytes)
668            || $self->increment_downbytes($downbytes)
669            || $self->increment_totalbytes($totalbytes)
670            || $self->insert_cust_pay_prepay( $amount,
671                                              ref($prepay_credit)
672                                                ? $prepay_credit->identifier
673                                                : $prepay_credit
674                                            );
675
676   if ( $error ) {
677     $dbh->rollback if $oldAutoCommit;
678     return $error;
679   }
680
681   if ( defined($amountref)  ) { $$amountref  = $amount;  }
682   if ( defined($secondsref) ) { $$secondsref = $seconds; }
683   if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
684   if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
685   if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
686
687   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
688   '';
689
690 }
691
692 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
693
694 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
695 specified either by I<identifier> or as an FS::prepay_credit object.
696
697 References to I<amount> and I<seconds> scalars should be passed as arguments
698 and will be incremented by the values of the prepaid card.
699
700 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
701 check or set this customer's I<agentnum>.
702
703 If there is an error, returns the error, otherwise returns false.
704
705 =cut
706
707
708 sub get_prepay {
709   my( $self, $prepay_credit, $amountref, $secondsref,
710       $upref, $downref, $totalref) = @_;
711
712   local $SIG{HUP} = 'IGNORE';
713   local $SIG{INT} = 'IGNORE';
714   local $SIG{QUIT} = 'IGNORE';
715   local $SIG{TERM} = 'IGNORE';
716   local $SIG{TSTP} = 'IGNORE';
717   local $SIG{PIPE} = 'IGNORE';
718
719   my $oldAutoCommit = $FS::UID::AutoCommit;
720   local $FS::UID::AutoCommit = 0;
721   my $dbh = dbh;
722
723   unless ( ref($prepay_credit) ) {
724
725     my $identifier = $prepay_credit;
726
727     $prepay_credit = qsearchs(
728       'prepay_credit',
729       { 'identifier' => $prepay_credit },
730       '',
731       'FOR UPDATE'
732     );
733
734     unless ( $prepay_credit ) {
735       $dbh->rollback if $oldAutoCommit;
736       return "Invalid prepaid card: ". $identifier;
737     }
738
739   }
740
741   if ( $prepay_credit->agentnum ) {
742     if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
743       $dbh->rollback if $oldAutoCommit;
744       return "prepaid card not valid for agent ". $self->agentnum;
745     }
746     $self->agentnum($prepay_credit->agentnum);
747   }
748
749   my $error = $prepay_credit->delete;
750   if ( $error ) {
751     $dbh->rollback if $oldAutoCommit;
752     return "removing prepay_credit (transaction rolled back): $error";
753   }
754
755   $$amountref  += $prepay_credit->amount;
756   $$secondsref += $prepay_credit->seconds;
757   $$upref      += $prepay_credit->upbytes;
758   $$downref    += $prepay_credit->downbytes;
759   $$totalref   += $prepay_credit->totalbytes;
760
761   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
762   '';
763
764 }
765
766 =item increment_upbytes SECONDS
767
768 Updates this customer's single or primary account (see L<FS::svc_acct>) by
769 the specified number of upbytes.  If there is an error, returns the error,
770 otherwise returns false.
771
772 =cut
773
774 sub increment_upbytes {
775   _increment_column( shift, 'upbytes', @_);
776 }
777
778 =item increment_downbytes SECONDS
779
780 Updates this customer's single or primary account (see L<FS::svc_acct>) by
781 the specified number of downbytes.  If there is an error, returns the error,
782 otherwise returns false.
783
784 =cut
785
786 sub increment_downbytes {
787   _increment_column( shift, 'downbytes', @_);
788 }
789
790 =item increment_totalbytes SECONDS
791
792 Updates this customer's single or primary account (see L<FS::svc_acct>) by
793 the specified number of totalbytes.  If there is an error, returns the error,
794 otherwise returns false.
795
796 =cut
797
798 sub increment_totalbytes {
799   _increment_column( shift, 'totalbytes', @_);
800 }
801
802 =item increment_seconds SECONDS
803
804 Updates this customer's single or primary account (see L<FS::svc_acct>) by
805 the specified number of seconds.  If there is an error, returns the error,
806 otherwise returns false.
807
808 =cut
809
810 sub increment_seconds {
811   _increment_column( shift, 'seconds', @_);
812 }
813
814 =item _increment_column AMOUNT
815
816 Updates this customer's single or primary account (see L<FS::svc_acct>) by
817 the specified number of seconds or bytes.  If there is an error, returns
818 the error, otherwise returns false.
819
820 =cut
821
822 sub _increment_column {
823   my( $self, $column, $amount ) = @_;
824   warn "$me increment_column called: $column, $amount\n"
825     if $DEBUG;
826
827   return '' unless $amount;
828
829   my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
830                       $self->ncancelled_pkgs;
831
832   if ( ! @cust_pkg ) {
833     return 'No packages with primary or single services found'.
834            ' to apply pre-paid time';
835   } elsif ( scalar(@cust_pkg) > 1 ) {
836     #maybe have a way to specify the package/account?
837     return 'Multiple packages found to apply pre-paid time';
838   }
839
840   my $cust_pkg = $cust_pkg[0];
841   warn "  found package pkgnum ". $cust_pkg->pkgnum. "\n"
842     if $DEBUG > 1;
843
844   my @cust_svc =
845     $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
846
847   if ( ! @cust_svc ) {
848     return 'No account found to apply pre-paid time';
849   } elsif ( scalar(@cust_svc) > 1 ) {
850     return 'Multiple accounts found to apply pre-paid time';
851   }
852   
853   my $svc_acct = $cust_svc[0]->svc_x;
854   warn "  found service svcnum ". $svc_acct->pkgnum.
855        ' ('. $svc_acct->email. ")\n"
856     if $DEBUG > 1;
857
858   $column = "increment_$column";
859   $svc_acct->$column($amount);
860
861 }
862
863 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
864
865 Inserts a prepayment in the specified amount for this customer.  An optional
866 second argument can specify the prepayment identifier for tracking purposes.
867 If there is an error, returns the error, otherwise returns false.
868
869 =cut
870
871 sub insert_cust_pay_prepay {
872   shift->insert_cust_pay('PREP', @_);
873 }
874
875 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
876
877 Inserts a cash payment in the specified amount for this customer.  An optional
878 second argument can specify the payment identifier for tracking purposes.
879 If there is an error, returns the error, otherwise returns false.
880
881 =cut
882
883 sub insert_cust_pay_cash {
884   shift->insert_cust_pay('CASH', @_);
885 }
886
887 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
888
889 Inserts a Western Union payment in the specified amount for this customer.  An
890 optional second argument can specify the prepayment identifier for tracking
891 purposes.  If there is an error, returns the error, otherwise returns false.
892
893 =cut
894
895 sub insert_cust_pay_west {
896   shift->insert_cust_pay('WEST', @_);
897 }
898
899 sub insert_cust_pay {
900   my( $self, $payby, $amount ) = splice(@_, 0, 3);
901   my $payinfo = scalar(@_) ? shift : '';
902
903   my $cust_pay = new FS::cust_pay {
904     'custnum' => $self->custnum,
905     'paid'    => sprintf('%.2f', $amount),
906     #'_date'   => #date the prepaid card was purchased???
907     'payby'   => $payby,
908     'payinfo' => $payinfo,
909   };
910   $cust_pay->insert;
911
912 }
913
914 =item reexport
915
916 This method is deprecated.  See the I<depend_jobnum> option to the insert and
917 order_pkgs methods for a better way to defer provisioning.
918
919 Re-schedules all exports by calling the B<reexport> method of all associated
920 packages (see L<FS::cust_pkg>).  If there is an error, returns the error;
921 otherwise returns false.
922
923 =cut
924
925 sub reexport {
926   my $self = shift;
927
928   carp "WARNING: FS::cust_main::reexport is deprectated; ".
929        "use the depend_jobnum option to insert or order_pkgs to delay export";
930
931   local $SIG{HUP} = 'IGNORE';
932   local $SIG{INT} = 'IGNORE';
933   local $SIG{QUIT} = 'IGNORE';
934   local $SIG{TERM} = 'IGNORE';
935   local $SIG{TSTP} = 'IGNORE';
936   local $SIG{PIPE} = 'IGNORE';
937
938   my $oldAutoCommit = $FS::UID::AutoCommit;
939   local $FS::UID::AutoCommit = 0;
940   my $dbh = dbh;
941
942   foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
943     my $error = $cust_pkg->reexport;
944     if ( $error ) {
945       $dbh->rollback if $oldAutoCommit;
946       return $error;
947     }
948   }
949
950   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
951   '';
952
953 }
954
955 =item delete NEW_CUSTNUM
956
957 This deletes the customer.  If there is an error, returns the error, otherwise
958 returns false.
959
960 This will completely remove all traces of the customer record.  This is not
961 what you want when a customer cancels service; for that, cancel all of the
962 customer's packages (see L</cancel>).
963
964 If the customer has any uncancelled packages, you need to pass a new (valid)
965 customer number for those packages to be transferred to.  Cancelled packages
966 will be deleted.  Did I mention that this is NOT what you want when a customer
967 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
968
969 You can't delete a customer with invoices (see L<FS::cust_bill>),
970 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
971 refunds (see L<FS::cust_refund>).
972
973 =cut
974
975 sub delete {
976   my $self = shift;
977
978   local $SIG{HUP} = 'IGNORE';
979   local $SIG{INT} = 'IGNORE';
980   local $SIG{QUIT} = 'IGNORE';
981   local $SIG{TERM} = 'IGNORE';
982   local $SIG{TSTP} = 'IGNORE';
983   local $SIG{PIPE} = 'IGNORE';
984
985   my $oldAutoCommit = $FS::UID::AutoCommit;
986   local $FS::UID::AutoCommit = 0;
987   my $dbh = dbh;
988
989   if ( $self->cust_bill ) {
990     $dbh->rollback if $oldAutoCommit;
991     return "Can't delete a customer with invoices";
992   }
993   if ( $self->cust_credit ) {
994     $dbh->rollback if $oldAutoCommit;
995     return "Can't delete a customer with credits";
996   }
997   if ( $self->cust_pay ) {
998     $dbh->rollback if $oldAutoCommit;
999     return "Can't delete a customer with payments";
1000   }
1001   if ( $self->cust_refund ) {
1002     $dbh->rollback if $oldAutoCommit;
1003     return "Can't delete a customer with refunds";
1004   }
1005
1006   my @cust_pkg = $self->ncancelled_pkgs;
1007   if ( @cust_pkg ) {
1008     my $new_custnum = shift;
1009     unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1010       $dbh->rollback if $oldAutoCommit;
1011       return "Invalid new customer number: $new_custnum";
1012     }
1013     foreach my $cust_pkg ( @cust_pkg ) {
1014       my %hash = $cust_pkg->hash;
1015       $hash{'custnum'} = $new_custnum;
1016       my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1017       my $error = $new_cust_pkg->replace($cust_pkg,
1018                                          options => { $cust_pkg->options },
1019                                         );
1020       if ( $error ) {
1021         $dbh->rollback if $oldAutoCommit;
1022         return $error;
1023       }
1024     }
1025   }
1026   my @cancelled_cust_pkg = $self->all_pkgs;
1027   foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1028     my $error = $cust_pkg->delete;
1029     if ( $error ) {
1030       $dbh->rollback if $oldAutoCommit;
1031       return $error;
1032     }
1033   }
1034
1035   foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1036     qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1037   ) {
1038     my $error = $cust_main_invoice->delete;
1039     if ( $error ) {
1040       $dbh->rollback if $oldAutoCommit;
1041       return $error;
1042     }
1043   }
1044
1045   my $error = $self->SUPER::delete;
1046   if ( $error ) {
1047     $dbh->rollback if $oldAutoCommit;
1048     return $error;
1049   }
1050
1051   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1052   '';
1053
1054 }
1055
1056 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
1057
1058 Replaces the OLD_RECORD with this one in the database.  If there is an error,
1059 returns the error, otherwise returns false.
1060
1061 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1062 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
1063 expected and rollback the entire transaction; it is not necessary to call 
1064 check_invoicing_list first.  Here's an example:
1065
1066   $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1067
1068 =cut
1069
1070 sub replace {
1071   my $self = shift;
1072   my $old = shift;
1073   my @param = @_;
1074   warn "$me replace called\n"
1075     if $DEBUG;
1076
1077   local $SIG{HUP} = 'IGNORE';
1078   local $SIG{INT} = 'IGNORE';
1079   local $SIG{QUIT} = 'IGNORE';
1080   local $SIG{TERM} = 'IGNORE';
1081   local $SIG{TSTP} = 'IGNORE';
1082   local $SIG{PIPE} = 'IGNORE';
1083
1084   # We absolutely have to have an old vs. new record to make this work.
1085   if (!defined($old)) {
1086     $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1087   }
1088
1089   my $curuser = $FS::CurrentUser::CurrentUser;
1090   if (    $self->payby eq 'COMP'
1091        && $self->payby ne $old->payby
1092        && ! $curuser->access_right('Complimentary customer')
1093      )
1094   {
1095     return "You are not permitted to create complimentary accounts.";
1096   }
1097
1098   local($ignore_expired_card) = 1
1099     if $old->payby  =~ /^(CARD|DCRD)$/
1100     && $self->payby =~ /^(CARD|DCRD)$/
1101     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1102
1103   my $oldAutoCommit = $FS::UID::AutoCommit;
1104   local $FS::UID::AutoCommit = 0;
1105   my $dbh = dbh;
1106
1107   my $error = $self->SUPER::replace($old);
1108
1109   if ( $error ) {
1110     $dbh->rollback if $oldAutoCommit;
1111     return $error;
1112   }
1113
1114   if ( @param ) { # INVOICING_LIST_ARYREF
1115     my $invoicing_list = shift @param;
1116     $error = $self->check_invoicing_list( $invoicing_list );
1117     if ( $error ) {
1118       $dbh->rollback if $oldAutoCommit;
1119       return $error;
1120     }
1121     $self->invoicing_list( $invoicing_list );
1122   }
1123
1124   if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1125        grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1126     # card/check/lec info has changed, want to retry realtime_ invoice events
1127     my $error = $self->retry_realtime;
1128     if ( $error ) {
1129       $dbh->rollback if $oldAutoCommit;
1130       return $error;
1131     }
1132   }
1133
1134   unless ( $import || $skip_fuzzyfiles ) {
1135     $error = $self->queue_fuzzyfiles_update;
1136     if ( $error ) {
1137       $dbh->rollback if $oldAutoCommit;
1138       return "updating fuzzy search cache: $error";
1139     }
1140   }
1141
1142   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1143   '';
1144
1145 }
1146
1147 =item queue_fuzzyfiles_update
1148
1149 Used by insert & replace to update the fuzzy search cache
1150
1151 =cut
1152
1153 sub queue_fuzzyfiles_update {
1154   my $self = shift;
1155
1156   local $SIG{HUP} = 'IGNORE';
1157   local $SIG{INT} = 'IGNORE';
1158   local $SIG{QUIT} = 'IGNORE';
1159   local $SIG{TERM} = 'IGNORE';
1160   local $SIG{TSTP} = 'IGNORE';
1161   local $SIG{PIPE} = 'IGNORE';
1162
1163   my $oldAutoCommit = $FS::UID::AutoCommit;
1164   local $FS::UID::AutoCommit = 0;
1165   my $dbh = dbh;
1166
1167   my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1168   my $error = $queue->insert( map $self->getfield($_),
1169                                   qw(first last company)
1170                             );
1171   if ( $error ) {
1172     $dbh->rollback if $oldAutoCommit;
1173     return "queueing job (transaction rolled back): $error";
1174   }
1175
1176   if ( $self->ship_last ) {
1177     $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1178     $error = $queue->insert( map $self->getfield("ship_$_"),
1179                                  qw(first last company)
1180                            );
1181     if ( $error ) {
1182       $dbh->rollback if $oldAutoCommit;
1183       return "queueing job (transaction rolled back): $error";
1184     }
1185   }
1186
1187   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1188   '';
1189
1190 }
1191
1192 =item check
1193
1194 Checks all fields to make sure this is a valid customer record.  If there is
1195 an error, returns the error, otherwise returns false.  Called by the insert
1196 and replace methods.
1197
1198 =cut
1199
1200 sub check {
1201   my $self = shift;
1202
1203   warn "$me check BEFORE: \n". $self->_dump
1204     if $DEBUG > 2;
1205
1206   my $error =
1207     $self->ut_numbern('custnum')
1208     || $self->ut_number('agentnum')
1209     || $self->ut_textn('agent_custid')
1210     || $self->ut_number('refnum')
1211     || $self->ut_name('last')
1212     || $self->ut_name('first')
1213     || $self->ut_snumbern('birthdate')
1214     || $self->ut_snumbern('signupdate')
1215     || $self->ut_textn('company')
1216     || $self->ut_text('address1')
1217     || $self->ut_textn('address2')
1218     || $self->ut_text('city')
1219     || $self->ut_textn('county')
1220     || $self->ut_textn('state')
1221     || $self->ut_country('country')
1222     || $self->ut_anything('comments')
1223     || $self->ut_numbern('referral_custnum')
1224     || $self->ut_textn('stateid')
1225     || $self->ut_textn('stateid_state')
1226     || $self->ut_textn('invoice_terms')
1227   ;
1228   #barf.  need message catalogs.  i18n.  etc.
1229   $error .= "Please select an advertising source."
1230     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1231   return $error if $error;
1232
1233   return "Unknown agent"
1234     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1235
1236   return "Unknown refnum"
1237     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1238
1239   return "Unknown referring custnum: ". $self->referral_custnum
1240     unless ! $self->referral_custnum 
1241            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1242
1243   if ( $self->ss eq '' ) {
1244     $self->ss('');
1245   } else {
1246     my $ss = $self->ss;
1247     $ss =~ s/\D//g;
1248     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1249       or return "Illegal social security number: ". $self->ss;
1250     $self->ss("$1-$2-$3");
1251   }
1252
1253
1254 # bad idea to disable, causes billing to fail because of no tax rates later
1255 #  unless ( $import ) {
1256     unless ( qsearch('cust_main_county', {
1257       'country' => $self->country,
1258       'state'   => '',
1259      } ) ) {
1260       return "Unknown state/county/country: ".
1261         $self->state. "/". $self->county. "/". $self->country
1262         unless qsearch('cust_main_county',{
1263           'state'   => $self->state,
1264           'county'  => $self->county,
1265           'country' => $self->country,
1266         } );
1267     }
1268 #  }
1269
1270   $error =
1271     $self->ut_phonen('daytime', $self->country)
1272     || $self->ut_phonen('night', $self->country)
1273     || $self->ut_phonen('fax', $self->country)
1274     || $self->ut_zip('zip', $self->country)
1275   ;
1276   return $error if $error;
1277
1278   if ( $conf->exists('cust_main-require_phone')
1279        && ! length($self->daytime) && ! length($self->night)
1280      ) {
1281
1282     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1283                           ? 'Day Phone'
1284                           : FS::Msgcat::_gettext('daytime');
1285     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1286                         ? 'Night Phone'
1287                         : FS::Msgcat::_gettext('night');
1288   
1289     return "$daytime_label or $night_label is required"
1290   
1291   }
1292
1293   my @addfields = qw(
1294     last first company address1 address2 city county state zip
1295     country daytime night fax
1296   );
1297
1298   if ( defined $self->dbdef_table->column('ship_last') ) {
1299     if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1300                        @addfields )
1301          && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
1302        )
1303     {
1304       my $error =
1305         $self->ut_name('ship_last')
1306         || $self->ut_name('ship_first')
1307         || $self->ut_textn('ship_company')
1308         || $self->ut_text('ship_address1')
1309         || $self->ut_textn('ship_address2')
1310         || $self->ut_text('ship_city')
1311         || $self->ut_textn('ship_county')
1312         || $self->ut_textn('ship_state')
1313         || $self->ut_country('ship_country')
1314       ;
1315       return $error if $error;
1316
1317       #false laziness with above
1318       unless ( qsearchs('cust_main_county', {
1319         'country' => $self->ship_country,
1320         'state'   => '',
1321        } ) ) {
1322         return "Unknown ship_state/ship_county/ship_country: ".
1323           $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1324           unless qsearch('cust_main_county',{
1325             'state'   => $self->ship_state,
1326             'county'  => $self->ship_county,
1327             'country' => $self->ship_country,
1328           } );
1329       }
1330       #eofalse
1331
1332       $error =
1333         $self->ut_phonen('ship_daytime', $self->ship_country)
1334         || $self->ut_phonen('ship_night', $self->ship_country)
1335         || $self->ut_phonen('ship_fax', $self->ship_country)
1336         || $self->ut_zip('ship_zip', $self->ship_country)
1337       ;
1338       return $error if $error;
1339
1340     } else { # ship_ info eq billing info, so don't store dup info in database
1341       $self->setfield("ship_$_", '')
1342         foreach qw( last first company address1 address2 city county state zip
1343                     country daytime night fax );
1344     }
1345   }
1346
1347   #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1348   #  or return "Illegal payby: ". $self->payby;
1349   #$self->payby($1);
1350   FS::payby->can_payby($self->table, $self->payby)
1351     or return "Illegal payby: ". $self->payby;
1352
1353   $error =    $self->ut_numbern('paystart_month')
1354            || $self->ut_numbern('paystart_year')
1355            || $self->ut_numbern('payissue')
1356            || $self->ut_textn('paytype')
1357   ;
1358   return $error if $error;
1359
1360   if ( $self->payip eq '' ) {
1361     $self->payip('');
1362   } else {
1363     $error = $self->ut_ip('payip');
1364     return $error if $error;
1365   }
1366
1367   # If it is encrypted and the private key is not availaible then we can't
1368   # check the credit card.
1369
1370   my $check_payinfo = 1;
1371
1372   if ($self->is_encrypted($self->payinfo)) {
1373     $check_payinfo = 0;
1374   }
1375
1376   if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1377
1378     my $payinfo = $self->payinfo;
1379     $payinfo =~ s/\D//g;
1380     $payinfo =~ /^(\d{13,16})$/
1381       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1382     $payinfo = $1;
1383     $self->payinfo($payinfo);
1384     validate($payinfo)
1385       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1386
1387     return gettext('unknown_card_type')
1388       if cardtype($self->payinfo) eq "Unknown";
1389
1390     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1391     if ( $ban ) {
1392       return 'Banned credit card: banned on '.
1393              time2str('%a %h %o at %r', $ban->_date).
1394              ' by '. $ban->otaker.
1395              ' (ban# '. $ban->bannum. ')';
1396     }
1397
1398     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1399       if ( cardtype($self->payinfo) eq 'American Express card' ) {
1400         $self->paycvv =~ /^(\d{4})$/
1401           or return "CVV2 (CID) for American Express cards is four digits.";
1402         $self->paycvv($1);
1403       } else {
1404         $self->paycvv =~ /^(\d{3})$/
1405           or return "CVV2 (CVC2/CID) is three digits.";
1406         $self->paycvv($1);
1407       }
1408     } else {
1409       $self->paycvv('');
1410     }
1411
1412     my $cardtype = cardtype($payinfo);
1413     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1414
1415       return "Start date or issue number is required for $cardtype cards"
1416         unless $self->paystart_month && $self->paystart_year or $self->payissue;
1417
1418       return "Start month must be between 1 and 12"
1419         if $self->paystart_month
1420            and $self->paystart_month < 1 || $self->paystart_month > 12;
1421
1422       return "Start year must be 1990 or later"
1423         if $self->paystart_year
1424            and $self->paystart_year < 1990;
1425
1426       return "Issue number must be beween 1 and 99"
1427         if $self->payissue
1428           and $self->payissue < 1 || $self->payissue > 99;
1429
1430     } else {
1431       $self->paystart_month('');
1432       $self->paystart_year('');
1433       $self->payissue('');
1434     }
1435
1436   } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1437
1438     my $payinfo = $self->payinfo;
1439     $payinfo =~ s/[^\d\@]//g;
1440     if ( $conf->exists('echeck-nonus') ) {
1441       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1442       $payinfo = "$1\@$2";
1443     } else {
1444       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1445       $payinfo = "$1\@$2";
1446     }
1447     $self->payinfo($payinfo);
1448     $self->paycvv('');
1449
1450     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1451     if ( $ban ) {
1452       return 'Banned ACH account: banned on '.
1453              time2str('%a %h %o at %r', $ban->_date).
1454              ' by '. $ban->otaker.
1455              ' (ban# '. $ban->bannum. ')';
1456     }
1457
1458   } elsif ( $self->payby eq 'LECB' ) {
1459
1460     my $payinfo = $self->payinfo;
1461     $payinfo =~ s/\D//g;
1462     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1463     $payinfo = $1;
1464     $self->payinfo($payinfo);
1465     $self->paycvv('');
1466
1467   } elsif ( $self->payby eq 'BILL' ) {
1468
1469     $error = $self->ut_textn('payinfo');
1470     return "Illegal P.O. number: ". $self->payinfo if $error;
1471     $self->paycvv('');
1472
1473   } elsif ( $self->payby eq 'COMP' ) {
1474
1475     my $curuser = $FS::CurrentUser::CurrentUser;
1476     if (    ! $self->custnum
1477          && ! $curuser->access_right('Complimentary customer')
1478        )
1479     {
1480       return "You are not permitted to create complimentary accounts."
1481     }
1482
1483     $error = $self->ut_textn('payinfo');
1484     return "Illegal comp account issuer: ". $self->payinfo if $error;
1485     $self->paycvv('');
1486
1487   } elsif ( $self->payby eq 'PREPAY' ) {
1488
1489     my $payinfo = $self->payinfo;
1490     $payinfo =~ s/\W//g; #anything else would just confuse things
1491     $self->payinfo($payinfo);
1492     $error = $self->ut_alpha('payinfo');
1493     return "Illegal prepayment identifier: ". $self->payinfo if $error;
1494     return "Unknown prepayment identifier"
1495       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1496     $self->paycvv('');
1497
1498   }
1499
1500   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1501     return "Expiration date required"
1502       unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1503     $self->paydate('');
1504   } else {
1505     my( $m, $y );
1506     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1507       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1508     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1509       ( $m, $y ) = ( $3, "20$2" );
1510     } else {
1511       return "Illegal expiration date: ". $self->paydate;
1512     }
1513     $self->paydate("$y-$m-01");
1514     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1515     return gettext('expired_card')
1516       if !$import
1517       && !$ignore_expired_card 
1518       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1519   }
1520
1521   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1522        ( ! $conf->exists('require_cardname')
1523          || $self->payby !~ /^(CARD|DCRD)$/  ) 
1524   ) {
1525     $self->payname( $self->first. " ". $self->getfield('last') );
1526   } else {
1527     $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1528       or return gettext('illegal_name'). " payname: ". $self->payname;
1529     $self->payname($1);
1530   }
1531
1532   foreach my $flag (qw( tax spool_cdr )) {
1533     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1534     $self->$flag($1);
1535   }
1536
1537   $self->otaker(getotaker) unless $self->otaker;
1538
1539   warn "$me check AFTER: \n". $self->_dump
1540     if $DEBUG > 2;
1541
1542   $self->SUPER::check;
1543 }
1544
1545 =item all_pkgs
1546
1547 Returns all packages (see L<FS::cust_pkg>) for this customer.
1548
1549 =cut
1550
1551 sub all_pkgs {
1552   my $self = shift;
1553
1554   return $self->num_pkgs unless wantarray;
1555
1556   my @cust_pkg = ();
1557   if ( $self->{'_pkgnum'} ) {
1558     @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1559   } else {
1560     @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1561   }
1562
1563   sort sort_packages @cust_pkg;
1564 }
1565
1566 =item cust_pkg
1567
1568 Synonym for B<all_pkgs>.
1569
1570 =cut
1571
1572 sub cust_pkg {
1573   shift->all_pkgs(@_);
1574 }
1575
1576 =item ncancelled_pkgs
1577
1578 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1579
1580 =cut
1581
1582 sub ncancelled_pkgs {
1583   my $self = shift;
1584
1585   return $self->num_ncancelled_pkgs unless wantarray;
1586
1587   my @cust_pkg = ();
1588   if ( $self->{'_pkgnum'} ) {
1589
1590     warn "$me ncancelled_pkgs: returning cached objects"
1591       if $DEBUG > 1;
1592
1593     @cust_pkg = grep { ! $_->getfield('cancel') }
1594                 values %{ $self->{'_pkgnum'}->cache };
1595
1596   } else {
1597
1598     warn "$me ncancelled_pkgs: searching for packages with custnum ".
1599          $self->custnum. "\n"
1600       if $DEBUG > 1;
1601
1602     @cust_pkg =
1603       qsearch( 'cust_pkg', {
1604                              'custnum' => $self->custnum,
1605                              'cancel'  => '',
1606                            });
1607     push @cust_pkg,
1608       qsearch( 'cust_pkg', {
1609                              'custnum' => $self->custnum,
1610                              'cancel'  => 0,
1611                            });
1612   }
1613
1614   sort sort_packages @cust_pkg;
1615
1616 }
1617
1618 # This should be generalized to use config options to determine order.
1619 sub sort_packages {
1620   if ( $a->get('cancel') and $b->get('cancel') ) {
1621     $a->pkgnum <=> $b->pkgnum;
1622   } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1623     return -1 if $b->get('cancel');
1624     return  1 if $a->get('cancel');
1625     return 0;
1626   } else {
1627     $a->pkgnum <=> $b->pkgnum;
1628   }
1629 }
1630
1631 =item suspended_pkgs
1632
1633 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1634
1635 =cut
1636
1637 sub suspended_pkgs {
1638   my $self = shift;
1639   grep { $_->susp } $self->ncancelled_pkgs;
1640 }
1641
1642 =item unflagged_suspended_pkgs
1643
1644 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1645 customer (thouse packages without the `manual_flag' set).
1646
1647 =cut
1648
1649 sub unflagged_suspended_pkgs {
1650   my $self = shift;
1651   return $self->suspended_pkgs
1652     unless dbdef->table('cust_pkg')->column('manual_flag');
1653   grep { ! $_->manual_flag } $self->suspended_pkgs;
1654 }
1655
1656 =item unsuspended_pkgs
1657
1658 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1659 this customer.
1660
1661 =cut
1662
1663 sub unsuspended_pkgs {
1664   my $self = shift;
1665   grep { ! $_->susp } $self->ncancelled_pkgs;
1666 }
1667
1668 =item num_cancelled_pkgs
1669
1670 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1671 customer.
1672
1673 =cut
1674
1675 sub num_cancelled_pkgs {
1676   shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1677 }
1678
1679 sub num_ncancelled_pkgs {
1680   shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1681 }
1682
1683 sub num_pkgs {
1684   my( $self, $sql ) = @_;
1685   $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1686   my $sth = dbh->prepare(
1687     "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1688   ) or die dbh->errstr;
1689   $sth->execute($self->custnum) or die $sth->errstr;
1690   $sth->fetchrow_arrayref->[0];
1691 }
1692
1693 =item unsuspend
1694
1695 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1696 and L<FS::cust_pkg>) for this customer.  Always returns a list: an empty list
1697 on success or a list of errors.
1698
1699 =cut
1700
1701 sub unsuspend {
1702   my $self = shift;
1703   grep { $_->unsuspend } $self->suspended_pkgs;
1704 }
1705
1706 =item suspend
1707
1708 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1709
1710 Returns a list: an empty list on success or a list of errors.
1711
1712 =cut
1713
1714 sub suspend {
1715   my $self = shift;
1716   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1717 }
1718
1719 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1720
1721 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1722 PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref instead
1723 of a list of pkgparts; the hashref has the following keys:
1724
1725 =over 4
1726
1727 =item pkgparts - listref of pkgparts
1728
1729 =item (other options are passed to the suspend method)
1730
1731 =back
1732
1733
1734 Returns a list: an empty list on success or a list of errors.
1735
1736 =cut
1737
1738 sub suspend_if_pkgpart {
1739   my $self = shift;
1740   my (@pkgparts, %opt);
1741   if (ref($_[0]) eq 'HASH'){
1742     @pkgparts = @{$_[0]{pkgparts}};
1743     %opt      = %{$_[0]};
1744   }else{
1745     @pkgparts = @_;
1746   }
1747   grep { $_->suspend(%opt) }
1748     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1749       $self->unsuspended_pkgs;
1750 }
1751
1752 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1753
1754 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1755 given PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref
1756 instead of a list of pkgparts; the hashref has the following keys:
1757
1758 =over 4
1759
1760 =item pkgparts - listref of pkgparts
1761
1762 =item (other options are passed to the suspend method)
1763
1764 =back
1765
1766 Returns a list: an empty list on success or a list of errors.
1767
1768 =cut
1769
1770 sub suspend_unless_pkgpart {
1771   my $self = shift;
1772   my (@pkgparts, %opt);
1773   if (ref($_[0]) eq 'HASH'){
1774     @pkgparts = @{$_[0]{pkgparts}};
1775     %opt      = %{$_[0]};
1776   }else{
1777     @pkgparts = @_;
1778   }
1779   grep { $_->suspend(%opt) }
1780     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1781       $self->unsuspended_pkgs;
1782 }
1783
1784 =item cancel [ OPTION => VALUE ... ]
1785
1786 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1787
1788 Available options are:
1789
1790 =over 4
1791
1792 =item quiet - can be set true to supress email cancellation notices.
1793
1794 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason.  The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
1795
1796 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1797
1798 =back
1799
1800 Always returns a list: an empty list on success or a list of errors.
1801
1802 =cut
1803
1804 sub cancel {
1805   my( $self, %opt ) = @_;
1806
1807   warn "$me cancel called on customer ". $self->custnum. " with options ".
1808        join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1809     if $DEBUG;
1810
1811   return ( 'access denied' )
1812     unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1813
1814   if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1815
1816     #should try decryption (we might have the private key)
1817     # and if not maybe queue a job for the server that does?
1818     return ( "Can't (yet) ban encrypted credit cards" )
1819       if $self->is_encrypted($self->payinfo);
1820
1821     my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1822     my $error = $ban->insert;
1823     return ( $error ) if $error;
1824
1825   }
1826
1827   my @pkgs = $self->ncancelled_pkgs;
1828
1829   warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1830        scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1831     if $DEBUG;
1832
1833   grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1834 }
1835
1836 sub _banned_pay_hashref {
1837   my $self = shift;
1838
1839   my %payby2ban = (
1840     'CARD' => 'CARD',
1841     'DCRD' => 'CARD',
1842     'CHEK' => 'CHEK',
1843     'DCHK' => 'CHEK'
1844   );
1845
1846   {
1847     'payby'   => $payby2ban{$self->payby},
1848     'payinfo' => md5_base64($self->payinfo),
1849     #don't ever *search* on reason! #'reason'  =>
1850   };
1851 }
1852
1853 =item notes
1854
1855 Returns all notes (see L<FS::cust_main_note>) for this customer.
1856
1857 =cut
1858
1859 sub notes {
1860   my $self = shift;
1861   #order by?
1862   qsearch( 'cust_main_note',
1863            { 'custnum' => $self->custnum },
1864            '',
1865            'ORDER BY _DATE DESC'
1866          );
1867 }
1868
1869 =item agent
1870
1871 Returns the agent (see L<FS::agent>) for this customer.
1872
1873 =cut
1874
1875 sub agent {
1876   my $self = shift;
1877   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1878 }
1879
1880 =item bill_and_collect 
1881
1882 Cancels and suspends any packages due, generates bills, applies payments and
1883 cred
1884
1885 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1886
1887 Options are passed as name-value pairs.  Currently available options are:
1888
1889 =over 4
1890
1891 =item time
1892
1893 Bills the customer as if it were that time.  Specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion functions.  For example:
1894
1895  use Date::Parse;
1896  ...
1897  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1898
1899 =item invoice_time
1900
1901 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices.  Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
1902
1903 =item check_freq
1904
1905 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1906
1907 =item resetup
1908
1909 If set true, re-charges setup fees.
1910
1911 =item debug
1912
1913 Debugging level.  Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1914
1915 =back
1916
1917 =cut
1918
1919 sub bill_and_collect {
1920   my( $self, %options ) = @_;
1921
1922   ###
1923   # cancel packages
1924   ###
1925
1926   #$^T not $options{time} because freeside-daily -d is for pre-printing invoices
1927   foreach my $cust_pkg (
1928     grep { $_->expire && $_->expire <= $^T } $self->ncancelled_pkgs
1929   ) {
1930     my $error = $cust_pkg->cancel;
1931     warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1932          " for custnum ". $self->custnum. ": $error"
1933       if $error;
1934   }
1935
1936   ###
1937   # suspend packages
1938   ###
1939
1940   #$^T not $options{time} because freeside-daily -d is for pre-printing invoices
1941   foreach my $cust_pkg (
1942     grep { (    $_->part_pkg->is_prepaid && $_->bill && $_->bill < $^T
1943              || $_->adjourn && $_->adjourn <= $^T
1944            )
1945            && ! $_->susp
1946          }
1947          $self->ncancelled_pkgs
1948   ) {
1949     my $error = $cust_pkg->suspend;
1950     warn "Error suspending package ". $cust_pkg->pkgnum.
1951          " for custnum ". $self->custnum. ": $error"
1952       if $error;
1953   }
1954
1955   ###
1956   # bill and collect
1957   ###
1958
1959   my $error = $self->bill( %options );
1960   warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
1961
1962   $self->apply_payments_and_credits;
1963
1964   $error = $self->collect( %options );
1965   warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
1966
1967 }
1968
1969 =item bill OPTIONS
1970
1971 Generates invoices (see L<FS::cust_bill>) for this customer.  Usually used in
1972 conjunction with the collect method by calling B<bill_and_collect>.
1973
1974 If there is an error, returns the error, otherwise returns false.
1975
1976 Options are passed as name-value pairs.  Currently available options are:
1977
1978 =over 4
1979
1980 =item resetup
1981
1982 If set true, re-charges setup fees.
1983
1984 =item time
1985
1986 Bills the customer as if it were that time.  Specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion functions.  For example:
1987
1988  use Date::Parse;
1989  ...
1990  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1991
1992 =item pkg_list
1993
1994 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
1995
1996  $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
1997
1998 =item invoice_time
1999
2000 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices.  Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
2001
2002 =back
2003
2004 =cut
2005
2006 sub bill {
2007   my( $self, %options ) = @_;
2008   return '' if $self->payby eq 'COMP';
2009   warn "$me bill customer ". $self->custnum. "\n"
2010     if $DEBUG;
2011
2012   my $time = $options{'time'} || time;
2013
2014   my $error;
2015
2016   #put below somehow?
2017   local $SIG{HUP} = 'IGNORE';
2018   local $SIG{INT} = 'IGNORE';
2019   local $SIG{QUIT} = 'IGNORE';
2020   local $SIG{TERM} = 'IGNORE';
2021   local $SIG{TSTP} = 'IGNORE';
2022   local $SIG{PIPE} = 'IGNORE';
2023
2024   my $oldAutoCommit = $FS::UID::AutoCommit;
2025   local $FS::UID::AutoCommit = 0;
2026   my $dbh = dbh;
2027
2028   $self->select_for_update; #mutex
2029
2030   #create a new invoice
2031   #(we'll remove it later if it doesn't actually need to be generated [contains
2032   # no line items] and we're inside a transaciton so nothing else will see it)
2033   my $cust_bill = new FS::cust_bill ( {
2034     'custnum' => $self->custnum,
2035     '_date'   => ( $options{'invoice_time'} || $time ),
2036     #'charged' => $charged,
2037     'charged' => 0,
2038   } );
2039   $error = $cust_bill->insert;
2040   if ( $error ) {
2041     $dbh->rollback if $oldAutoCommit;
2042     return "can't create invoice for customer #". $self->custnum. ": $error";
2043   }
2044   my $invnum = $cust_bill->invnum;
2045
2046   ###
2047   # find the packages which are due for billing, find out how much they are
2048   # & generate invoice database.
2049   ###
2050
2051   my( $total_setup, $total_recur ) = ( 0, 0 );
2052   my %tax;
2053   my @precommit_hooks = ();
2054
2055   foreach my $cust_pkg (
2056     qsearch('cust_pkg', { 'custnum' => $self->custnum } )
2057   ) {
2058
2059     #NO!! next if $cust_pkg->cancel;  
2060     next if $cust_pkg->getfield('cancel');  
2061
2062     warn "  bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2063
2064     #? to avoid use of uninitialized value errors... ?
2065     $cust_pkg->setfield('bill', '')
2066       unless defined($cust_pkg->bill);
2067  
2068     my $part_pkg = $cust_pkg->part_pkg;
2069
2070     my %hash = $cust_pkg->hash;
2071     my $old_cust_pkg = new FS::cust_pkg \%hash;
2072
2073     my @details = ();
2074
2075     ###
2076     # bill setup
2077     ###
2078
2079     my $setup = 0;
2080     if ( ! $cust_pkg->setup &&
2081          (
2082            ( $conf->exists('disable_setup_suspended_pkgs') &&
2083             ! $cust_pkg->getfield('susp')
2084           ) || ! $conf->exists('disable_setup_suspended_pkgs')
2085          )
2086       || $options{'resetup'}
2087     ) {
2088     
2089       warn "    bill setup\n" if $DEBUG > 1;
2090
2091       $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2092       if ( $@ ) {
2093         $dbh->rollback if $oldAutoCommit;
2094         return "$@ running calc_setup for $cust_pkg\n";
2095       }
2096
2097       $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
2098     }
2099
2100     ###
2101     # bill recurring fee
2102     ### 
2103
2104     my $recur = 0;
2105     my $sdate;
2106     if ( $part_pkg->getfield('freq') ne '0' &&
2107          ! $cust_pkg->getfield('susp') &&
2108          ( $cust_pkg->getfield('bill') || 0 ) <= $time
2109     ) {
2110
2111       # XXX should this be a package event?  probably.  events are called
2112       # at collection time at the moment, though...
2113       if ( $part_pkg->can('reset_usage') ) {
2114         warn "    resetting usage counters" if $DEBUG > 1;
2115         $part_pkg->reset_usage($cust_pkg);
2116       }
2117
2118       warn "    bill recur\n" if $DEBUG > 1;
2119
2120       # XXX shared with $recur_prog
2121       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2122
2123       #over two params!  lets at least switch to a hashref for the rest...
2124       my %param = ( 'precommit_hooks' => \@precommit_hooks, );
2125
2126       $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2127       if ( $@ ) {
2128         $dbh->rollback if $oldAutoCommit;
2129         return "$@ running calc_recur for $cust_pkg\n";
2130       }
2131
2132       #change this bit to use Date::Manip? CAREFUL with timezones (see
2133       # mailing list archive)
2134       my ($sec,$min,$hour,$mday,$mon,$year) =
2135         (localtime($sdate) )[0,1,2,3,4,5];
2136
2137       #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2138       # only for figuring next bill date, nothing else, so, reset $sdate again
2139       # here
2140       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2141       $cust_pkg->last_bill($sdate)
2142         if $cust_pkg->dbdef_table->column('last_bill');
2143
2144       if ( $part_pkg->freq =~ /^\d+$/ ) {
2145         $mon += $part_pkg->freq;
2146         until ( $mon < 12 ) { $mon -= 12; $year++; }
2147       } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2148         my $weeks = $1;
2149         $mday += $weeks * 7;
2150       } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2151         my $days = $1;
2152         $mday += $days;
2153       } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2154         my $hours = $1;
2155         $hour += $hours;
2156       } else {
2157         $dbh->rollback if $oldAutoCommit;
2158         return "unparsable frequency: ". $part_pkg->freq;
2159       }
2160       $cust_pkg->setfield('bill',
2161         timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2162     }
2163
2164     warn "\$setup is undefined" unless defined($setup);
2165     warn "\$recur is undefined" unless defined($recur);
2166     warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2167
2168     ###
2169     # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2170     ###
2171
2172     if ( $cust_pkg->modified ) {  # hmmm.. and if the options are modified?
2173
2174       warn "  package ". $cust_pkg->pkgnum. " modified; updating\n"
2175         if $DEBUG >1;
2176
2177       $error=$cust_pkg->replace($old_cust_pkg,
2178                                 options => { $cust_pkg->options },
2179                                );
2180       if ( $error ) { #just in case
2181         $dbh->rollback if $oldAutoCommit;
2182         return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2183       }
2184
2185       $setup = sprintf( "%.2f", $setup );
2186       $recur = sprintf( "%.2f", $recur );
2187       if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2188         $dbh->rollback if $oldAutoCommit;
2189         return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2190       }
2191       if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2192         $dbh->rollback if $oldAutoCommit;
2193         return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2194       }
2195
2196       if ( $setup != 0 || $recur != 0 ) {
2197
2198         warn "    charges (setup=$setup, recur=$recur); adding line items\n"
2199           if $DEBUG > 1;
2200         my $cust_bill_pkg = new FS::cust_bill_pkg ({
2201           'invnum'  => $invnum,
2202           'pkgnum'  => $cust_pkg->pkgnum,
2203           'setup'   => $setup,
2204           'recur'   => $recur,
2205           'sdate'   => $sdate,
2206           'edate'   => $cust_pkg->bill,
2207           'details' => \@details,
2208         });
2209         $error = $cust_bill_pkg->insert;
2210         if ( $error ) {
2211           $dbh->rollback if $oldAutoCommit;
2212           return "can't create invoice line item for invoice #$invnum: $error";
2213         }
2214         $total_setup += $setup;
2215         $total_recur += $recur;
2216
2217         ###
2218         # handle taxes
2219         ###
2220
2221         unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2222
2223           my $prefix = 
2224             ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2225             ? 'ship_'
2226             : '';
2227           my %taxhash = map { $_ => $self->get("$prefix$_") }
2228                             qw( state county country );
2229
2230           $taxhash{'taxclass'} = $part_pkg->taxclass;
2231
2232           my @taxes = qsearch( 'cust_main_county', \%taxhash );
2233
2234           unless ( @taxes ) {
2235             $taxhash{'taxclass'} = '';
2236             @taxes =  qsearch( 'cust_main_county', \%taxhash );
2237           }
2238
2239           #one more try at a whole-country tax rate
2240           unless ( @taxes ) {
2241             $taxhash{$_} = '' foreach qw( state county );
2242             @taxes =  qsearch( 'cust_main_county', \%taxhash );
2243           }
2244
2245           # maybe eliminate this entirely, along with all the 0% records
2246           unless ( @taxes ) {
2247             $dbh->rollback if $oldAutoCommit;
2248             return
2249               "fatal: can't find tax rate for state/county/country/taxclass ".
2250               join('/', ( map $self->get("$prefix$_"),
2251                               qw(state county country)
2252                         ),
2253                         $part_pkg->taxclass ). "\n";
2254           }
2255   
2256           foreach my $tax ( @taxes ) {
2257
2258             my $taxable_charged = 0;
2259             $taxable_charged += $setup
2260               unless $part_pkg->setuptax =~ /^Y$/i
2261                   || $tax->setuptax =~ /^Y$/i;
2262             $taxable_charged += $recur
2263               unless $part_pkg->recurtax =~ /^Y$/i
2264                   || $tax->recurtax =~ /^Y$/i;
2265             next unless $taxable_charged;
2266
2267             if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2268               #my ($mon,$year) = (localtime($sdate) )[4,5];
2269               my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2270               $mon++;
2271               my $freq = $part_pkg->freq || 1;
2272               if ( $freq !~ /(\d+)$/ ) {
2273                 $dbh->rollback if $oldAutoCommit;
2274                 return "daily/weekly package definitions not (yet?)".
2275                        " compatible with monthly tax exemptions";
2276               }
2277               my $taxable_per_month =
2278                 sprintf("%.2f", $taxable_charged / $freq );
2279
2280               #call the whole thing off if this customer has any old
2281               #exemption records...
2282               my @cust_tax_exempt =
2283                 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2284               if ( @cust_tax_exempt ) {
2285                 $dbh->rollback if $oldAutoCommit;
2286                 return
2287                   'this customer still has old-style tax exemption records; '.
2288                   'run bin/fs-migrate-cust_tax_exempt?';
2289               }
2290
2291               foreach my $which_month ( 1 .. $freq ) {
2292
2293                 #maintain the new exemption table now
2294                 my $sql = "
2295                   SELECT SUM(amount)
2296                     FROM cust_tax_exempt_pkg
2297                       LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2298                       LEFT JOIN cust_bill     USING ( invnum     )
2299                     WHERE custnum = ?
2300                       AND taxnum  = ?
2301                       AND year    = ?
2302                       AND month   = ?
2303                 ";
2304                 my $sth = dbh->prepare($sql) or do {
2305                   $dbh->rollback if $oldAutoCommit;
2306                   return "fatal: can't lookup exising exemption: ". dbh->errstr;
2307                 };
2308                 $sth->execute(
2309                   $self->custnum,
2310                   $tax->taxnum,
2311                   1900+$year,
2312                   $mon,
2313                 ) or do {
2314                   $dbh->rollback if $oldAutoCommit;
2315                   return "fatal: can't lookup exising exemption: ". dbh->errstr;
2316                 };
2317                 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2318                 
2319                 my $remaining_exemption =
2320                   $tax->exempt_amount - $existing_exemption;
2321                 if ( $remaining_exemption > 0 ) {
2322                   my $addl = $remaining_exemption > $taxable_per_month
2323                     ? $taxable_per_month
2324                     : $remaining_exemption;
2325                   $taxable_charged -= $addl;
2326
2327                   my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2328                     'billpkgnum' => $cust_bill_pkg->billpkgnum,
2329                     'taxnum'     => $tax->taxnum,
2330                     'year'       => 1900+$year,
2331                     'month'      => $mon,
2332                     'amount'     => sprintf("%.2f", $addl ),
2333                   } );
2334                   $error = $cust_tax_exempt_pkg->insert;
2335                   if ( $error ) {
2336                     $dbh->rollback if $oldAutoCommit;
2337                     return "fatal: can't insert cust_tax_exempt_pkg: $error";
2338                   }
2339                 } # if $remaining_exemption > 0
2340
2341                 #++
2342                 $mon++;
2343                 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2344                 until ( $mon < 13 ) { $mon -= 12; $year++; }
2345   
2346               } #foreach $which_month
2347   
2348             } #if $tax->exempt_amount
2349
2350             $taxable_charged = sprintf( "%.2f", $taxable_charged);
2351
2352             #$tax += $taxable_charged * $cust_main_county->tax / 100
2353             $tax{ $tax->taxname || 'Tax' } +=
2354               $taxable_charged * $tax->tax / 100
2355
2356           } #foreach my $tax ( @taxes )
2357
2358         } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2359
2360       } #if $setup != 0 || $recur != 0
2361       
2362     } #if $cust_pkg->modified
2363
2364   } #foreach my $cust_pkg
2365
2366   unless ( $cust_bill->cust_bill_pkg ) {
2367     $cust_bill->delete; #don't create an invoice w/o line items
2368
2369    # XXX this seems to be broken
2370    #( DBD::Pg::st execute failed: ERROR:  syntax error at or near "hcb" )
2371 #   # get rid of our fake history too, waste of unecessary space
2372 #    my $h_cleanup_query = q{
2373 #      DELETE FROM h_cust_bill hcb
2374 #       WHERE hcb.invnum = ?
2375 #      AND NOT EXISTS ( SELECT 1 FROM cust_bill cb where cb.invnum = hcb.invnum )
2376 #    };
2377 #    my $h_sth = $dbh->prepare($h_cleanup_query);
2378 #    $h_sth->execute($invnum);
2379
2380     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2381     return '';
2382   }
2383
2384   my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2385
2386   foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2387     my $tax = sprintf("%.2f", $tax{$taxname} );
2388     $charged = sprintf( "%.2f", $charged+$tax );
2389   
2390     my $cust_bill_pkg = new FS::cust_bill_pkg ({
2391       'invnum'   => $invnum,
2392       'pkgnum'   => 0,
2393       'setup'    => $tax,
2394       'recur'    => 0,
2395       'sdate'    => '',
2396       'edate'    => '',
2397       'itemdesc' => $taxname,
2398     });
2399     $error = $cust_bill_pkg->insert;
2400     if ( $error ) {
2401       $dbh->rollback if $oldAutoCommit;
2402       return "can't create invoice line item for invoice #$invnum: $error";
2403     }
2404     $total_setup += $tax;
2405
2406   }
2407
2408   $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2409   $error = $cust_bill->replace;
2410   if ( $error ) {
2411     $dbh->rollback if $oldAutoCommit;
2412     return "can't update charged for invoice #$invnum: $error";
2413   }
2414
2415   foreach my $hook ( @precommit_hooks ) { 
2416     eval {
2417       &{$hook}; #($self) ?
2418     };
2419     if ( $@ ) {
2420       $dbh->rollback if $oldAutoCommit;
2421       return "$@ running precommit hook $hook\n";
2422     }
2423   }
2424   
2425   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2426   ''; #no error
2427 }
2428
2429 =item collect OPTIONS
2430
2431 (Attempt to) collect money for this customer's outstanding invoices (see
2432 L<FS::cust_bill>).  Usually used after the bill method.
2433
2434 Actions are now triggered by billing events; see L<FS::part_event> and the
2435 billing events web interface.  Old-style invoice events (see
2436 L<FS::part_bill_event>) have been deprecated.
2437
2438 If there is an error, returns the error, otherwise returns false.
2439
2440 Options are passed as name-value pairs.
2441
2442 Currently available options are:
2443
2444 =over 4
2445
2446 =item invoice_time
2447
2448 Use this time when deciding when to print invoices and late notices on those invoices.  The default is now.  It is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion functions.
2449
2450 =item retry
2451
2452 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2453
2454 =item quiet
2455
2456 set true to surpress email card/ACH decline notices.
2457
2458 =item check_freq
2459
2460 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2461
2462 =item payby
2463
2464 allows for one time override of normal customer billing method
2465
2466 =item debug
2467
2468 Debugging level.  Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2469
2470
2471 =back
2472
2473 =cut
2474
2475 sub collect {
2476   my( $self, %options ) = @_;
2477   my $invoice_time = $options{'invoice_time'} || time;
2478
2479   #put below somehow?
2480   local $SIG{HUP} = 'IGNORE';
2481   local $SIG{INT} = 'IGNORE';
2482   local $SIG{QUIT} = 'IGNORE';
2483   local $SIG{TERM} = 'IGNORE';
2484   local $SIG{TSTP} = 'IGNORE';
2485   local $SIG{PIPE} = 'IGNORE';
2486
2487   my $oldAutoCommit = $FS::UID::AutoCommit;
2488   local $FS::UID::AutoCommit = 0;
2489   my $dbh = dbh;
2490
2491   $self->select_for_update; #mutex
2492
2493   if ( $DEBUG ) {
2494     my $balance = $self->balance;
2495     warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2496   }
2497
2498   if ( exists($options{'retry_card'}) ) {
2499     carp 'retry_card option passed to collect is deprecated; use retry';
2500     $options{'retry'} ||= $options{'retry_card'};
2501   }
2502   if ( exists($options{'retry'}) && $options{'retry'} ) {
2503     my $error = $self->retry_realtime;
2504     if ( $error ) {
2505       $dbh->rollback if $oldAutoCommit;
2506       return $error;
2507     }
2508   }
2509
2510   # false laziness w/pay_batch::import_results
2511
2512   my $due_cust_event = $self->due_cust_event(
2513     'debug'      => ( $options{'debug'} || 0 ),
2514     'time'       => $invoice_time,
2515     'check_freq' => $options{'check_freq'},
2516   );
2517   unless( ref($due_cust_event) ) {
2518     $dbh->rollback if $oldAutoCommit;
2519     return $due_cust_event;
2520   }
2521
2522   foreach my $cust_event ( @$due_cust_event ) {
2523
2524     #XXX lock event
2525     
2526     #re-eval event conditions (a previous event could have changed things)
2527     unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2528       #don't leave stray "new/locked" records around
2529       my $error = $cust_event->delete;
2530       if ( $error ) {
2531         #gah, even with transactions
2532         $dbh->commit if $oldAutoCommit; #well.
2533         return $error;
2534       }
2535       next;
2536     }
2537
2538     {
2539       local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2540       warn "  running cust_event ". $cust_event->eventnum. "\n"
2541         if $DEBUG > 1;
2542
2543       
2544       #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2545       if ( my $error = $cust_event->do_event() ) {
2546         #XXX wtf is this?  figure out a proper dealio with return value
2547         #from do_event
2548           # gah, even with transactions.
2549           $dbh->commit if $oldAutoCommit; #well.
2550           return $error;
2551         }
2552     }
2553
2554   }
2555
2556   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2557   '';
2558
2559 }
2560
2561 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2562
2563 Inserts database records for and returns an ordered listref of new events due
2564 for this customer, as FS::cust_event objects (see L<FS::cust_event>).  If no
2565 events are due, an empty listref is returned.  If there is an error, returns a
2566 scalar error message.
2567
2568 To actually run the events, call each event's test_condition method, and if
2569 still true, call the event's do_event method.
2570
2571 Options are passed as a hashref or as a list of name-value pairs.  Available
2572 options are:
2573
2574 =over 4
2575
2576 =item check_freq
2577
2578 Search only for events of this check frequency (how often events of this type are checked); currently "1d" (daily, the default) and "1m" (monthly) are recognized.
2579
2580 =item time
2581
2582 "Current time" for the events.
2583
2584 =item debug
2585
2586 Debugging level.  Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2587
2588 =item eventtable
2589
2590 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2591
2592 =item objects
2593
2594 Explicitly pass the objects to be tested (typically used with eventtable).
2595
2596 =back
2597
2598 =cut
2599
2600 sub due_cust_event {
2601   my $self = shift;
2602   my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2603
2604   #???
2605   #my $DEBUG = $opt{'debug'}
2606   local($DEBUG) = $opt{'debug'}
2607     if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2608
2609   warn "$me due_cust_event called with options ".
2610        join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2611     if $DEBUG;
2612
2613   $opt{'time'} ||= time;
2614
2615   local $SIG{HUP} = 'IGNORE';
2616   local $SIG{INT} = 'IGNORE';
2617   local $SIG{QUIT} = 'IGNORE';
2618   local $SIG{TERM} = 'IGNORE';
2619   local $SIG{TSTP} = 'IGNORE';
2620   local $SIG{PIPE} = 'IGNORE';
2621
2622   my $oldAutoCommit = $FS::UID::AutoCommit;
2623   local $FS::UID::AutoCommit = 0;
2624   my $dbh = dbh;
2625
2626   $self->select_for_update; #mutex
2627
2628   ###
2629   # 1: find possible events (initial search)
2630   ###
2631   
2632   my @cust_event = ();
2633
2634   my @eventtable = $opt{'eventtable'}
2635                      ? ( $opt{'eventtable'} )
2636                      : FS::part_event->eventtables_runorder;
2637
2638   foreach my $eventtable ( @eventtable ) {
2639
2640     my @objects;
2641     if ( $opt{'objects'} ) {
2642
2643       @objects = @{ $opt{'objects'} };
2644
2645     } else {
2646
2647       #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2648       @objects = ( $eventtable eq 'cust_main' )
2649                    ? ( $self )
2650                    : ( $self->$eventtable() );
2651
2652     }
2653
2654     my @e_cust_event = ();
2655
2656     my $cross = "CROSS JOIN $eventtable";
2657     $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2658       unless $eventtable eq 'cust_main';
2659
2660     foreach my $object ( @objects ) {
2661
2662       #this first search uses the condition_sql magic for optimization.
2663       #the more possible events we can eliminate in this step the better
2664
2665       my $cross_where = '';
2666       my $pkey = $object->primary_key;
2667       $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2668
2669       my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2670       my $extra_sql =
2671         FS::part_event_condition->where_conditions_sql( $eventtable,
2672                                                         'time'=>$opt{'time'}
2673                                                       );
2674       my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2675
2676       $extra_sql = "AND $extra_sql" if $extra_sql;
2677
2678       #here is the agent virtualization
2679       $extra_sql .= " AND (    part_event.agentnum IS NULL
2680                             OR part_event.agentnum = ". $self->agentnum. ' )';
2681
2682       $extra_sql .= " $order";
2683
2684       warn "searching for events for $eventtable ". $object->$pkey. "\n"
2685         if $opt{'debug'} > 2;
2686       my @part_event = qsearch( {
2687         'debug'     => ( $opt{'debug'} > 3 ? 1 : 0 ),
2688         'select'    => 'part_event.*',
2689         'table'     => 'part_event',
2690         'addl_from' => "$cross $join",
2691         'hashref'   => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2692                          'eventtable' => $eventtable,
2693                          'disabled'   => '',
2694                        },
2695         'extra_sql' => "AND $cross_where $extra_sql",
2696       } );
2697
2698       if ( $DEBUG > 2 ) {
2699         my $pkey = $object->primary_key;
2700         warn "      ". scalar(@part_event).
2701              " possible events found for $eventtable ". $object->$pkey(). "\n";
2702       }
2703
2704       push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2705
2706     }
2707
2708     warn "    ". scalar(@e_cust_event).
2709          " subtotal possible cust events found for $eventtable\n"
2710       if $DEBUG > 1;
2711
2712     push @cust_event, @e_cust_event;
2713
2714   }
2715
2716   warn "  ". scalar(@cust_event).
2717        " total possible cust events found in initial search\n"
2718     if $DEBUG; # > 1;
2719
2720   ##
2721   # 2: test conditions
2722   ##
2723   
2724   my %unsat = ();
2725
2726   @cust_event = grep $_->test_conditions( 'time'          => $opt{'time'},
2727                                           'stats_hashref' => \%unsat ),
2728                      @cust_event;
2729
2730   warn "  ". scalar(@cust_event). " cust events left satisfying conditions\n"
2731     if $DEBUG; # > 1;
2732
2733   warn "    invalid conditions not eliminated with condition_sql:\n".
2734        join('', map "      $_: ".$unsat{$_}."\n", keys %unsat )
2735     if $DEBUG; # > 1;
2736
2737   ##
2738   # 3: insert
2739   ##
2740
2741   foreach my $cust_event ( @cust_event ) {
2742
2743     my $error = $cust_event->insert();
2744     if ( $error ) {
2745       $dbh->rollback if $oldAutoCommit;
2746       return $error;
2747     }
2748                                        
2749   }
2750
2751   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2752
2753   ##
2754   # 4: return
2755   ##
2756
2757   warn "  returning events: ". Dumper(@cust_event). "\n"
2758     if $DEBUG > 2;
2759
2760   \@cust_event;
2761
2762 }
2763
2764 =item retry_realtime
2765
2766 Schedules realtime / batch  credit card / electronic check / LEC billing
2767 events for for retry.  Useful if card information has changed or manual
2768 retry is desired.  The 'collect' method must be called to actually retry
2769 the transaction.
2770
2771 Implementation details: For either this customer, or for each of this
2772 customer's open invoices, changes the status of the first "done" (with
2773 statustext error) realtime processing event to "failed".
2774
2775 =cut
2776
2777 sub retry_realtime {
2778   my $self = shift;
2779
2780   local $SIG{HUP} = 'IGNORE';
2781   local $SIG{INT} = 'IGNORE';
2782   local $SIG{QUIT} = 'IGNORE';
2783   local $SIG{TERM} = 'IGNORE';
2784   local $SIG{TSTP} = 'IGNORE';
2785   local $SIG{PIPE} = 'IGNORE';
2786
2787   my $oldAutoCommit = $FS::UID::AutoCommit;
2788   local $FS::UID::AutoCommit = 0;
2789   my $dbh = dbh;
2790
2791   #a little false laziness w/due_cust_event (not too bad, really)
2792
2793   my $join = FS::part_event_condition->join_conditions_sql;
2794   my $order = FS::part_event_condition->order_conditions_sql;
2795   my $mine = 
2796   '( '
2797    . join ( ' OR ' , map { 
2798     "( part_event.eventtable = " . dbh->quote($_) 
2799     . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
2800    } FS::part_event->eventtables)
2801    . ') ';
2802
2803   #here is the agent virtualization
2804   my $agent_virt = " (    part_event.agentnum IS NULL
2805                        OR part_event.agentnum = ". $self->agentnum. ' )';
2806
2807   #XXX this shouldn't be hardcoded, actions should declare it...
2808   my @realtime_events = qw(
2809     cust_bill_realtime_card
2810     cust_bill_realtime_check
2811     cust_bill_realtime_lec
2812     cust_bill_batch
2813   );
2814
2815   my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
2816                                                   @realtime_events
2817                                      ).
2818                           ' ) ';
2819
2820   my @cust_event = qsearchs({
2821     'table'     => 'cust_event',
2822     'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
2823     'hashref'   => { 'status' => 'done' },
2824     'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
2825                    " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
2826   });
2827
2828   my %seen_invnum = ();
2829   foreach my $cust_event (@cust_event) {
2830
2831     #max one for the customer, one for each open invoice
2832     my $cust_X = $cust_event->cust_X;
2833     next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
2834                           ? $cust_X->invnum
2835                           : 0
2836                         }++
2837          or $cust_event->part_event->eventtable eq 'cust_bill'
2838             && ! $cust_X->owed;
2839
2840     my $error = $cust_event->retry;
2841     if ( $error ) {
2842       $dbh->rollback if $oldAutoCommit;
2843       return "error scheduling event for retry: $error";
2844     }
2845
2846   }
2847
2848   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2849   '';
2850
2851 }
2852
2853 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2854
2855 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2856 via a Business::OnlinePayment realtime gateway.  See
2857 L<http://420.am/business-onlinepayment> for supported gateways.
2858
2859 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2860
2861 Available options are: I<description>, I<invnum>, I<quiet>
2862
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.
2866
2867 I<description> is a free-text field passed to the gateway.  It defaults to
2868 "Internet services".
2869
2870 If an I<invnum> is specified, this payment (if successful) is applied to the
2871 specified invoice.  If you don't specify an I<invnum> you might want to
2872 call the B<apply_payments> method.
2873
2874 I<quiet> can be set true to surpress email decline notices.
2875
2876 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2877
2878 =cut
2879
2880 sub realtime_bop {
2881   my( $self, $method, $amount, %options ) = @_;
2882   if ( $DEBUG ) {
2883     warn "$me realtime_bop: $method $amount\n";
2884     warn "  $_ => $options{$_}\n" foreach keys %options;
2885   }
2886
2887   $options{'description'} ||= 'Internet services';
2888
2889   eval "use Business::OnlinePayment";  
2890   die $@ if $@;
2891
2892   my $payinfo = exists($options{'payinfo'})
2893                   ? $options{'payinfo'}
2894                   : $self->payinfo;
2895
2896   my %method2payby = (
2897     'CC'     => 'CARD',
2898     'ECHECK' => 'CHEK',
2899     'LEC'    => 'LECB',
2900   );
2901
2902   ###
2903   # check for banned credit card/ACH
2904   ###
2905
2906   my $ban = qsearchs('banned_pay', {
2907     'payby'   => $method2payby{$method},
2908     'payinfo' => md5_base64($payinfo),
2909   } );
2910   return "Banned credit card" if $ban;
2911
2912   ###
2913   # select a gateway
2914   ###
2915
2916   my $taxclass = '';
2917   if ( $options{'invnum'} ) {
2918     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2919     die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2920     my @taxclasses =
2921       map  { $_->part_pkg->taxclass }
2922       grep { $_ }
2923       map  { $_->cust_pkg }
2924       $cust_bill->cust_bill_pkg;
2925     unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2926                                                            #different taxclasses
2927       $taxclass = $taxclasses[0];
2928     }
2929   }
2930
2931   #look for an agent gateway override first
2932   my $cardtype;
2933   if ( $method eq 'CC' ) {
2934     $cardtype = cardtype($payinfo);
2935   } elsif ( $method eq 'ECHECK' ) {
2936     $cardtype = 'ACH';
2937   } else {
2938     $cardtype = $method;
2939   }
2940
2941   my $override =
2942        qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2943                                            cardtype => $cardtype,
2944                                            taxclass => $taxclass,       } )
2945     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2946                                            cardtype => '',
2947                                            taxclass => $taxclass,       } )
2948     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2949                                            cardtype => $cardtype,
2950                                            taxclass => '',              } )
2951     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2952                                            cardtype => '',
2953                                            taxclass => '',              } );
2954
2955   my $payment_gateway = '';
2956   my( $processor, $login, $password, $action, @bop_options );
2957   if ( $override ) { #use a payment gateway override
2958
2959     $payment_gateway = $override->payment_gateway;
2960
2961     $processor   = $payment_gateway->gateway_module;
2962     $login       = $payment_gateway->gateway_username;
2963     $password    = $payment_gateway->gateway_password;
2964     $action      = $payment_gateway->gateway_action;
2965     @bop_options = $payment_gateway->options;
2966
2967   } else { #use the standard settings from the config
2968
2969     ( $processor, $login, $password, $action, @bop_options ) =
2970       $self->default_payment_gateway($method);
2971
2972   }
2973
2974   ###
2975   # massage data
2976   ###
2977
2978   my $address = exists($options{'address1'})
2979                     ? $options{'address1'}
2980                     : $self->address1;
2981   my $address2 = exists($options{'address2'})
2982                     ? $options{'address2'}
2983                     : $self->address2;
2984   $address .= ", ". $address2 if length($address2);
2985
2986   my $o_payname = exists($options{'payname'})
2987                     ? $options{'payname'}
2988                     : $self->payname;
2989   my($payname, $payfirst, $paylast);
2990   if ( $o_payname && $method ne 'ECHECK' ) {
2991     ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2992       or return "Illegal payname $payname";
2993     ($payfirst, $paylast) = ($1, $2);
2994   } else {
2995     $payfirst = $self->getfield('first');
2996     $paylast = $self->getfield('last');
2997     $payname =  "$payfirst $paylast";
2998   }
2999
3000   my @invoicing_list = $self->invoicing_list_emailonly;
3001   if ( $conf->exists('emailinvoiceautoalways')
3002        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3003        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3004     push @invoicing_list, $self->all_emails;
3005   }
3006
3007   my $email = ($conf->exists('business-onlinepayment-email-override'))
3008               ? $conf->config('business-onlinepayment-email-override')
3009               : $invoicing_list[0];
3010
3011   my %content = ();
3012
3013   my $payip = exists($options{'payip'})
3014                 ? $options{'payip'}
3015                 : $self->payip;
3016   $content{customer_ip} = $payip
3017     if length($payip);
3018
3019   $content{invoice_number} = $options{'invnum'}
3020     if exists($options{'invnum'}) && length($options{'invnum'});
3021
3022   my $paydate = '';
3023   if ( $method eq 'CC' ) { 
3024
3025     $content{card_number} = $payinfo;
3026     $paydate = exists($options{'paydate'})
3027                     ? $options{'paydate'}
3028                     : $self->paydate;
3029     $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3030     $content{expiration} = "$2/$1";
3031
3032     my $paycvv = exists($options{'paycvv'})
3033                    ? $options{'paycvv'}
3034                    : $self->paycvv;
3035     $content{cvv2} = $self->paycvv
3036       if length($paycvv);
3037
3038     my $paystart_month = exists($options{'paystart_month'})
3039                            ? $options{'paystart_month'}
3040                            : $self->paystart_month;
3041
3042     my $paystart_year  = exists($options{'paystart_year'})
3043                            ? $options{'paystart_year'}
3044                            : $self->paystart_year;
3045
3046     $content{card_start} = "$paystart_month/$paystart_year"
3047       if $paystart_month && $paystart_year;
3048
3049     my $payissue       = exists($options{'payissue'})
3050                            ? $options{'payissue'}
3051                            : $self->payissue;
3052     $content{issue_number} = $payissue if $payissue;
3053
3054     $content{recurring_billing} = 'YES'
3055       if qsearch('cust_pay', { 'custnum' => $self->custnum,
3056                                'payby'   => 'CARD',
3057                                'payinfo' => $payinfo,
3058                              } )
3059       || qsearch('cust_pay', { 'custnum' => $self->custnum,
3060                                'payby'   => 'CARD',
3061                                'paymask' => $self->mask_payinfo('CARD', $payinfo),
3062                              } );
3063
3064
3065   } elsif ( $method eq 'ECHECK' ) {
3066     ( $content{account_number}, $content{routing_code} ) =
3067       split('@', $payinfo);
3068     $content{bank_name} = $o_payname;
3069     $content{bank_state} = exists($options{'paystate'})
3070                              ? $options{'paystate'}
3071                              : $self->getfield('paystate');
3072     $content{account_type} = exists($options{'paytype'})
3073                                ? uc($options{'paytype'}) || 'CHECKING'
3074                                : uc($self->getfield('paytype')) || 'CHECKING';
3075     $content{account_name} = $payname;
3076     $content{customer_org} = $self->company ? 'B' : 'I';
3077     $content{state_id}       = exists($options{'stateid'})
3078                                  ? $options{'stateid'}
3079                                  : $self->getfield('stateid');
3080     $content{state_id_state} = exists($options{'stateid_state'})
3081                                  ? $options{'stateid_state'}
3082                                  : $self->getfield('stateid_state');
3083     $content{customer_ssn} = exists($options{'ss'})
3084                                ? $options{'ss'}
3085                                : $self->ss;
3086   } elsif ( $method eq 'LEC' ) {
3087     $content{phone} = $payinfo;
3088   }
3089
3090   ###
3091   # run transaction(s)
3092   ###
3093
3094   my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3095
3096   my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3097   $transaction->content(
3098     'type'           => $method,
3099     'login'          => $login,
3100     'password'       => $password,
3101     'action'         => $action1,
3102     'description'    => $options{'description'},
3103     'amount'         => $amount,
3104     #'invoice_number' => $options{'invnum'},
3105     'customer_id'    => $self->custnum,
3106     'last_name'      => $paylast,
3107     'first_name'     => $payfirst,
3108     'name'           => $payname,
3109     'address'        => $address,
3110     'city'           => ( exists($options{'city'})
3111                             ? $options{'city'}
3112                             : $self->city          ),
3113     'state'          => ( exists($options{'state'})
3114                             ? $options{'state'}
3115                             : $self->state          ),
3116     'zip'            => ( exists($options{'zip'})
3117                             ? $options{'zip'}
3118                             : $self->zip          ),
3119     'country'        => ( exists($options{'country'})
3120                             ? $options{'country'}
3121                             : $self->country          ),
3122     'referer'        => 'http://cleanwhisker.420.am/',
3123     'email'          => $email,
3124     'phone'          => $self->daytime || $self->night,
3125     %content, #after
3126   );
3127   $transaction->submit();
3128
3129   if ( $transaction->is_success() && $action2 ) {
3130     my $auth = $transaction->authorization;
3131     my $ordernum = $transaction->can('order_number')
3132                    ? $transaction->order_number
3133                    : '';
3134
3135     my $capture =
3136       new Business::OnlinePayment( $processor, @bop_options );
3137
3138     my %capture = (
3139       %content,
3140       type           => $method,
3141       action         => $action2,
3142       login          => $login,
3143       password       => $password,
3144       order_number   => $ordernum,
3145       amount         => $amount,
3146       authorization  => $auth,
3147       description    => $options{'description'},
3148     );
3149
3150     foreach my $field (qw( authorization_source_code returned_ACI
3151                            transaction_identifier validation_code           
3152                            transaction_sequence_num local_transaction_date    
3153                            local_transaction_time AVS_result_code          )) {
3154       $capture{$field} = $transaction->$field() if $transaction->can($field);
3155     }
3156
3157     $capture->content( %capture );
3158
3159     $capture->submit();
3160
3161     unless ( $capture->is_success ) {
3162       my $e = "Authorization successful but capture failed, custnum #".
3163               $self->custnum. ': '.  $capture->result_code.
3164               ": ". $capture->error_message;
3165       warn $e;
3166       return $e;
3167     }
3168
3169   }
3170
3171   ###
3172   # remove paycvv after initial transaction
3173   ###
3174
3175   #false laziness w/misc/process/payment.cgi - check both to make sure working
3176   # correctly
3177   if ( defined $self->dbdef_table->column('paycvv')
3178        && length($self->paycvv)
3179        && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3180   ) {
3181     my $error = $self->remove_cvv;
3182     if ( $error ) {
3183       warn "WARNING: error removing cvv: $error\n";
3184     }
3185   }
3186
3187   ###
3188   # result handling
3189   ###
3190
3191   if ( $transaction->is_success() ) {
3192
3193     my %method2payby = (
3194       'CC'     => 'CARD',
3195       'ECHECK' => 'CHEK',
3196       'LEC'    => 'LECB',
3197     );
3198
3199     my $paybatch = '';
3200     if ( $payment_gateway ) { # agent override
3201       $paybatch = $payment_gateway->gatewaynum. '-';
3202     }
3203
3204     $paybatch .= "$processor:". $transaction->authorization;
3205
3206     $paybatch .= ':'. $transaction->order_number
3207       if $transaction->can('order_number')
3208       && length($transaction->order_number);
3209
3210     my $cust_pay = new FS::cust_pay ( {
3211        'custnum'  => $self->custnum,
3212        'invnum'   => $options{'invnum'},
3213        'paid'     => $amount,
3214        '_date'     => '',
3215        'payby'    => $method2payby{$method},
3216        'payinfo'  => $payinfo,
3217        'paybatch' => $paybatch,
3218        'paydate'  => $paydate,
3219     } );
3220     $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3221
3222     my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3223
3224     if ( $error ) {
3225       $cust_pay->invnum(''); #try again with no specific invnum
3226       my $error2 = $cust_pay->insert( $options{'manual'} ?
3227                                       ( 'manual' => 1 ) : ()
3228                                     );
3229       if ( $error2 ) {
3230         # gah, even with transactions.
3231         my $e = 'WARNING: Card/ACH debited but database not updated - '.
3232                 "error inserting payment ($processor): $error2".
3233                 " (previously tried insert with invnum #$options{'invnum'}" .
3234                 ": $error )";
3235         warn $e;
3236         return $e;
3237       }
3238     }
3239     return ''; #no error
3240
3241   } else {
3242
3243     my $perror = "$processor error: ". $transaction->error_message;
3244
3245     unless ( $transaction->error_message ) {
3246
3247       my $t_response;
3248       if ( $transaction->can('response_page') ) {
3249         $t_response = {
3250                         'page'    => ( $transaction->can('response_page')
3251                                          ? $transaction->response_page
3252                                          : ''
3253                                      ),
3254                         'code'    => ( $transaction->can('response_code')
3255                                          ? $transaction->response_code
3256                                          : ''
3257                                      ),
3258                         'headers' => ( $transaction->can('response_headers')
3259                                          ? $transaction->response_headers
3260                                          : ''
3261                                      ),
3262                       };
3263       } else {
3264         $t_response .=
3265           "No additional debugging information available for $processor";
3266       }
3267
3268       $perror .= "No error_message returned from $processor -- ".
3269                  ( ref($t_response) ? Dumper($t_response) : $t_response );
3270
3271     }
3272
3273     if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3274          && $conf->exists('emaildecline')
3275          && grep { $_ ne 'POST' } $self->invoicing_list
3276          && ! grep { $transaction->error_message =~ /$_/ }
3277                    $conf->config('emaildecline-exclude')
3278     ) {
3279       my @templ = $conf->config('declinetemplate');
3280       my $template = new Text::Template (
3281         TYPE   => 'ARRAY',
3282         SOURCE => [ map "$_\n", @templ ],
3283       ) or return "($perror) can't create template: $Text::Template::ERROR";
3284       $template->compile()
3285         or return "($perror) can't compile template: $Text::Template::ERROR";
3286
3287       my $templ_hash = { error => $transaction->error_message };
3288
3289       my $error = send_email(
3290         'from'    => $conf->config('invoice_from'),
3291         'to'      => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3292         'subject' => 'Your payment could not be processed',
3293         'body'    => [ $template->fill_in(HASH => $templ_hash) ],
3294       );
3295
3296       $perror .= " (also received error sending decline notification: $error)"
3297         if $error;
3298
3299     }
3300   
3301     return $perror;
3302   }
3303
3304 }
3305
3306 =item default_payment_gateway
3307
3308 =cut
3309
3310 sub default_payment_gateway {
3311   my( $self, $method ) = @_;
3312
3313   die "Real-time processing not enabled\n"
3314     unless $conf->exists('business-onlinepayment');
3315
3316   #load up config
3317   my $bop_config = 'business-onlinepayment';
3318   $bop_config .= '-ach'
3319     if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
3320   my ( $processor, $login, $password, $action, @bop_options ) =
3321     $conf->config($bop_config);
3322   $action ||= 'normal authorization';
3323   pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3324   die "No real-time processor is enabled - ".
3325       "did you set the business-onlinepayment configuration value?\n"
3326     unless $processor;
3327
3328   ( $processor, $login, $password, $action, @bop_options )
3329 }
3330
3331 =item remove_cvv
3332
3333 Removes the I<paycvv> field from the database directly.
3334
3335 If there is an error, returns the error, otherwise returns false.
3336
3337 =cut
3338
3339 sub remove_cvv {
3340   my $self = shift;
3341   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3342     or return dbh->errstr;
3343   $sth->execute($self->custnum)
3344     or return $sth->errstr;
3345   $self->paycvv('');
3346   '';
3347 }
3348
3349 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3350
3351 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3352 via a Business::OnlinePayment realtime gateway.  See
3353 L<http://420.am/business-onlinepayment> for supported gateways.
3354
3355 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3356
3357 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3358
3359 Most gateways require a reference to an original payment transaction to refund,
3360 so you probably need to specify a I<paynum>.
3361
3362 I<amount> defaults to the original amount of the payment if not specified.
3363
3364 I<reason> specifies a reason for the refund.
3365
3366 I<paydate> specifies the expiration date for a credit card overriding the
3367 value from the customer record or the payment record. Specified as yyyy-mm-dd
3368
3369 Implementation note: If I<amount> is unspecified or equal to the amount of the
3370 orignal payment, first an attempt is made to "void" the transaction via
3371 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3372 the normal attempt is made to "refund" ("credit") the transaction via the
3373 gateway is attempted.
3374
3375 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3376 #I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
3377 #if set, will override the value from the customer record.
3378
3379 #If an I<invnum> is specified, this payment (if successful) is applied to the
3380 #specified invoice.  If you don't specify an I<invnum> you might want to
3381 #call the B<apply_payments> method.
3382
3383 =cut
3384
3385 #some false laziness w/realtime_bop, not enough to make it worth merging
3386 #but some useful small subs should be pulled out
3387 sub realtime_refund_bop {
3388   my( $self, $method, %options ) = @_;
3389   if ( $DEBUG ) {
3390     warn "$me realtime_refund_bop: $method refund\n";
3391     warn "  $_ => $options{$_}\n" foreach keys %options;
3392   }
3393
3394   eval "use Business::OnlinePayment";  
3395   die $@ if $@;
3396
3397   ###
3398   # look up the original payment and optionally a gateway for that payment
3399   ###
3400
3401   my $cust_pay = '';
3402   my $amount = $options{'amount'};
3403
3404   my( $processor, $login, $password, @bop_options ) ;
3405   my( $auth, $order_number ) = ( '', '', '' );
3406
3407   if ( $options{'paynum'} ) {
3408
3409     warn "  paynum: $options{paynum}\n" if $DEBUG > 1;
3410     $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3411       or return "Unknown paynum $options{'paynum'}";
3412     $amount ||= $cust_pay->paid;
3413
3414     $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3415       or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3416                 $cust_pay->paybatch;
3417     my $gatewaynum = '';
3418     ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3419
3420     if ( $gatewaynum ) { #gateway for the payment to be refunded
3421
3422       my $payment_gateway =
3423         qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3424       die "payment gateway $gatewaynum not found"
3425         unless $payment_gateway;
3426
3427       $processor   = $payment_gateway->gateway_module;
3428       $login       = $payment_gateway->gateway_username;
3429       $password    = $payment_gateway->gateway_password;
3430       @bop_options = $payment_gateway->options;
3431
3432     } else { #try the default gateway
3433
3434       my( $conf_processor, $unused_action );
3435       ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3436         $self->default_payment_gateway($method);
3437
3438       return "processor of payment $options{'paynum'} $processor does not".
3439              " match default processor $conf_processor"
3440         unless $processor eq $conf_processor;
3441
3442     }
3443
3444
3445   } else { # didn't specify a paynum, so look for agent gateway overrides
3446            # like a normal transaction 
3447
3448     my $cardtype;
3449     if ( $method eq 'CC' ) {
3450       $cardtype = cardtype($self->payinfo);
3451     } elsif ( $method eq 'ECHECK' ) {
3452       $cardtype = 'ACH';
3453     } else {
3454       $cardtype = $method;
3455     }
3456     my $override =
3457            qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3458                                                cardtype => $cardtype,
3459                                                taxclass => '',              } )
3460         || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3461                                                cardtype => '',
3462                                                taxclass => '',              } );
3463
3464     if ( $override ) { #use a payment gateway override
3465  
3466       my $payment_gateway = $override->payment_gateway;
3467
3468       $processor   = $payment_gateway->gateway_module;
3469       $login       = $payment_gateway->gateway_username;
3470       $password    = $payment_gateway->gateway_password;
3471       #$action      = $payment_gateway->gateway_action;
3472       @bop_options = $payment_gateway->options;
3473
3474     } else { #use the standard settings from the config
3475
3476       my $unused_action;
3477       ( $processor, $login, $password, $unused_action, @bop_options ) =
3478         $self->default_payment_gateway($method);
3479
3480     }
3481
3482   }
3483   return "neither amount nor paynum specified" unless $amount;
3484
3485   my %content = (
3486     'type'           => $method,
3487     'login'          => $login,
3488     'password'       => $password,
3489     'order_number'   => $order_number,
3490     'amount'         => $amount,
3491     'referer'        => 'http://cleanwhisker.420.am/',
3492   );
3493   $content{authorization} = $auth
3494     if length($auth); #echeck/ACH transactions have an order # but no auth
3495                       #(at least with authorize.net)
3496
3497   my $disable_void_after;
3498   if ($conf->exists('disable_void_after')
3499       && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3500     $disable_void_after = $1;
3501   }
3502
3503   #first try void if applicable
3504   if ( $cust_pay && $cust_pay->paid == $amount
3505     && (
3506       ( not defined($disable_void_after) )
3507       || ( time < ($cust_pay->_date + $disable_void_after ) )
3508     )
3509   ) {
3510     warn "  attempting void\n" if $DEBUG > 1;
3511     my $void = new Business::OnlinePayment( $processor, @bop_options );
3512     $void->content( 'action' => 'void', %content );
3513     $void->submit();
3514     if ( $void->is_success ) {
3515       my $error = $cust_pay->void($options{'reason'});
3516       if ( $error ) {
3517         # gah, even with transactions.
3518         my $e = 'WARNING: Card/ACH voided but database not updated - '.
3519                 "error voiding payment: $error";
3520         warn $e;
3521         return $e;
3522       }
3523       warn "  void successful\n" if $DEBUG > 1;
3524       return '';
3525     }
3526   }
3527
3528   warn "  void unsuccessful, trying refund\n"
3529     if $DEBUG > 1;
3530
3531   #massage data
3532   my $address = $self->address1;
3533   $address .= ", ". $self->address2 if $self->address2;
3534
3535   my($payname, $payfirst, $paylast);
3536   if ( $self->payname && $method ne 'ECHECK' ) {
3537     $payname = $self->payname;
3538     $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3539       or return "Illegal payname $payname";
3540     ($payfirst, $paylast) = ($1, $2);
3541   } else {
3542     $payfirst = $self->getfield('first');
3543     $paylast = $self->getfield('last');
3544     $payname =  "$payfirst $paylast";
3545   }
3546
3547   my @invoicing_list = $self->invoicing_list_emailonly;
3548   if ( $conf->exists('emailinvoiceautoalways')
3549        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3550        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3551     push @invoicing_list, $self->all_emails;
3552   }
3553
3554   my $email = ($conf->exists('business-onlinepayment-email-override'))
3555               ? $conf->config('business-onlinepayment-email-override')
3556               : $invoicing_list[0];
3557
3558   my $payip = exists($options{'payip'})
3559                 ? $options{'payip'}
3560                 : $self->payip;
3561   $content{customer_ip} = $payip
3562     if length($payip);
3563
3564   my $payinfo = '';
3565   if ( $method eq 'CC' ) {
3566
3567     if ( $cust_pay ) {
3568       $content{card_number} = $payinfo = $cust_pay->payinfo;
3569       (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3570         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3571         ($content{expiration} = "$2/$1");  # where available
3572     } else {
3573       $content{card_number} = $payinfo = $self->payinfo;
3574       (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3575         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3576       $content{expiration} = "$2/$1";
3577     }
3578
3579   } elsif ( $method eq 'ECHECK' ) {
3580
3581     if ( $cust_pay ) {
3582       $payinfo = $cust_pay->payinfo;
3583     } else {
3584       $payinfo = $self->payinfo;
3585     } 
3586     ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3587     $content{bank_name} = $self->payname;
3588     $content{account_type} = 'CHECKING';
3589     $content{account_name} = $payname;
3590     $content{customer_org} = $self->company ? 'B' : 'I';
3591     $content{customer_ssn} = $self->ss;
3592   } elsif ( $method eq 'LEC' ) {
3593     $content{phone} = $payinfo = $self->payinfo;
3594   }
3595
3596   #then try refund
3597   my $refund = new Business::OnlinePayment( $processor, @bop_options );
3598   my %sub_content = $refund->content(
3599     'action'         => 'credit',
3600     'customer_id'    => $self->custnum,
3601     'last_name'      => $paylast,
3602     'first_name'     => $payfirst,
3603     'name'           => $payname,
3604     'address'        => $address,
3605     'city'           => $self->city,
3606     'state'          => $self->state,
3607     'zip'            => $self->zip,
3608     'country'        => $self->country,
3609     'email'          => $email,
3610     'phone'          => $self->daytime || $self->night,
3611     %content, #after
3612   );
3613   warn join('', map { "  $_ => $sub_content{$_}\n" } keys %sub_content )
3614     if $DEBUG > 1;
3615   $refund->submit();
3616
3617   return "$processor error: ". $refund->error_message
3618     unless $refund->is_success();
3619
3620   my %method2payby = (
3621     'CC'     => 'CARD',
3622     'ECHECK' => 'CHEK',
3623     'LEC'    => 'LECB',
3624   );
3625
3626   my $paybatch = "$processor:". $refund->authorization;
3627   $paybatch .= ':'. $refund->order_number
3628     if $refund->can('order_number') && $refund->order_number;
3629
3630   while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3631     my @cust_bill_pay = $cust_pay->cust_bill_pay;
3632     last unless @cust_bill_pay;
3633     my $cust_bill_pay = pop @cust_bill_pay;
3634     my $error = $cust_bill_pay->delete;
3635     last if $error;
3636   }
3637
3638   my $cust_refund = new FS::cust_refund ( {
3639     'custnum'  => $self->custnum,
3640     'paynum'   => $options{'paynum'},
3641     'refund'   => $amount,
3642     '_date'    => '',
3643     'payby'    => $method2payby{$method},
3644     'payinfo'  => $payinfo,
3645     'paybatch' => $paybatch,
3646     'reason'   => $options{'reason'} || 'card or ACH refund',
3647   } );
3648   my $error = $cust_refund->insert;
3649   if ( $error ) {
3650     $cust_refund->paynum(''); #try again with no specific paynum
3651     my $error2 = $cust_refund->insert;
3652     if ( $error2 ) {
3653       # gah, even with transactions.
3654       my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3655               "error inserting refund ($processor): $error2".
3656               " (previously tried insert with paynum #$options{'paynum'}" .
3657               ": $error )";
3658       warn $e;
3659       return $e;
3660     }
3661   }
3662
3663   ''; #no error
3664
3665 }
3666
3667 =item batch_card OPTION => VALUE...
3668
3669 Adds a payment for this invoice to the pending credit card batch (see
3670 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3671 runs the payment using a realtime gateway.
3672
3673 =cut
3674
3675 sub batch_card {
3676   my ($self, %options) = @_;
3677
3678   my $amount;
3679   if (exists($options{amount})) {
3680     $amount = $options{amount};
3681   }else{
3682     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3683   }
3684   return '' unless $amount > 0;
3685   
3686   my $invnum = delete $options{invnum};
3687   my $payby = $options{invnum} || $self->payby;  #dubious
3688
3689   if ($options{'realtime'}) {
3690     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3691                                 $amount,
3692                                 %options,
3693                               );
3694   }
3695
3696   my $oldAutoCommit = $FS::UID::AutoCommit;
3697   local $FS::UID::AutoCommit = 0;
3698   my $dbh = dbh;
3699
3700   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3701     or return "Cannot lock pay_batch: " . $dbh->errstr;
3702
3703   my %pay_batch = (
3704     'status' => 'O',
3705     'payby'  => FS::payby->payby2payment($payby),
3706   );
3707
3708   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3709
3710   unless ( $pay_batch ) {
3711     $pay_batch = new FS::pay_batch \%pay_batch;
3712     my $error = $pay_batch->insert;
3713     if ( $error ) {
3714       $dbh->rollback if $oldAutoCommit;
3715       die "error creating new batch: $error\n";
3716     }
3717   }
3718
3719   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3720       'batchnum' => $pay_batch->batchnum,
3721       'custnum'  => $self->custnum,
3722   } );
3723
3724   foreach (qw( address1 address2 city state zip country payby payinfo paydate
3725                payname )) {
3726     $options{$_} = '' unless exists($options{$_});
3727   }
3728
3729   my $cust_pay_batch = new FS::cust_pay_batch ( {
3730     'batchnum' => $pay_batch->batchnum,
3731     'invnum'   => $invnum || 0,                    # is there a better value?
3732                                                    # this field should be
3733                                                    # removed...
3734                                                    # cust_bill_pay_batch now
3735     'custnum'  => $self->custnum,
3736     'last'     => $self->getfield('last'),
3737     'first'    => $self->getfield('first'),
3738     'address1' => $options{address1} || $self->address1,
3739     'address2' => $options{address2} || $self->address2,
3740     'city'     => $options{city}     || $self->city,
3741     'state'    => $options{state}    || $self->state,
3742     'zip'      => $options{zip}      || $self->zip,
3743     'country'  => $options{country}  || $self->country,
3744     'payby'    => $options{payby}    || $self->payby,
3745     'payinfo'  => $options{payinfo}  || $self->payinfo,
3746     'exp'      => $options{paydate}  || $self->paydate,
3747     'payname'  => $options{payname}  || $self->payname,
3748     'amount'   => $amount,                         # consolidating
3749   } );
3750   
3751   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3752     if $old_cust_pay_batch;
3753
3754   my $error;
3755   if ($old_cust_pay_batch) {
3756     $error = $cust_pay_batch->replace($old_cust_pay_batch)
3757   } else {
3758     $error = $cust_pay_batch->insert;
3759   }
3760
3761   if ( $error ) {
3762     $dbh->rollback if $oldAutoCommit;
3763     die $error;
3764   }
3765
3766   my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
3767   foreach my $cust_bill ($self->open_cust_bill) {
3768     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3769     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3770       'invnum' => $cust_bill->invnum,
3771       'paybatchnum' => $cust_pay_batch->paybatchnum,
3772       'amount' => $cust_bill->owed,
3773       '_date' => time,
3774     };
3775     if ($unapplied >= $cust_bill_pay_batch->amount){
3776       $unapplied -= $cust_bill_pay_batch->amount;
3777       next;
3778     }else{
3779       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
3780                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
3781     }
3782     $error = $cust_bill_pay_batch->insert;
3783     if ( $error ) {
3784       $dbh->rollback if $oldAutoCommit;
3785       die $error;
3786     }
3787   }
3788
3789   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3790   '';
3791 }
3792
3793 =item total_owed
3794
3795 Returns the total owed for this customer on all invoices
3796 (see L<FS::cust_bill/owed>).
3797
3798 =cut
3799
3800 sub total_owed {
3801   my $self = shift;
3802   $self->total_owed_date(2145859200); #12/31/2037
3803 }
3804
3805 =item total_owed_date TIME
3806
3807 Returns the total owed for this customer on all invoices with date earlier than
3808 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
3809 see L<Time::Local> and L<Date::Parse> for conversion functions.
3810
3811 =cut
3812
3813 sub total_owed_date {
3814   my $self = shift;
3815   my $time = shift;
3816   my $total_bill = 0;
3817   foreach my $cust_bill (
3818     grep { $_->_date <= $time }
3819       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3820   ) {
3821     $total_bill += $cust_bill->owed;
3822   }
3823   sprintf( "%.2f", $total_bill );
3824 }
3825
3826 =item apply_payments_and_credits
3827
3828 Applies unapplied payments and credits.
3829
3830 In most cases, this new method should be used in place of sequential
3831 apply_payments and apply_credits methods.
3832
3833 If there is an error, returns the error, otherwise returns false.
3834
3835 =cut
3836
3837 sub apply_payments_and_credits {
3838   my $self = shift;
3839
3840   local $SIG{HUP} = 'IGNORE';
3841   local $SIG{INT} = 'IGNORE';
3842   local $SIG{QUIT} = 'IGNORE';
3843   local $SIG{TERM} = 'IGNORE';
3844   local $SIG{TSTP} = 'IGNORE';
3845   local $SIG{PIPE} = 'IGNORE';
3846
3847   my $oldAutoCommit = $FS::UID::AutoCommit;
3848   local $FS::UID::AutoCommit = 0;
3849   my $dbh = dbh;
3850
3851   $self->select_for_update; #mutex
3852
3853   foreach my $cust_bill ( $self->open_cust_bill ) {
3854     my $error = $cust_bill->apply_payments_and_credits;
3855     if ( $error ) {
3856       $dbh->rollback if $oldAutoCommit;
3857       return "Error applying: $error";
3858     }
3859   }
3860
3861   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3862   ''; #no error
3863
3864 }
3865
3866 =item apply_credits OPTION => VALUE ...
3867
3868 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3869 to outstanding invoice balances in chronological order (or reverse
3870 chronological order if the I<order> option is set to B<newest>) and returns the
3871 value of any remaining unapplied credits available for refund (see
3872 L<FS::cust_refund>).
3873
3874 Dies if there is an error.
3875
3876 =cut
3877
3878 sub apply_credits {
3879   my $self = shift;
3880   my %opt = @_;
3881
3882   local $SIG{HUP} = 'IGNORE';
3883   local $SIG{INT} = 'IGNORE';
3884   local $SIG{QUIT} = 'IGNORE';
3885   local $SIG{TERM} = 'IGNORE';
3886   local $SIG{TSTP} = 'IGNORE';
3887   local $SIG{PIPE} = 'IGNORE';
3888
3889   my $oldAutoCommit = $FS::UID::AutoCommit;
3890   local $FS::UID::AutoCommit = 0;
3891   my $dbh = dbh;
3892
3893   $self->select_for_update; #mutex
3894
3895   unless ( $self->total_credited ) {
3896     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3897     return 0;
3898   }
3899
3900   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3901       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3902
3903   my @invoices = $self->open_cust_bill;
3904   @invoices = sort { $b->_date <=> $a->_date } @invoices
3905     if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3906
3907   my $credit;
3908   foreach my $cust_bill ( @invoices ) {
3909     my $amount;
3910
3911     if ( !defined($credit) || $credit->credited == 0) {
3912       $credit = pop @credits or last;
3913     }
3914
3915     if ($cust_bill->owed >= $credit->credited) {
3916       $amount=$credit->credited;
3917     }else{
3918       $amount=$cust_bill->owed;
3919     }
3920     
3921     my $cust_credit_bill = new FS::cust_credit_bill ( {
3922       'crednum' => $credit->crednum,
3923       'invnum'  => $cust_bill->invnum,
3924       'amount'  => $amount,
3925     } );
3926     my $error = $cust_credit_bill->insert;
3927     if ( $error ) {
3928       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3929       die $error;
3930     }
3931     
3932     redo if ($cust_bill->owed > 0);
3933
3934   }
3935
3936   my $total_credited = $self->total_credited;
3937
3938   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3939
3940   return $total_credited;
3941 }
3942
3943 =item apply_payments
3944
3945 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3946 to outstanding invoice balances in chronological order.
3947
3948  #and returns the value of any remaining unapplied payments.
3949
3950 Dies if there is an error.
3951
3952 =cut
3953
3954 sub apply_payments {
3955   my $self = shift;
3956
3957   local $SIG{HUP} = 'IGNORE';
3958   local $SIG{INT} = 'IGNORE';
3959   local $SIG{QUIT} = 'IGNORE';
3960   local $SIG{TERM} = 'IGNORE';
3961   local $SIG{TSTP} = 'IGNORE';
3962   local $SIG{PIPE} = 'IGNORE';
3963
3964   my $oldAutoCommit = $FS::UID::AutoCommit;
3965   local $FS::UID::AutoCommit = 0;
3966   my $dbh = dbh;
3967
3968   $self->select_for_update; #mutex
3969
3970   #return 0 unless
3971
3972   my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3973       qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3974
3975   my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3976       qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3977
3978   my $payment;
3979
3980   foreach my $cust_bill ( @invoices ) {
3981     my $amount;
3982
3983     if ( !defined($payment) || $payment->unapplied == 0 ) {
3984       $payment = pop @payments or last;
3985     }
3986
3987     if ( $cust_bill->owed >= $payment->unapplied ) {
3988       $amount = $payment->unapplied;
3989     } else {
3990       $amount = $cust_bill->owed;
3991     }
3992
3993     my $cust_bill_pay = new FS::cust_bill_pay ( {
3994       'paynum' => $payment->paynum,
3995       'invnum' => $cust_bill->invnum,
3996       'amount' => $amount,
3997     } );
3998     my $error = $cust_bill_pay->insert;
3999     if ( $error ) {
4000       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4001       die $error;
4002     }
4003
4004     redo if ( $cust_bill->owed > 0);
4005
4006   }
4007
4008   my $total_unapplied_payments = $self->total_unapplied_payments;
4009
4010   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4011
4012   return $total_unapplied_payments;
4013 }
4014
4015 =item total_credited
4016
4017 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4018 customer.  See L<FS::cust_credit/credited>.
4019
4020 =cut
4021
4022 sub total_credited {
4023   my $self = shift;
4024   my $total_credit = 0;
4025   foreach my $cust_credit ( qsearch('cust_credit', {
4026     'custnum' => $self->custnum,
4027   } ) ) {
4028     $total_credit += $cust_credit->credited;
4029   }
4030   sprintf( "%.2f", $total_credit );
4031 }
4032
4033 =item total_unapplied_payments
4034
4035 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4036 See L<FS::cust_pay/unapplied>.
4037
4038 =cut
4039
4040 sub total_unapplied_payments {
4041   my $self = shift;
4042   my $total_unapplied = 0;
4043   foreach my $cust_pay ( qsearch('cust_pay', {
4044     'custnum' => $self->custnum,
4045   } ) ) {
4046     $total_unapplied += $cust_pay->unapplied;
4047   }
4048   sprintf( "%.2f", $total_unapplied );
4049 }
4050
4051 =item total_unapplied_refunds
4052
4053 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4054 customer.  See L<FS::cust_refund/unapplied>.
4055
4056 =cut
4057
4058 sub total_unapplied_refunds {
4059   my $self = shift;
4060   my $total_unapplied = 0;
4061   foreach my $cust_refund ( qsearch('cust_refund', {
4062     'custnum' => $self->custnum,
4063   } ) ) {
4064     $total_unapplied += $cust_refund->unapplied;
4065   }
4066   sprintf( "%.2f", $total_unapplied );
4067 }
4068
4069 =item balance
4070
4071 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4072 total_credited minus total_unapplied_payments).
4073
4074 =cut
4075
4076 sub balance {
4077   my $self = shift;
4078   sprintf( "%.2f",
4079       $self->total_owed
4080     + $self->total_unapplied_refunds
4081     - $self->total_credited
4082     - $self->total_unapplied_payments
4083   );
4084 }
4085
4086 =item balance_date TIME
4087
4088 Returns the balance for this customer, only considering invoices with date
4089 earlier than TIME (total_owed_date minus total_credited minus
4090 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
4091 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
4092 functions.
4093
4094 =cut
4095
4096 sub balance_date {
4097   my $self = shift;
4098   my $time = shift;
4099   sprintf( "%.2f",
4100         $self->total_owed_date($time)
4101       + $self->total_unapplied_refunds
4102       - $self->total_credited
4103       - $self->total_unapplied_payments
4104   );
4105 }
4106
4107 =item in_transit_payments
4108
4109 Returns the total of requests for payments for this customer pending in 
4110 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
4111
4112 =cut
4113
4114 sub in_transit_payments {
4115   my $self = shift;
4116   my $in_transit_payments = 0;
4117   foreach my $pay_batch ( qsearch('pay_batch', {
4118     'status' => 'I',
4119   } ) ) {
4120     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4121       'batchnum' => $pay_batch->batchnum,
4122       'custnum' => $self->custnum,
4123     } ) ) {
4124       $in_transit_payments += $cust_pay_batch->amount;
4125     }
4126   }
4127   sprintf( "%.2f", $in_transit_payments );
4128 }
4129
4130 =item paydate_monthyear
4131
4132 Returns a two-element list consisting of the month and year of this customer's
4133 paydate (credit card expiration date for CARD customers)
4134
4135 =cut
4136
4137 sub paydate_monthyear {
4138   my $self = shift;
4139   if ( $self->paydate  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4140     ( $2, $1 );
4141   } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4142     ( $1, $3 );
4143   } else {
4144     ('', '');
4145   }
4146 }
4147
4148 =item invoicing_list [ ARRAYREF ]
4149
4150 If an arguement is given, sets these email addresses as invoice recipients
4151 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
4152 (except as warnings), so use check_invoicing_list first.
4153
4154 Returns a list of email addresses (with svcnum entries expanded).
4155
4156 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
4157 check it without disturbing anything by passing nothing.
4158
4159 This interface may change in the future.
4160
4161 =cut
4162
4163 sub invoicing_list {
4164   my( $self, $arrayref ) = @_;
4165
4166   if ( $arrayref ) {
4167     my @cust_main_invoice;
4168     if ( $self->custnum ) {
4169       @cust_main_invoice = 
4170         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4171     } else {
4172       @cust_main_invoice = ();
4173     }
4174     foreach my $cust_main_invoice ( @cust_main_invoice ) {
4175       #warn $cust_main_invoice->destnum;
4176       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4177         #warn $cust_main_invoice->destnum;
4178         my $error = $cust_main_invoice->delete;
4179         warn $error if $error;
4180       }
4181     }
4182     if ( $self->custnum ) {
4183       @cust_main_invoice = 
4184         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4185     } else {
4186       @cust_main_invoice = ();
4187     }
4188     my %seen = map { $_->address => 1 } @cust_main_invoice;
4189     foreach my $address ( @{$arrayref} ) {
4190       next if exists $seen{$address} && $seen{$address};
4191       $seen{$address} = 1;
4192       my $cust_main_invoice = new FS::cust_main_invoice ( {
4193         'custnum' => $self->custnum,
4194         'dest'    => $address,
4195       } );
4196       my $error = $cust_main_invoice->insert;
4197       warn $error if $error;
4198     }
4199   }
4200   
4201   if ( $self->custnum ) {
4202     map { $_->address }
4203       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4204   } else {
4205     ();
4206   }
4207
4208 }
4209
4210 =item check_invoicing_list ARRAYREF
4211
4212 Checks these arguements as valid input for the invoicing_list method.  If there
4213 is an error, returns the error, otherwise returns false.
4214
4215 =cut
4216
4217 sub check_invoicing_list {
4218   my( $self, $arrayref ) = @_;
4219
4220   foreach my $address ( @$arrayref ) {
4221
4222     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4223       return 'Can\'t add FAX invoice destination with a blank FAX number.';
4224     }
4225
4226     my $cust_main_invoice = new FS::cust_main_invoice ( {
4227       'custnum' => $self->custnum,
4228       'dest'    => $address,
4229     } );
4230     my $error = $self->custnum
4231                 ? $cust_main_invoice->check
4232                 : $cust_main_invoice->checkdest
4233     ;
4234     return $error if $error;
4235
4236   }
4237
4238   return "Email address required"
4239     if $conf->exists('cust_main-require_invoicing_list_email')
4240     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4241
4242   '';
4243 }
4244
4245 =item set_default_invoicing_list
4246
4247 Sets the invoicing list to all accounts associated with this customer,
4248 overwriting any previous invoicing list.
4249
4250 =cut
4251
4252 sub set_default_invoicing_list {
4253   my $self = shift;
4254   $self->invoicing_list($self->all_emails);
4255 }
4256
4257 =item all_emails
4258
4259 Returns the email addresses of all accounts provisioned for this customer.
4260
4261 =cut
4262
4263 sub all_emails {
4264   my $self = shift;
4265   my %list;
4266   foreach my $cust_pkg ( $self->all_pkgs ) {
4267     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4268     my @svc_acct =
4269       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4270         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4271           @cust_svc;
4272     $list{$_}=1 foreach map { $_->email } @svc_acct;
4273   }
4274   keys %list;
4275 }
4276
4277 =item invoicing_list_addpost
4278
4279 Adds postal invoicing to this customer.  If this customer is already configured
4280 to receive postal invoices, does nothing.
4281
4282 =cut
4283
4284 sub invoicing_list_addpost {
4285   my $self = shift;
4286   return if grep { $_ eq 'POST' } $self->invoicing_list;
4287   my @invoicing_list = $self->invoicing_list;
4288   push @invoicing_list, 'POST';
4289   $self->invoicing_list(\@invoicing_list);
4290 }
4291
4292 =item invoicing_list_emailonly
4293
4294 Returns the list of email invoice recipients (invoicing_list without non-email
4295 destinations such as POST and FAX).
4296
4297 =cut
4298
4299 sub invoicing_list_emailonly {
4300   my $self = shift;
4301   warn "$me invoicing_list_emailonly called"
4302     if $DEBUG;
4303   grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4304 }
4305
4306 =item invoicing_list_emailonly_scalar
4307
4308 Returns the list of email invoice recipients (invoicing_list without non-email
4309 destinations such as POST and FAX) as a comma-separated scalar.
4310
4311 =cut
4312
4313 sub invoicing_list_emailonly_scalar {
4314   my $self = shift;
4315   warn "$me invoicing_list_emailonly_scalar called"
4316     if $DEBUG;
4317   join(', ', $self->invoicing_list_emailonly);
4318 }
4319
4320 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4321
4322 Returns an array of customers referred by this customer (referral_custnum set
4323 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
4324 customers referred by customers referred by this customer and so on, inclusive.
4325 The default behavior is DEPTH 1 (no recursion).
4326
4327 =cut
4328
4329 sub referral_cust_main {
4330   my $self = shift;
4331   my $depth = @_ ? shift : 1;
4332   my $exclude = @_ ? shift : {};
4333
4334   my @cust_main =
4335     map { $exclude->{$_->custnum}++; $_; }
4336       grep { ! $exclude->{ $_->custnum } }
4337         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4338
4339   if ( $depth > 1 ) {
4340     push @cust_main,
4341       map { $_->referral_cust_main($depth-1, $exclude) }
4342         @cust_main;
4343   }
4344
4345   @cust_main;
4346 }
4347
4348 =item referral_cust_main_ncancelled
4349
4350 Same as referral_cust_main, except only returns customers with uncancelled
4351 packages.
4352
4353 =cut
4354
4355 sub referral_cust_main_ncancelled {
4356   my $self = shift;
4357   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4358 }
4359
4360 =item referral_cust_pkg [ DEPTH ]
4361
4362 Like referral_cust_main, except returns a flat list of all unsuspended (and
4363 uncancelled) packages for each customer.  The number of items in this list may
4364 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4365
4366 =cut
4367
4368 sub referral_cust_pkg {
4369   my $self = shift;
4370   my $depth = @_ ? shift : 1;
4371
4372   map { $_->unsuspended_pkgs }
4373     grep { $_->unsuspended_pkgs }
4374       $self->referral_cust_main($depth);
4375 }
4376
4377 =item referring_cust_main
4378
4379 Returns the single cust_main record for the customer who referred this customer
4380 (referral_custnum), or false.
4381
4382 =cut
4383
4384 sub referring_cust_main {
4385   my $self = shift;
4386   return '' unless $self->referral_custnum;
4387   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4388 }
4389
4390 =item credit AMOUNT, REASON
4391
4392 Applies a credit to this customer.  If there is an error, returns the error,
4393 otherwise returns false.
4394
4395 =cut
4396
4397 sub credit {
4398   my( $self, $amount, $reason ) = @_;
4399   my $cust_credit = new FS::cust_credit {
4400     'custnum' => $self->custnum,
4401     'amount'  => $amount,
4402     'reason'  => $reason,
4403   };
4404   $cust_credit->insert;
4405 }
4406
4407 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4408
4409 Creates a one-time charge for this customer.  If there is an error, returns
4410 the error, otherwise returns false.
4411
4412 =cut
4413
4414 sub charge {
4415   my $self = shift;
4416   my ( $amount, $pkg, $comment, $taxclass, $additional );
4417   if ( ref( $_[0] ) ) {
4418     $amount     = $_[0]->{amount};
4419     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4420     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
4421                                            : '$'. sprintf("%.2f",$amount);
4422     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4423     $additional = $_[0]->{additional};
4424   }else{
4425     $amount     = shift;
4426     $pkg        = @_ ? shift : 'One-time charge';
4427     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
4428     $taxclass   = @_ ? shift : '';
4429     $additional = [];
4430   }
4431
4432   local $SIG{HUP} = 'IGNORE';
4433   local $SIG{INT} = 'IGNORE';
4434   local $SIG{QUIT} = 'IGNORE';
4435   local $SIG{TERM} = 'IGNORE';
4436   local $SIG{TSTP} = 'IGNORE';
4437   local $SIG{PIPE} = 'IGNORE';
4438
4439   my $oldAutoCommit = $FS::UID::AutoCommit;
4440   local $FS::UID::AutoCommit = 0;
4441   my $dbh = dbh;
4442
4443   my $part_pkg = new FS::part_pkg ( {
4444     'pkg'      => $pkg,
4445     'comment'  => $comment,
4446     'plan'     => 'flat',
4447     'freq'     => 0,
4448     'disabled' => 'Y',
4449     'taxclass' => $taxclass,
4450   } );
4451
4452   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4453                         ( 0 .. @$additional - 1 )
4454                   ),
4455                   'additional_count' => scalar(@$additional),
4456                   'setup_fee' => $amount,
4457                 );
4458
4459   my $error = $part_pkg->insert( options => \%options );
4460   if ( $error ) {
4461     $dbh->rollback if $oldAutoCommit;
4462     return $error;
4463   }
4464
4465   my $pkgpart = $part_pkg->pkgpart;
4466   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4467   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4468     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4469     $error = $type_pkgs->insert;
4470     if ( $error ) {
4471       $dbh->rollback if $oldAutoCommit;
4472       return $error;
4473     }
4474   }
4475
4476   my $cust_pkg = new FS::cust_pkg ( {
4477     'custnum' => $self->custnum,
4478     'pkgpart' => $pkgpart,
4479   } );
4480
4481   $error = $cust_pkg->insert;
4482   if ( $error ) {
4483     $dbh->rollback if $oldAutoCommit;
4484     return $error;
4485   }
4486
4487   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4488   '';
4489
4490 }
4491
4492 =item cust_bill
4493
4494 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4495
4496 =cut
4497
4498 sub cust_bill {
4499   my $self = shift;
4500   sort { $a->_date <=> $b->_date }
4501     qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4502 }
4503
4504 =item open_cust_bill
4505
4506 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4507 customer.
4508
4509 =cut
4510
4511 sub open_cust_bill {
4512   my $self = shift;
4513   grep { $_->owed > 0 } $self->cust_bill;
4514 }
4515
4516 =item cust_credit
4517
4518 Returns all the credits (see L<FS::cust_credit>) for this customer.
4519
4520 =cut
4521
4522 sub cust_credit {
4523   my $self = shift;
4524   sort { $a->_date <=> $b->_date }
4525     qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4526 }
4527
4528 =item cust_pay
4529
4530 Returns all the payments (see L<FS::cust_pay>) for this customer.
4531
4532 =cut
4533
4534 sub cust_pay {
4535   my $self = shift;
4536   sort { $a->_date <=> $b->_date }
4537     qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4538 }
4539
4540 =item cust_pay_void
4541
4542 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4543
4544 =cut
4545
4546 sub cust_pay_void {
4547   my $self = shift;
4548   sort { $a->_date <=> $b->_date }
4549     qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4550 }
4551
4552 =item cust_pay_batch
4553
4554 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
4555
4556 =cut
4557
4558 sub cust_pay_batch {
4559   my $self = shift;
4560   sort { $a->_date <=> $b->_date }
4561     qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
4562 }
4563
4564 =item cust_refund
4565
4566 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4567
4568 =cut
4569
4570 sub cust_refund {
4571   my $self = shift;
4572   sort { $a->_date <=> $b->_date }
4573     qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4574 }
4575
4576 =item name
4577
4578 Returns a name string for this customer, either "Company (Last, First)" or
4579 "Last, First".
4580
4581 =cut
4582
4583 sub name {
4584   my $self = shift;
4585   my $name = $self->contact;
4586   $name = $self->company. " ($name)" if $self->company;
4587   $name;
4588 }
4589
4590 =item ship_name
4591
4592 Returns a name string for this (service/shipping) contact, either
4593 "Company (Last, First)" or "Last, First".
4594
4595 =cut
4596
4597 sub ship_name {
4598   my $self = shift;
4599   if ( $self->get('ship_last') ) { 
4600     my $name = $self->ship_contact;
4601     $name = $self->ship_company. " ($name)" if $self->ship_company;
4602     $name;
4603   } else {
4604     $self->name;
4605   }
4606 }
4607
4608 =item contact
4609
4610 Returns this customer's full (billing) contact name only, "Last, First"
4611
4612 =cut
4613
4614 sub contact {
4615   my $self = shift;
4616   $self->get('last'). ', '. $self->first;
4617 }
4618
4619 =item ship_contact
4620
4621 Returns this customer's full (shipping) contact name only, "Last, First"
4622
4623 =cut
4624
4625 sub ship_contact {
4626   my $self = shift;
4627   $self->get('ship_last')
4628     ? $self->get('ship_last'). ', '. $self->ship_first
4629     : $self->contact;
4630 }
4631
4632 =item country_full
4633
4634 Returns this customer's full country name
4635
4636 =cut
4637
4638 sub country_full {
4639   my $self = shift;
4640   code2country($self->country);
4641 }
4642
4643 =item cust_status
4644
4645 =item status
4646
4647 Returns a status string for this customer, currently:
4648
4649 =over 4
4650
4651 =item prospect - No packages have ever been ordered
4652
4653 =item active - One or more recurring packages is active
4654
4655 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4656
4657 =item suspended - All non-cancelled recurring packages are suspended
4658
4659 =item cancelled - All recurring packages are cancelled
4660
4661 =back
4662
4663 =cut
4664
4665 sub status { shift->cust_status(@_); }
4666
4667 sub cust_status {
4668   my $self = shift;
4669   for my $status (qw( prospect active inactive suspended cancelled )) {
4670     my $method = $status.'_sql';
4671     my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4672     my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4673     $sth->execute( ($self->custnum) x $numnum )
4674       or die "Error executing 'SELECT $sql': ". $sth->errstr;
4675     return $status if $sth->fetchrow_arrayref->[0];
4676   }
4677 }
4678
4679 =item ucfirst_cust_status
4680
4681 =item ucfirst_status
4682
4683 Returns the status with the first character capitalized.
4684
4685 =cut
4686
4687 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4688
4689 sub ucfirst_cust_status {
4690   my $self = shift;
4691   ucfirst($self->cust_status);
4692 }
4693
4694 =item statuscolor
4695
4696 Returns a hex triplet color string for this customer's status.
4697
4698 =cut
4699
4700 use vars qw(%statuscolor);
4701 tie my %statuscolor, 'Tie::IxHash',
4702   'prospect'  => '7e0079', #'000000', #black?  naw, purple
4703   'active'    => '00CC00', #green
4704   'inactive'  => '0000CC', #blue
4705   'suspended' => 'FF9900', #yellow
4706   'cancelled' => 'FF0000', #red
4707 ;
4708
4709 sub statuscolor { shift->cust_statuscolor(@_); }
4710
4711 sub cust_statuscolor {
4712   my $self = shift;
4713   $statuscolor{$self->cust_status};
4714 }
4715
4716 =item tickets
4717
4718 Returns an array of hashes representing the customer's RT tickets.
4719
4720 =cut
4721
4722 sub tickets {
4723   my $self = shift;
4724
4725   my $num = $conf->config('cust_main-max_tickets') || 10;
4726   my @tickets = ();
4727
4728   unless ( $conf->config('ticket_system-custom_priority_field') ) {
4729
4730     @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4731
4732   } else {
4733
4734     foreach my $priority (
4735       $conf->config('ticket_system-custom_priority_field-values'), ''
4736     ) {
4737       last if scalar(@tickets) >= $num;
4738       push @tickets, 
4739         @{ FS::TicketSystem->customer_tickets( $self->custnum,
4740                                                $num - scalar(@tickets),
4741                                                $priority,
4742                                              )
4743          };
4744     }
4745   }
4746   (@tickets);
4747 }
4748
4749 # Return services representing svc_accts in customer support packages
4750 sub support_services {
4751   my $self = shift;
4752   my %packages = map { $_ => 1 } $conf->config('support_packages');
4753
4754   grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4755     grep { $_->part_svc->svcdb eq 'svc_acct' }
4756     map { $_->cust_svc }
4757     grep { exists $packages{ $_->pkgpart } }
4758     $self->ncancelled_pkgs;
4759
4760 }
4761
4762 =back
4763
4764 =head1 CLASS METHODS
4765
4766 =over 4
4767
4768 =item statuses
4769
4770 Class method that returns the list of possible status strings for customers
4771 (see L<the status method|/status>).  For example:
4772
4773   @statuses = FS::cust_main->statuses();
4774
4775 =cut
4776
4777 sub statuses {
4778   #my $self = shift; #could be class...
4779   keys %statuscolor;
4780 }
4781
4782 =item prospect_sql
4783
4784 Returns an SQL expression identifying prospective cust_main records (customers
4785 with no packages ever ordered)
4786
4787 =cut
4788
4789 use vars qw($select_count_pkgs);
4790 $select_count_pkgs =
4791   "SELECT COUNT(*) FROM cust_pkg
4792     WHERE cust_pkg.custnum = cust_main.custnum";
4793
4794 sub select_count_pkgs_sql {
4795   $select_count_pkgs;
4796 }
4797
4798 sub prospect_sql { "
4799   0 = ( $select_count_pkgs )
4800 "; }
4801
4802 =item active_sql
4803
4804 Returns an SQL expression identifying active cust_main records (customers with
4805 no active recurring packages, but otherwise unsuspended/uncancelled).
4806
4807 =cut
4808
4809 sub active_sql { "
4810   0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
4811       )
4812 "; }
4813
4814 =item inactive_sql
4815
4816 Returns an SQL expression identifying inactive cust_main records (customers with
4817 active recurring packages).
4818
4819 =cut
4820
4821 sub inactive_sql { "
4822   0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4823   AND
4824   0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4825 "; }
4826
4827 =item susp_sql
4828 =item suspended_sql
4829
4830 Returns an SQL expression identifying suspended cust_main records.
4831
4832 =cut
4833
4834
4835 sub suspended_sql { susp_sql(@_); }
4836 sub susp_sql { "
4837     0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
4838     AND
4839     0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4840 "; }
4841
4842 =item cancel_sql
4843 =item cancelled_sql
4844
4845 Returns an SQL expression identifying cancelled cust_main records.
4846
4847 =cut
4848
4849 sub cancelled_sql { cancel_sql(@_); }
4850 sub cancel_sql {
4851
4852   my $recurring_sql = FS::cust_pkg->recurring_sql;
4853   #my $recurring_sql = "
4854   #  '0' != ( select freq from part_pkg
4855   #             where cust_pkg.pkgpart = part_pkg.pkgpart )
4856   #";
4857
4858   "
4859     0 < ( $select_count_pkgs )
4860     AND 0 = ( $select_count_pkgs AND $recurring_sql
4861                   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4862             )
4863   ";
4864 }
4865
4866 =item uncancel_sql
4867 =item uncancelled_sql
4868
4869 Returns an SQL expression identifying un-cancelled cust_main records.
4870
4871 =cut
4872
4873 sub uncancelled_sql { uncancel_sql(@_); }
4874 sub uncancel_sql { "
4875   ( 0 < ( $select_count_pkgs
4876                    AND ( cust_pkg.cancel IS NULL
4877                          OR cust_pkg.cancel = 0
4878                        )
4879         )
4880     OR 0 = ( $select_count_pkgs )
4881   )
4882 "; }
4883
4884 =item balance_sql
4885
4886 Returns an SQL fragment to retreive the balance.
4887
4888 =cut
4889
4890 sub balance_sql { "
4891     COALESCE( ( SELECT SUM(charged) FROM cust_bill
4892                   WHERE cust_bill.custnum   = cust_main.custnum ), 0)
4893   - COALESCE( ( SELECT SUM(paid)    FROM cust_pay
4894                   WHERE cust_pay.custnum    = cust_main.custnum ), 0)
4895   - COALESCE( ( SELECT SUM(amount)  FROM cust_credit
4896                   WHERE cust_credit.custnum = cust_main.custnum ), 0)
4897   + COALESCE( ( SELECT SUM(refund)  FROM cust_refund
4898                    WHERE cust_refund.custnum = cust_main.custnum ), 0)
4899 "; }
4900
4901 =item balance_date_sql TIME
4902
4903 Returns an SQL fragment to retreive the balance for this customer, only
4904 considering invoices with date earlier than TIME. (total_owed_date minus total_credited minus
4905 total_unapplied_payments).  TIME is specified as an SQL fragment or a numeric
4906 UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and
4907 L<Date::Parse> for conversion functions.
4908
4909 =cut
4910
4911 sub balance_date_sql {
4912   my( $class, $time ) = @_;
4913
4914   my $owed_sql         = FS::cust_bill->owed_sql;
4915   my $unapp_refund_sql = FS::cust_refund->unapplied_sql;
4916   #my $unapp_credit_sql = FS::cust_credit->unapplied_sql;
4917   my $unapp_credit_sql = FS::cust_credit->credited_sql;
4918   my $unapp_pay_sql    = FS::cust_pay->unapplied_sql;
4919
4920   "
4921       COALESCE( ( SELECT SUM($owed_sql) FROM cust_bill
4922                     WHERE cust_bill.custnum   = cust_main.custnum
4923                       AND cust_bill._date    <= $time             )
4924                 ,0
4925               )
4926     + COALESCE( ( SELECT SUM($unapp_refund_sql) FROM cust_refund
4927                     WHERE cust_refund.custnum = cust_main.custnum )
4928                 ,0
4929               )
4930     - COALESCE( ( SELECT SUM($unapp_credit_sql) FROM cust_credit
4931                     WHERE cust_credit.custnum = cust_main.custnum )
4932                 ,0
4933               )
4934     - COALESCE( ( SELECT SUM($unapp_pay_sql) FROM cust_pay
4935                     WHERE cust_pay.custnum = cust_main.custnum )
4936                 ,0
4937               )
4938
4939   ";
4940
4941 }
4942
4943 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
4944
4945 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
4946 records.  Currently, I<first>, I<last> and/or I<company> may be specified (the
4947 appropriate ship_ field is also searched).
4948
4949 Additional options are the same as FS::Record::qsearch
4950
4951 =cut
4952
4953 sub fuzzy_search {
4954   my( $self, $fuzzy, $hash, @opt) = @_;
4955   #$self
4956   $hash ||= {};
4957   my @cust_main = ();
4958
4959   check_and_rebuild_fuzzyfiles();
4960   foreach my $field ( keys %$fuzzy ) {
4961
4962     my $all = $self->all_X($field);
4963     next unless scalar(@$all);
4964
4965     my %match = ();
4966     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
4967
4968     my @fcust = ();
4969     foreach ( keys %match ) {
4970       push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
4971       push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
4972     }
4973     my %fsaw = ();
4974     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
4975   }
4976
4977   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
4978   my %saw = ();
4979   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
4980
4981   @cust_main;
4982
4983 }
4984
4985 =item masked FIELD
4986
4987 Returns a masked version of the named field
4988
4989 =cut
4990
4991 sub masked {
4992 my ($self,$field) = @_;
4993
4994 # Show last four
4995
4996 'x'x(length($self->getfield($field))-4).
4997   substr($self->getfield($field), (length($self->getfield($field))-4));
4998
4999 }
5000
5001 =back
5002
5003 =head1 SUBROUTINES
5004
5005 =over 4
5006
5007 =item smart_search OPTION => VALUE ...
5008
5009 Accepts the following options: I<search>, the string to search for.  The string
5010 will be searched for as a customer number, phone number, name or company name,
5011 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5012 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5013 skip fuzzy matching when an exact match is found.
5014
5015 Any additional options are treated as an additional qualifier on the search
5016 (i.e. I<agentnum>).
5017
5018 Returns a (possibly empty) array of FS::cust_main objects.
5019
5020 =cut
5021
5022 sub smart_search {
5023   my %options = @_;
5024
5025   #here is the agent virtualization
5026   my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5027
5028   my @cust_main = ();
5029
5030   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5031   my $search = delete $options{'search'};
5032   ( my $alphanum_search = $search ) =~ s/\W//g;
5033   
5034   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5035
5036     #false laziness w/Record::ut_phone
5037     my $phonen = "$1-$2-$3";
5038     $phonen .= " x$4" if $4;
5039
5040     push @cust_main, qsearch( {
5041       'table'   => 'cust_main',
5042       'hashref' => { %options },
5043       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5044                      ' ( '.
5045                          join(' OR ', map "$_ = '$phonen'",
5046                                           qw( daytime night fax
5047                                               ship_daytime ship_night ship_fax )
5048                              ).
5049                      ' ) '.
5050                      " AND $agentnums_sql", #agent virtualization
5051     } );
5052
5053     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5054       #try looking for matches with extensions unless one was specified
5055
5056       push @cust_main, qsearch( {
5057         'table'   => 'cust_main',
5058         'hashref' => { %options },
5059         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5060                        ' ( '.
5061                            join(' OR ', map "$_ LIKE '$phonen\%'",
5062                                             qw( daytime night
5063                                                 ship_daytime ship_night )
5064                                ).
5065                        ' ) '.
5066                        " AND $agentnums_sql", #agent virtualization
5067       } );
5068
5069     }
5070
5071   } elsif ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
5072
5073     push @cust_main, qsearch( {
5074       'table'     => 'cust_main',
5075       'hashref'   => { 'custnum' => $1, %options },
5076       'extra_sql' => " AND $agentnums_sql", #agent virtualization
5077     } );
5078
5079   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5080
5081     my($company, $last, $first) = ( $1, $2, $3 );
5082
5083     # "Company (Last, First)"
5084     #this is probably something a browser remembered,
5085     #so just do an exact search
5086
5087     foreach my $prefix ( '', 'ship_' ) {
5088       push @cust_main, qsearch( {
5089         'table'     => 'cust_main',
5090         'hashref'   => { $prefix.'first'   => $first,
5091                          $prefix.'last'    => $last,
5092                          $prefix.'company' => $company,
5093                          %options,
5094                        },
5095         'extra_sql' => " AND $agentnums_sql",
5096       } );
5097     }
5098
5099   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5100                                               # try (ship_){last,company}
5101
5102     my $value = lc($1);
5103
5104     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5105     # # full strings the browser remembers won't work
5106     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5107
5108     use Lingua::EN::NameParse;
5109     my $NameParse = new Lingua::EN::NameParse(
5110              auto_clean     => 1,
5111              allow_reversed => 1,
5112     );
5113
5114     my($last, $first) = ( '', '' );
5115     #maybe disable this too and just rely on NameParse?
5116     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5117     
5118       ($last, $first) = ( $1, $2 );
5119     
5120     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
5121     } elsif ( ! $NameParse->parse($value) ) {
5122
5123       my %name = $NameParse->components;
5124       $first = $name{'given_name_1'};
5125       $last  = $name{'surname_1'};
5126
5127     }
5128
5129     if ( $first && $last ) {
5130
5131       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5132
5133       #exact
5134       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5135       $sql .= "
5136         (     ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5137            OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5138         )";
5139
5140       push @cust_main, qsearch( {
5141         'table'     => 'cust_main',
5142         'hashref'   => \%options,
5143         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5144       } );
5145
5146       # or it just be something that was typed in... (try that in a sec)
5147
5148     }
5149
5150     my $q_value = dbh->quote($value);
5151
5152     #exact
5153     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5154     $sql .= " (    LOWER(last)         = $q_value
5155                 OR LOWER(company)      = $q_value
5156                 OR LOWER(ship_last)    = $q_value
5157                 OR LOWER(ship_company) = $q_value
5158               )";
5159
5160     push @cust_main, qsearch( {
5161       'table'     => 'cust_main',
5162       'hashref'   => \%options,
5163       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5164     } );
5165
5166     #no exact match, trying substring/fuzzy
5167     #always do substring & fuzzy (unless they're explicity config'ed off)
5168     #getting complaints searches are not returning enough
5169     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
5170
5171       #still some false laziness w/ search/cust_main.cgi
5172
5173       #substring
5174
5175       my @hashrefs = (
5176         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
5177         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5178       );
5179
5180       if ( $first && $last ) {
5181
5182         push @hashrefs,
5183           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
5184             'last'         => { op=>'ILIKE', value=>"%$last%" },
5185           },
5186           { 'ship_first'   => { op=>'ILIKE', value=>"%$first%" },
5187             'ship_last'    => { op=>'ILIKE', value=>"%$last%" },
5188           },
5189         ;
5190
5191       } else {
5192
5193         push @hashrefs,
5194           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
5195           { 'ship_last'    => { op=>'ILIKE', value=>"%$value%" }, },
5196         ;
5197       }
5198
5199       foreach my $hashref ( @hashrefs ) {
5200
5201         push @cust_main, qsearch( {
5202           'table'     => 'cust_main',
5203           'hashref'   => { %$hashref,
5204                            %options,
5205                          },
5206           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
5207         } );
5208
5209       }
5210
5211       #fuzzy
5212       my @fuzopts = (
5213         \%options,                #hashref
5214         '',                       #select
5215         " AND $agentnums_sql",    #extra_sql  #agent virtualization
5216       );
5217
5218       if ( $first && $last ) {
5219         push @cust_main, FS::cust_main->fuzzy_search(
5220           { 'last'   => $last,    #fuzzy hashref
5221             'first'  => $first }, #
5222           @fuzopts
5223         );
5224       }
5225       foreach my $field ( 'last', 'company' ) {
5226         push @cust_main,
5227           FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
5228       }
5229
5230     }
5231
5232     #eliminate duplicates
5233     my %saw = ();
5234     @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5235
5236   }
5237
5238   @cust_main;
5239
5240 }
5241
5242 =item check_and_rebuild_fuzzyfiles
5243
5244 =cut
5245
5246 use vars qw(@fuzzyfields);
5247 @fuzzyfields = ( 'last', 'first', 'company' );
5248
5249 sub check_and_rebuild_fuzzyfiles {
5250   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5251   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
5252 }
5253
5254 =item rebuild_fuzzyfiles
5255
5256 =cut
5257
5258 sub rebuild_fuzzyfiles {
5259
5260   use Fcntl qw(:flock);
5261
5262   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5263   mkdir $dir, 0700 unless -d $dir;
5264
5265   foreach my $fuzzy ( @fuzzyfields ) {
5266
5267     open(LOCK,">>$dir/cust_main.$fuzzy")
5268       or die "can't open $dir/cust_main.$fuzzy: $!";
5269     flock(LOCK,LOCK_EX)
5270       or die "can't lock $dir/cust_main.$fuzzy: $!";
5271
5272     open (CACHE,">$dir/cust_main.$fuzzy.tmp")
5273       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
5274
5275     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
5276       my $sth = dbh->prepare("SELECT $field FROM cust_main".
5277                              " WHERE $field != '' AND $field IS NOT NULL");
5278       $sth->execute or die $sth->errstr;
5279
5280       while ( my $row = $sth->fetchrow_arrayref ) {
5281         print CACHE $row->[0]. "\n";
5282       }
5283
5284     } 
5285
5286     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
5287   
5288     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
5289     close LOCK;
5290   }
5291
5292 }
5293
5294 =item all_X
5295
5296 =cut
5297
5298 sub all_X {
5299   my( $self, $field ) = @_;
5300   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5301   open(CACHE,"<$dir/cust_main.$field")
5302     or die "can't open $dir/cust_main.$field: $!";
5303   my @array = map { chomp; $_; } <CACHE>;
5304   close CACHE;
5305   \@array;
5306 }
5307
5308 =item append_fuzzyfiles LASTNAME COMPANY
5309
5310 =cut
5311
5312 sub append_fuzzyfiles {
5313   #my( $first, $last, $company ) = @_;
5314
5315   &check_and_rebuild_fuzzyfiles;
5316
5317   use Fcntl qw(:flock);
5318
5319   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5320
5321   foreach my $field (qw( first last company )) {
5322     my $value = shift;
5323
5324     if ( $value ) {
5325
5326       open(CACHE,">>$dir/cust_main.$field")
5327         or die "can't open $dir/cust_main.$field: $!";
5328       flock(CACHE,LOCK_EX)
5329         or die "can't lock $dir/cust_main.$field: $!";
5330
5331       print CACHE "$value\n";
5332
5333       flock(CACHE,LOCK_UN)
5334         or die "can't unlock $dir/cust_main.$field: $!";
5335       close CACHE;
5336     }
5337
5338   }
5339
5340   1;
5341 }
5342
5343 =item batch_import
5344
5345 =cut
5346
5347 sub batch_import {
5348   my $param = shift;
5349   #warn join('-',keys %$param);
5350   my $fh = $param->{filehandle};
5351   my $agentnum = $param->{agentnum};
5352
5353   my $refnum = $param->{refnum};
5354   my $pkgpart = $param->{pkgpart};
5355
5356   #my @fields = @{$param->{fields}};
5357   my $format = $param->{'format'};
5358   my @fields;
5359   my $payby;
5360   if ( $format eq 'simple' ) {
5361     @fields = qw( cust_pkg.setup dayphone first last
5362                   address1 address2 city state zip comments );
5363     $payby = 'BILL';
5364   } elsif ( $format eq 'extended' ) {
5365     @fields = qw( agent_custid refnum
5366                   last first address1 address2 city state zip country
5367                   daytime night
5368                   ship_last ship_first ship_address1 ship_address2
5369                   ship_city ship_state ship_zip ship_country
5370                   payinfo paycvv paydate
5371                   invoicing_list
5372                   cust_pkg.pkgpart
5373                   svc_acct.username svc_acct._password 
5374                 );
5375     $payby = 'BILL';
5376   } else {
5377     die "unknown format $format";
5378   }
5379
5380   eval "use Text::CSV_XS;";
5381   die $@ if $@;
5382
5383   my $csv = new Text::CSV_XS;
5384   #warn $csv;
5385   #warn $fh;
5386
5387   my $imported = 0;
5388   #my $columns;
5389
5390   local $SIG{HUP} = 'IGNORE';
5391   local $SIG{INT} = 'IGNORE';
5392   local $SIG{QUIT} = 'IGNORE';
5393   local $SIG{TERM} = 'IGNORE';
5394   local $SIG{TSTP} = 'IGNORE';
5395   local $SIG{PIPE} = 'IGNORE';
5396
5397   my $oldAutoCommit = $FS::UID::AutoCommit;
5398   local $FS::UID::AutoCommit = 0;
5399   my $dbh = dbh;
5400   
5401   #while ( $columns = $csv->getline($fh) ) {
5402   my $line;
5403   while ( defined($line=<$fh>) ) {
5404
5405     $csv->parse($line) or do {
5406       $dbh->rollback if $oldAutoCommit;
5407       return "can't parse: ". $csv->error_input();
5408     };
5409
5410     my @columns = $csv->fields();
5411     #warn join('-',@columns);
5412
5413     my %cust_main = (
5414       agentnum => $agentnum,
5415       refnum   => $refnum,
5416       country  => $conf->config('countrydefault') || 'US',
5417       payby    => $payby, #default
5418       paydate  => '12/2037', #default
5419     );
5420     my $billtime = time;
5421     my %cust_pkg = ( pkgpart => $pkgpart );
5422     my %svc_acct = ();
5423     foreach my $field ( @fields ) {
5424
5425       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
5426
5427         #$cust_pkg{$1} = str2time( shift @$columns );
5428         if ( $1 eq 'pkgpart' ) {
5429           $cust_pkg{$1} = shift @columns;
5430         } elsif ( $1 eq 'setup' ) {
5431           $billtime = str2time(shift @columns);
5432         } else {
5433           $cust_pkg{$1} = str2time( shift @columns );
5434         } 
5435
5436       } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
5437
5438         $svc_acct{$1} = shift @columns;
5439         
5440       } else {
5441
5442         #refnum interception
5443         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
5444
5445           my $referral = $columns[0];
5446           my %hash = ( 'referral' => $referral,
5447                        'agentnum' => $agentnum,
5448                        'disabled' => '',
5449                      );
5450
5451           my $part_referral = qsearchs('part_referral', \%hash )
5452                               || new FS::part_referral \%hash;
5453
5454           unless ( $part_referral->refnum ) {
5455             my $error = $part_referral->insert;
5456             if ( $error ) {
5457               $dbh->rollback if $oldAutoCommit;
5458               return "can't auto-insert advertising source: $referral: $error";
5459             }
5460           }
5461
5462           $columns[0] = $part_referral->refnum;
5463         }
5464
5465         #$cust_main{$field} = shift @$columns; 
5466         $cust_main{$field} = shift @columns; 
5467       }
5468     }
5469
5470     $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
5471
5472     my $invoicing_list = $cust_main{'invoicing_list'}
5473                            ? [ delete $cust_main{'invoicing_list'} ]
5474                            : [];
5475
5476     my $cust_main = new FS::cust_main ( \%cust_main );
5477
5478     use Tie::RefHash;
5479     tie my %hash, 'Tie::RefHash'; #this part is important
5480
5481     if ( $cust_pkg{'pkgpart'} ) {
5482       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
5483
5484       my @svc_acct = ();
5485       if ( $svc_acct{'username'} ) {
5486         my $part_pkg = $cust_pkg->part_pkg;
5487         unless ( $part_pkg ) {
5488           $dbh->rollback if $oldAutoCommit;
5489           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
5490         } 
5491         $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
5492         push @svc_acct, new FS::svc_acct ( \%svc_acct )
5493       }
5494
5495       $hash{$cust_pkg} = \@svc_acct;
5496     }
5497
5498     my $error = $cust_main->insert( \%hash, $invoicing_list );
5499
5500     if ( $error ) {
5501       $dbh->rollback if $oldAutoCommit;
5502       return "can't insert customer for $line: $error";
5503     }
5504
5505     if ( $format eq 'simple' ) {
5506
5507       #false laziness w/bill.cgi
5508       $error = $cust_main->bill( 'time' => $billtime );
5509       if ( $error ) {
5510         $dbh->rollback if $oldAutoCommit;
5511         return "can't bill customer for $line: $error";
5512       }
5513   
5514       $error = $cust_main->apply_payments_and_credits;
5515       if ( $error ) {
5516         $dbh->rollback if $oldAutoCommit;
5517         return "can't bill customer for $line: $error";
5518       }
5519
5520       $error = $cust_main->collect();
5521       if ( $error ) {
5522         $dbh->rollback if $oldAutoCommit;
5523         return "can't collect customer for $line: $error";
5524       }
5525
5526     }
5527
5528     $imported++;
5529   }
5530
5531   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5532
5533   return "Empty file!" unless $imported;
5534
5535   ''; #no error
5536
5537 }
5538
5539 =item batch_charge
5540
5541 =cut
5542
5543 sub batch_charge {
5544   my $param = shift;
5545   #warn join('-',keys %$param);
5546   my $fh = $param->{filehandle};
5547   my @fields = @{$param->{fields}};
5548
5549   eval "use Text::CSV_XS;";
5550   die $@ if $@;
5551
5552   my $csv = new Text::CSV_XS;
5553   #warn $csv;
5554   #warn $fh;
5555
5556   my $imported = 0;
5557   #my $columns;
5558
5559   local $SIG{HUP} = 'IGNORE';
5560   local $SIG{INT} = 'IGNORE';
5561   local $SIG{QUIT} = 'IGNORE';
5562   local $SIG{TERM} = 'IGNORE';
5563   local $SIG{TSTP} = 'IGNORE';
5564   local $SIG{PIPE} = 'IGNORE';
5565
5566   my $oldAutoCommit = $FS::UID::AutoCommit;
5567   local $FS::UID::AutoCommit = 0;
5568   my $dbh = dbh;
5569   
5570   #while ( $columns = $csv->getline($fh) ) {
5571   my $line;
5572   while ( defined($line=<$fh>) ) {
5573
5574     $csv->parse($line) or do {
5575       $dbh->rollback if $oldAutoCommit;
5576       return "can't parse: ". $csv->error_input();
5577     };
5578
5579     my @columns = $csv->fields();
5580     #warn join('-',@columns);
5581
5582     my %row = ();
5583     foreach my $field ( @fields ) {
5584       $row{$field} = shift @columns;
5585     }
5586
5587     my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
5588     unless ( $cust_main ) {
5589       $dbh->rollback if $oldAutoCommit;
5590       return "unknown custnum $row{'custnum'}";
5591     }
5592
5593     if ( $row{'amount'} > 0 ) {
5594       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5595       if ( $error ) {
5596         $dbh->rollback if $oldAutoCommit;
5597         return $error;
5598       }
5599       $imported++;
5600     } elsif ( $row{'amount'} < 0 ) {
5601       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5602                                       $row{'pkg'}                         );
5603       if ( $error ) {
5604         $dbh->rollback if $oldAutoCommit;
5605         return $error;
5606       }
5607       $imported++;
5608     } else {
5609       #hmm?
5610     }
5611
5612   }
5613
5614   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5615
5616   return "Empty file!" unless $imported;
5617
5618   ''; #no error
5619
5620 }
5621
5622 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5623
5624 Sends a templated email notification to the customer (see L<Text::Template>).
5625
5626 OPTIONS is a hash and may include
5627
5628 I<from> - the email sender (default is invoice_from)
5629
5630 I<to> - comma-separated scalar or arrayref of recipients 
5631    (default is invoicing_list)
5632
5633 I<subject> - The subject line of the sent email notification
5634    (default is "Notice from company_name")
5635
5636 I<extra_fields> - a hashref of name/value pairs which will be substituted
5637    into the template
5638
5639 The following variables are vavailable in the template.
5640
5641 I<$first> - the customer first name
5642 I<$last> - the customer last name
5643 I<$company> - the customer company
5644 I<$payby> - a description of the method of payment for the customer
5645             # would be nice to use FS::payby::shortname
5646 I<$payinfo> - the account information used to collect for this customer
5647 I<$expdate> - the expiration of the customer payment in seconds from epoch
5648
5649 =cut
5650
5651 sub notify {
5652   my ($customer, $template, %options) = @_;
5653
5654   return unless $conf->exists($template);
5655
5656   my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
5657   $from = $options{from} if exists($options{from});
5658
5659   my $to = join(',', $customer->invoicing_list_emailonly);
5660   $to = $options{to} if exists($options{to});
5661   
5662   my $subject = "Notice from " . $conf->config('company_name')
5663     if $conf->exists('company_name');
5664   $subject = $options{subject} if exists($options{subject});
5665
5666   my $notify_template = new Text::Template (TYPE => 'ARRAY',
5667                                             SOURCE => [ map "$_\n",
5668                                               $conf->config($template)]
5669                                            )
5670     or die "can't create new Text::Template object: Text::Template::ERROR";
5671   $notify_template->compile()
5672     or die "can't compile template: Text::Template::ERROR";
5673
5674   my $paydate = $customer->paydate;
5675   $FS::notify_template::_template::first = $customer->first;
5676   $FS::notify_template::_template::last = $customer->last;
5677   $FS::notify_template::_template::company = $customer->company;
5678   $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
5679   my $payby = $customer->payby;
5680   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5681   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5682
5683   #credit cards expire at the end of the month/year of their exp date
5684   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5685     $FS::notify_template::_template::payby = 'credit card';
5686     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5687     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5688     $expire_time--;
5689   }elsif ($payby eq 'COMP') {
5690     $FS::notify_template::_template::payby = 'complimentary account';
5691   }else{
5692     $FS::notify_template::_template::payby = 'current method';
5693   }
5694   $FS::notify_template::_template::expdate = $expire_time;
5695
5696   for (keys %{$options{extra_fields}}){
5697     no strict "refs";
5698     ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5699   }
5700
5701   send_email(from => $from,
5702              to => $to,
5703              subject => $subject,
5704              body => $notify_template->fill_in( PACKAGE =>
5705                                                 'FS::notify_template::_template'                                              ),
5706             );
5707
5708 }
5709
5710 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5711
5712 Generates a templated notification to the customer (see L<Text::Template>).
5713
5714 OPTIONS is a hash and may include
5715
5716 I<extra_fields> - a hashref of name/value pairs which will be substituted
5717    into the template.  These values may override values mentioned below
5718    and those from the customer record.
5719
5720 The following variables are available in the template instead of or in addition
5721 to the fields of the customer record.
5722
5723 I<$payby> - a description of the method of payment for the customer
5724             # would be nice to use FS::payby::shortname
5725 I<$payinfo> - the masked account information used to collect for this customer
5726 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5727 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress
5728
5729 =cut
5730
5731 sub generate_letter {
5732   my ($self, $template, %options) = @_;
5733
5734   return unless $conf->exists($template);
5735
5736   my $letter_template = new Text::Template
5737                         ( TYPE       => 'ARRAY',
5738                           SOURCE     => [ map "$_\n", $conf->config($template)],
5739                           DELIMITERS => [ '[@--', '--@]' ],
5740                         )
5741     or die "can't create new Text::Template object: Text::Template::ERROR";
5742
5743   $letter_template->compile()
5744     or die "can't compile template: Text::Template::ERROR";
5745
5746   my %letter_data = map { $_ => $self->$_ } $self->fields;
5747   $letter_data{payinfo} = $self->mask_payinfo;
5748
5749   #my $paydate = $self->paydate || '2037-12';
5750   my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12';
5751
5752   my $payby = $self->payby;
5753   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5754   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5755
5756   #credit cards expire at the end of the month/year of their exp date
5757   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5758     $letter_data{payby} = 'credit card';
5759     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5760     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5761     $expire_time--;
5762   }elsif ($payby eq 'COMP') {
5763     $letter_data{payby} = 'complimentary account';
5764   }else{
5765     $letter_data{payby} = 'current method';
5766   }
5767   $letter_data{expdate} = $expire_time;
5768
5769   for (keys %{$options{extra_fields}}){
5770     $letter_data{$_} = $options{extra_fields}->{$_};
5771   }
5772
5773   unless(exists($letter_data{returnaddress})){
5774     my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5775                                                   $self->agent_template)
5776                      );
5777
5778     $letter_data{returnaddress} = length($retadd) ? $retadd : '~';
5779   }
5780
5781   $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5782
5783   my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
5784   my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5785                            DIR      => $dir,
5786                            SUFFIX   => '.tex',
5787                            UNLINK   => 0,
5788                          ) or die "can't open temp file: $!\n";
5789
5790   $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5791   close $fh;
5792   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5793   return $1;
5794 }
5795
5796 =item print_ps TEMPLATE 
5797
5798 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5799
5800 =cut
5801
5802 sub print_ps {
5803   my $self = shift;
5804   my $file = $self->generate_letter(@_);
5805   FS::Misc::generate_ps($file);
5806 }
5807
5808 =item print TEMPLATE
5809
5810 Prints the filled in template.
5811
5812 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5813
5814 =cut
5815
5816 sub queueable_print {
5817   my %opt = @_;
5818
5819   my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5820     or die "invalid customer number: " . $opt{custvnum};
5821
5822   my $error = $self->print( $opt{template} );
5823   die $error if $error;
5824 }
5825
5826 sub print {
5827   my ($self, $template) = (shift, shift);
5828   do_print [ $self->print_ps($template) ];
5829 }
5830
5831 sub agent_template {
5832   my $self = shift;
5833   $self->_agent_plandata('agent_templatename');
5834 }
5835
5836 sub agent_invoice_from {
5837   my $self = shift;
5838   $self->_agent_plandata('agent_invoice_from');
5839 }
5840
5841 sub _agent_plandata {
5842   my( $self, $option ) = @_;
5843
5844   #yuck.  this whole thing needs to be reconciled better with 1.9's idea of
5845   #agent-specific Conf
5846   
5847   my $agentnum = $self->agentnum;
5848
5849   my $part_event_option =
5850     qsearchs({
5851       'select'    => 'part_event_option.*',
5852       'table'     => 'part_event_option',
5853       'addl_from' => q{
5854         LEFT JOIN part_event USING ( eventpart )
5855         LEFT JOIN part_event_option AS peo_agentnum
5856           ON ( part_event.eventpart = peo_agentnum.eventpart
5857                AND peo_agentnum.optionname = 'agentnum'
5858                AND peo_agentnum.optionvalue ~ '(^|,)}. $agentnum. q{(,|$)'
5859              )
5860         LEFT JOIN part_event_option AS peo_cust_bill_age
5861           ON ( part_event.eventpart = peo_cust_bill_age.eventpart
5862                AND peo_cust_bill_age.optionname = 'cust_bill_age'
5863              )
5864       },
5865       #'hashref'   => { 'optionname' => $option },
5866       #'hashref'   => { 'part_event_option.optionname' => $option },
5867       'extra_sql' =>
5868         " WHERE part_event_option.optionname = ". dbh->quote($option).
5869         " AND action = 'cust_bill_send_agent' ".
5870         " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5871         " AND peo_agentnum.optionname = 'agentnum' ".
5872         " AND agentnum IS NULL OR agentnum = $agentnum ".
5873         " ORDER BY
5874            CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
5875            THEN -1
5876            ELSE EXTRACT( EPOCH FROM
5877                            REPLACE( peo_cust_bill_age.optionvalue,
5878                                     'm',
5879                                     'mon'
5880                                   )::interval
5881                        )
5882           END
5883           , part_event.weight".
5884         " LIMIT 1"
5885     });
5886     
5887   unless ( $part_event_option ) {
5888     return $self->agent->invoice_template || ''
5889       if $option eq 'agent_templatename';
5890     return '';
5891   }
5892
5893   $part_event_option->optionvalue;
5894
5895 }
5896
5897 sub queued_bill {
5898   ## actual sub, not a method, designed to be called from the queue.
5899   ## sets up the customer, and calls the bill_and_collect
5900   my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5901   my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5902       $cust_main->bill_and_collect(
5903         %args,
5904       );
5905 }
5906
5907 =back
5908
5909 =head1 BUGS
5910
5911 The delete method.
5912
5913 The delete method should possibly take an FS::cust_main object reference
5914 instead of a scalar customer number.
5915
5916 Bill and collect options should probably be passed as references instead of a
5917 list.
5918
5919 There should probably be a configuration file with a list of allowed credit
5920 card types.
5921
5922 No multiple currency support (probably a larger project than just this module).
5923
5924 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5925
5926 Birthdates rely on negative epoch values.
5927
5928 The payby for card/check batches is broken.  With mixed batching, bad
5929 things will happen.
5930
5931 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5932
5933 =head1 SEE ALSO
5934
5935 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5936 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5937 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
5938
5939 =cut
5940
5941 1;
5942