delete CVV when processing batch results, RT#9652
[freeside.git] / FS / FS / cust_main.pm
1 package FS::cust_main;
2
3 require 5.006;
4 use strict;
5 use base qw( FS::otaker_Mixin FS::payinfo_Mixin FS::Record );
6 use vars qw( @EXPORT_OK $DEBUG $me $conf
7              @encrypted_fields
8              $import $ignore_expired_card
9              $skip_fuzzyfiles @fuzzyfields
10              @paytypes
11            );
12 use vars qw( $realtime_bop_decline_quiet ); #ugh
13 use Safe;
14 use Carp;
15 use Exporter;
16 use Scalar::Util qw( blessed );
17 use List::Util qw( min );
18 use Time::Local qw(timelocal);
19 use Storable qw(thaw);
20 use MIME::Base64;
21 use Data::Dumper;
22 use Tie::IxHash;
23 use Digest::MD5 qw(md5_base64);
24 use Date::Format;
25 #use Date::Manip;
26 use File::Temp qw( tempfile );
27 use String::Approx qw(amatch);
28 use Business::CreditCard 0.28;
29 use Locale::Country;
30 use FS::UID qw( getotaker dbh driver_name );
31 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
32 use FS::Misc qw( generate_email send_email generate_ps do_print );
33 use FS::Msgcat qw(gettext);
34 use FS::payby;
35 use FS::cust_pkg;
36 use FS::cust_svc;
37 use FS::cust_bill;
38 use FS::cust_bill_pkg;
39 use FS::cust_bill_pkg_display;
40 use FS::cust_bill_pkg_tax_location;
41 use FS::cust_bill_pkg_tax_rate_location;
42 use FS::cust_pay;
43 use FS::cust_pay_pending;
44 use FS::cust_pay_void;
45 use FS::cust_pay_batch;
46 use FS::cust_credit;
47 use FS::cust_refund;
48 use FS::part_referral;
49 use FS::cust_main_county;
50 use FS::cust_location;
51 use FS::cust_class;
52 use FS::cust_main_exemption;
53 use FS::cust_tax_adjustment;
54 use FS::tax_rate;
55 use FS::tax_rate_location;
56 use FS::cust_tax_location;
57 use FS::part_pkg_taxrate;
58 use FS::agent;
59 use FS::cust_main_invoice;
60 use FS::cust_tag;
61 use FS::cust_credit_bill;
62 use FS::cust_bill_pay;
63 use FS::prepay_credit;
64 use FS::queue;
65 use FS::part_pkg;
66 use FS::part_event;
67 use FS::part_event_condition;
68 use FS::part_export;
69 #use FS::cust_event;
70 use FS::type_pkgs;
71 use FS::payment_gateway;
72 use FS::agent_payment_gateway;
73 use FS::banned_pay;
74 use FS::TicketSystem;
75
76 @EXPORT_OK = qw( smart_search );
77
78 $realtime_bop_decline_quiet = 0;
79
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
83 $DEBUG = 0;
84 $me = '[FS::cust_main]';
85
86 $import = 0;
87 $ignore_expired_card = 0;
88
89 $skip_fuzzyfiles = 0;
90 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
91
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
94
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
96
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub { 
99 install_callback FS::UID sub { 
100   $conf = new FS::Conf;
101   #yes, need it for stuff below (prolly should be cached)
102 };
103
104 sub _cache {
105   my $self = shift;
106   my ( $hashref, $cache ) = @_;
107   if ( exists $hashref->{'pkgnum'} ) {
108     #@{ $self->{'_pkgnum'} } = ();
109     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110     $self->{'_pkgnum'} = $subcache;
111     #push @{ $self->{'_pkgnum'} },
112     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
113   }
114 }
115
116 =head1 NAME
117
118 FS::cust_main - Object methods for cust_main records
119
120 =head1 SYNOPSIS
121
122   use FS::cust_main;
123
124   $record = new FS::cust_main \%hash;
125   $record = new FS::cust_main { 'column' => 'value' };
126
127   $error = $record->insert;
128
129   $error = $new_record->replace($old_record);
130
131   $error = $record->delete;
132
133   $error = $record->check;
134
135   @cust_pkg = $record->all_pkgs;
136
137   @cust_pkg = $record->ncancelled_pkgs;
138
139   @cust_pkg = $record->suspended_pkgs;
140
141   $error = $record->bill;
142   $error = $record->bill %options;
143   $error = $record->bill 'time' => $time;
144
145   $error = $record->collect;
146   $error = $record->collect %options;
147   $error = $record->collect 'invoice_time'   => $time,
148                           ;
149
150 =head1 DESCRIPTION
151
152 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
153 FS::Record.  The following fields are currently supported:
154
155 =over 4
156
157 =item custnum
158
159 Primary key (assigned automatically for new customers)
160
161 =item agentnum
162
163 Agent (see L<FS::agent>)
164
165 =item refnum
166
167 Advertising source (see L<FS::part_referral>)
168
169 =item first
170
171 First name
172
173 =item last
174
175 Last name
176
177 =item ss
178
179 Cocial security number (optional)
180
181 =item company
182
183 (optional)
184
185 =item address1
186
187 =item address2
188
189 (optional)
190
191 =item city
192
193 =item county
194
195 (optional, see L<FS::cust_main_county>)
196
197 =item state
198
199 (see L<FS::cust_main_county>)
200
201 =item zip
202
203 =item country
204
205 (see L<FS::cust_main_county>)
206
207 =item daytime
208
209 phone (optional)
210
211 =item night
212
213 phone (optional)
214
215 =item fax
216
217 phone (optional)
218
219 =item ship_first
220
221 Shipping first name
222
223 =item ship_last
224
225 Shipping last name
226
227 =item ship_company
228
229 (optional)
230
231 =item ship_address1
232
233 =item ship_address2
234
235 (optional)
236
237 =item ship_city
238
239 =item ship_county
240
241 (optional, see L<FS::cust_main_county>)
242
243 =item ship_state
244
245 (see L<FS::cust_main_county>)
246
247 =item ship_zip
248
249 =item ship_country
250
251 (see L<FS::cust_main_county>)
252
253 =item ship_daytime
254
255 phone (optional)
256
257 =item ship_night
258
259 phone (optional)
260
261 =item ship_fax
262
263 phone (optional)
264
265 =item payby
266
267 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
268
269 =item payinfo
270
271 Payment Information (See L<FS::payinfo_Mixin> for data format)
272
273 =item paymask
274
275 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
276
277 =item paycvv
278
279 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
280
281 =item paydate
282
283 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
284
285 =item paystart_month
286
287 Start date month (maestro/solo cards only)
288
289 =item paystart_year
290
291 Start date year (maestro/solo cards only)
292
293 =item payissue
294
295 Issue number (maestro/solo cards only)
296
297 =item payname
298
299 Name on card or billing name
300
301 =item payip
302
303 IP address from which payment information was received
304
305 =item tax
306
307 Tax exempt, empty or `Y'
308
309 =item usernum
310
311 Order taker (see L<FS::access_user>)
312
313 =item comments
314
315 Comments (optional)
316
317 =item referral_custnum
318
319 Referring customer number
320
321 =item spool_cdr
322
323 Enable individual CDR spooling, empty or `Y'
324
325 =item dundate
326
327 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
328
329 =item squelch_cdr
330
331 Discourage individual CDR printing, empty or `Y'
332
333 =back
334
335 =head1 METHODS
336
337 =over 4
338
339 =item new HASHREF
340
341 Creates a new customer.  To add the customer to the database, see L<"insert">.
342
343 Note that this stores the hash reference, not a distinct copy of the hash it
344 points to.  You can ask the object for a copy with the I<hash> method.
345
346 =cut
347
348 sub table { 'cust_main'; }
349
350 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
351
352 Adds this customer to the database.  If there is an error, returns the error,
353 otherwise returns false.
354
355 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
356 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
357 are inserted atomicly, or the transaction is rolled back.  Passing an empty
358 hash reference is equivalent to not supplying this parameter.  There should be
359 a better explanation of this, but until then, here's an example:
360
361   use Tie::RefHash;
362   tie %hash, 'Tie::RefHash'; #this part is important
363   %hash = (
364     $cust_pkg => [ $svc_acct ],
365     ...
366   );
367   $cust_main->insert( \%hash );
368
369 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
370 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
371 expected and rollback the entire transaction; it is not necessary to call 
372 check_invoicing_list first.  The invoicing_list is set after the records in the
373 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
374 invoicing_list destination to the newly-created svc_acct.  Here's an example:
375
376   $cust_main->insert( {}, [ $email, 'POST' ] );
377
378 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
379
380 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
381 on the supplied jobnum (they will not run until the specific job completes).
382 This can be used to defer provisioning until some action completes (such
383 as running the customer's credit card successfully).
384
385 The I<noexport> option is deprecated.  If I<noexport> is set true, no
386 provisioning jobs (exports) are scheduled.  (You can schedule them later with
387 the B<reexport> method.)
388
389 The I<tax_exemption> option can be set to an arrayref of tax names.
390 FS::cust_main_exemption records will be created and inserted.
391
392 =cut
393
394 sub insert {
395   my $self = shift;
396   my $cust_pkgs = @_ ? shift : {};
397   my $invoicing_list = @_ ? shift : '';
398   my %options = @_;
399   warn "$me insert called with options ".
400        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
401     if $DEBUG;
402
403   local $SIG{HUP} = 'IGNORE';
404   local $SIG{INT} = 'IGNORE';
405   local $SIG{QUIT} = 'IGNORE';
406   local $SIG{TERM} = 'IGNORE';
407   local $SIG{TSTP} = 'IGNORE';
408   local $SIG{PIPE} = 'IGNORE';
409
410   my $oldAutoCommit = $FS::UID::AutoCommit;
411   local $FS::UID::AutoCommit = 0;
412   my $dbh = dbh;
413
414   my $prepay_identifier = '';
415   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
416   my $payby = '';
417   if ( $self->payby eq 'PREPAY' ) {
418
419     $self->payby('BILL');
420     $prepay_identifier = $self->payinfo;
421     $self->payinfo('');
422
423     warn "  looking up prepaid card $prepay_identifier\n"
424       if $DEBUG > 1;
425
426     my $error = $self->get_prepay( $prepay_identifier,
427                                    'amount_ref'     => \$amount,
428                                    'seconds_ref'    => \$seconds,
429                                    'upbytes_ref'    => \$upbytes,
430                                    'downbytes_ref'  => \$downbytes,
431                                    'totalbytes_ref' => \$totalbytes,
432                                  );
433     if ( $error ) {
434       $dbh->rollback if $oldAutoCommit;
435       #return "error applying prepaid card (transaction rolled back): $error";
436       return $error;
437     }
438
439     $payby = 'PREP' if $amount;
440
441   } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
442
443     $payby = $1;
444     $self->payby('BILL');
445     $amount = $self->paid;
446
447   }
448
449   warn "  inserting $self\n"
450     if $DEBUG > 1;
451
452   $self->signupdate(time) unless $self->signupdate;
453
454   $self->auto_agent_custid()
455     if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
456
457   my $error = $self->SUPER::insert;
458   if ( $error ) {
459     $dbh->rollback if $oldAutoCommit;
460     #return "inserting cust_main record (transaction rolled back): $error";
461     return $error;
462   }
463
464   warn "  setting invoicing list\n"
465     if $DEBUG > 1;
466
467   if ( $invoicing_list ) {
468     $error = $self->check_invoicing_list( $invoicing_list );
469     if ( $error ) {
470       $dbh->rollback if $oldAutoCommit;
471       #return "checking invoicing_list (transaction rolled back): $error";
472       return $error;
473     }
474     $self->invoicing_list( $invoicing_list );
475   }
476
477   warn "  setting customer tags\n"
478     if $DEBUG > 1;
479
480   foreach my $tagnum ( @{ $self->tagnum || [] } ) {
481     my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
482                                       'custnum' => $self->custnum };
483     my $error = $cust_tag->insert;
484     if ( $error ) {
485       $dbh->rollback if $oldAutoCommit;
486       return $error;
487     }
488   }
489
490   if ( $invoicing_list ) {
491     $error = $self->check_invoicing_list( $invoicing_list );
492     if ( $error ) {
493       $dbh->rollback if $oldAutoCommit;
494       #return "checking invoicing_list (transaction rolled back): $error";
495       return $error;
496     }
497     $self->invoicing_list( $invoicing_list );
498   }
499
500
501   warn "  setting cust_main_exemption\n"
502     if $DEBUG > 1;
503
504   my $tax_exemption = delete $options{'tax_exemption'};
505   if ( $tax_exemption ) {
506     foreach my $taxname ( @$tax_exemption ) {
507       my $cust_main_exemption = new FS::cust_main_exemption {
508         'custnum' => $self->custnum,
509         'taxname' => $taxname,
510       };
511       my $error = $cust_main_exemption->insert;
512       if ( $error ) {
513         $dbh->rollback if $oldAutoCommit;
514         return "inserting cust_main_exemption (transaction rolled back): $error";
515       }
516     }
517   }
518
519   if (    $conf->config('cust_main-skeleton_tables')
520        && $conf->config('cust_main-skeleton_custnum') ) {
521
522     warn "  inserting skeleton records\n"
523       if $DEBUG > 1;
524
525     my $error = $self->start_copy_skel;
526     if ( $error ) {
527       $dbh->rollback if $oldAutoCommit;
528       return $error;
529     }
530
531   }
532
533   warn "  ordering packages\n"
534     if $DEBUG > 1;
535
536   $error = $self->order_pkgs( $cust_pkgs,
537                               %options,
538                               'seconds_ref'    => \$seconds,
539                               'upbytes_ref'    => \$upbytes,
540                               'downbytes_ref'  => \$downbytes,
541                               'totalbytes_ref' => \$totalbytes,
542                             );
543   if ( $error ) {
544     $dbh->rollback if $oldAutoCommit;
545     return $error;
546   }
547
548   if ( $seconds ) {
549     $dbh->rollback if $oldAutoCommit;
550     return "No svc_acct record to apply pre-paid time";
551   }
552   if ( $upbytes || $downbytes || $totalbytes ) {
553     $dbh->rollback if $oldAutoCommit;
554     return "No svc_acct record to apply pre-paid data";
555   }
556
557   if ( $amount ) {
558     warn "  inserting initial $payby payment of $amount\n"
559       if $DEBUG > 1;
560     $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
561     if ( $error ) {
562       $dbh->rollback if $oldAutoCommit;
563       return "inserting payment (transaction rolled back): $error";
564     }
565   }
566
567   unless ( $import || $skip_fuzzyfiles ) {
568     warn "  queueing fuzzyfiles update\n"
569       if $DEBUG > 1;
570     $error = $self->queue_fuzzyfiles_update;
571     if ( $error ) {
572       $dbh->rollback if $oldAutoCommit;
573       return "updating fuzzy search cache: $error";
574     }
575   }
576
577   # cust_main exports!
578   warn "  exporting\n" if $DEBUG > 1;
579
580   my $export_args = $options{'export_args'} || [];
581
582   my @part_export =
583     map qsearch( 'part_export', {exportnum=>$_} ),
584       $conf->config('cust_main-exports'); #, $agentnum
585
586   foreach my $part_export ( @part_export ) {
587     my $error = $part_export->export_insert($self, @$export_args);
588     if ( $error ) {
589       $dbh->rollback if $oldAutoCommit;
590       return "exporting to ". $part_export->exporttype.
591              " (transaction rolled back): $error";
592     }
593   }
594
595   #foreach my $depend_jobnum ( @$depend_jobnums ) {
596   #    warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
597   #      if $DEBUG;
598   #    foreach my $jobnum ( @jobnums ) {
599   #      my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
600   #      warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
601   #        if $DEBUG;
602   #      my $error = $queue->depend_insert($depend_jobnum);
603   #      if ( $error ) {
604   #        $dbh->rollback if $oldAutoCommit;
605   #        return "error queuing job dependancy: $error";
606   #      }
607   #    }
608   #  }
609   #
610   #}
611   #
612   #if ( exists $options{'jobnums'} ) {
613   #  push @{ $options{'jobnums'} }, @jobnums;
614   #}
615
616   warn "  insert complete; committing transaction\n"
617     if $DEBUG > 1;
618
619   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
620   '';
621
622 }
623
624 use File::CounterFile;
625 sub auto_agent_custid {
626   my $self = shift;
627
628   my $format = $conf->config('cust_main-auto_agent_custid');
629   my $agent_custid;
630   if ( $format eq '1YMMXXXXXXXX' ) {
631
632     my $counter = new File::CounterFile 'cust_main.agent_custid';
633     $counter->lock;
634
635     my $ym = 100000000000 + time2str('%y%m00000000', time);
636     if ( $ym > $counter->value ) {
637       $counter->{'value'} = $agent_custid = $ym;
638       $counter->{'updated'} = 1;
639     } else {
640       $agent_custid = $counter->inc;
641     }
642
643     $counter->unlock;
644
645   } else {
646     die "Unknown cust_main-auto_agent_custid format: $format";
647   }
648
649   $self->agent_custid($agent_custid);
650
651 }
652
653 sub start_copy_skel {
654   my $self = shift;
655
656   #'mg_user_preference' => {},
657   #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
658   #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
659   #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
660   #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
661   my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
662   die $@ if $@;
663
664   _copy_skel( 'cust_main',                                 #tablename
665               $conf->config('cust_main-skeleton_custnum'), #sourceid
666               $self->custnum,                              #destid
667               @tables,                                     #child tables
668             );
669 }
670
671 #recursive subroutine, not a method
672 sub _copy_skel {
673   my( $table, $sourceid, $destid, %child_tables ) = @_;
674
675   my $primary_key;
676   if ( $table =~ /^(\w+)\.(\w+)$/ ) {
677     ( $table, $primary_key ) = ( $1, $2 );
678   } else {
679     my $dbdef_table = dbdef->table($table);
680     $primary_key = $dbdef_table->primary_key
681       or return "$table has no primary key".
682                 " (or do you need to run dbdef-create?)";
683   }
684
685   warn "  _copy_skel: $table.$primary_key $sourceid to $destid for ".
686        join (', ', keys %child_tables). "\n"
687     if $DEBUG > 2;
688
689   foreach my $child_table_def ( keys %child_tables ) {
690
691     my $child_table;
692     my $child_pkey = '';
693     if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
694       ( $child_table, $child_pkey ) = ( $1, $2 );
695     } else {
696       $child_table = $child_table_def;
697
698       $child_pkey = dbdef->table($child_table)->primary_key;
699       #  or return "$table has no primary key".
700       #            " (or do you need to run dbdef-create?)\n";
701     }
702
703     my $sequence = '';
704     if ( keys %{ $child_tables{$child_table_def} } ) {
705
706       return "$child_table has no primary key".
707              " (run dbdef-create or try specifying it?)\n"
708         unless $child_pkey;
709
710       #false laziness w/Record::insert and only works on Pg
711       #refactor the proper last-inserted-id stuff out of Record::insert if this
712       # ever gets use for anything besides a quick kludge for one customer
713       my $default = dbdef->table($child_table)->column($child_pkey)->default;
714       $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
715         or return "can't parse $child_table.$child_pkey default value ".
716                   " for sequence name: $default";
717       $sequence = $1;
718
719     }
720   
721     my @sel_columns = grep { $_ ne $primary_key }
722                            dbdef->table($child_table)->columns;
723     my $sel_columns = join(', ', @sel_columns );
724
725     my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
726     my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
727     my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
728
729     my $sel_st = "SELECT $sel_columns FROM $child_table".
730                  " WHERE $primary_key = $sourceid";
731     warn "    $sel_st\n"
732       if $DEBUG > 2;
733     my $sel_sth = dbh->prepare( $sel_st )
734       or return dbh->errstr;
735   
736     $sel_sth->execute or return $sel_sth->errstr;
737
738     while ( my $row = $sel_sth->fetchrow_hashref ) {
739
740       warn "    selected row: ".
741            join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
742         if $DEBUG > 2;
743
744       my $statement =
745         "INSERT INTO $child_table $ins_columns VALUES $placeholders";
746       my $ins_sth =dbh->prepare($statement)
747           or return dbh->errstr;
748       my @param = ( $destid, map $row->{$_}, @ins_columns );
749       warn "    $statement: [ ". join(', ', @param). " ]\n"
750         if $DEBUG > 2;
751       $ins_sth->execute( @param )
752         or return $ins_sth->errstr;
753
754       #next unless keys %{ $child_tables{$child_table} };
755       next unless $sequence;
756       
757       #another section of that laziness
758       my $seq_sql = "SELECT currval('$sequence')";
759       my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
760       $seq_sth->execute or return $seq_sth->errstr;
761       my $insertid = $seq_sth->fetchrow_arrayref->[0];
762   
763       # don't drink soap!  recurse!  recurse!  okay!
764       my $error =
765         _copy_skel( $child_table_def,
766                     $row->{$child_pkey}, #sourceid
767                     $insertid, #destid
768                     %{ $child_tables{$child_table_def} },
769                   );
770       return $error if $error;
771
772     }
773
774   }
775
776   return '';
777
778 }
779
780 =item order_pkg HASHREF | OPTION => VALUE ... 
781
782 Orders a single package.
783
784 Options may be passed as a list of key/value pairs or as a hash reference.
785 Options are:
786
787 =over 4
788
789 =item cust_pkg
790
791 FS::cust_pkg object
792
793 =item cust_location
794
795 Optional FS::cust_location object
796
797 =item svcs
798
799 Optional arryaref of FS::svc_* service objects.
800
801 =item depend_jobnum
802
803 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
804 jobs will have a dependancy on the supplied job (they will not run until the
805 specific job completes).  This can be used to defer provisioning until some
806 action completes (such as running the customer's credit card successfully).
807
808 =item ticket_subject
809
810 Optional subject for a ticket created and attached to this customer
811
812 =item ticket_subject
813
814 Optional queue name for ticket additions
815
816 =back
817
818 =cut
819
820 sub order_pkg {
821   my $self = shift;
822   my $opt = ref($_[0]) ? shift : { @_ };
823
824   warn "$me order_pkg called with options ".
825        join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
826     if $DEBUG;
827
828   my $cust_pkg = $opt->{'cust_pkg'};
829   my $svcs     = $opt->{'svcs'} || [];
830
831   my %svc_options = ();
832   $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
833     if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
834
835   my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
836                           qw( ticket_subject ticket_queue );
837
838   local $SIG{HUP} = 'IGNORE';
839   local $SIG{INT} = 'IGNORE';
840   local $SIG{QUIT} = 'IGNORE';
841   local $SIG{TERM} = 'IGNORE';
842   local $SIG{TSTP} = 'IGNORE';
843   local $SIG{PIPE} = 'IGNORE';
844
845   my $oldAutoCommit = $FS::UID::AutoCommit;
846   local $FS::UID::AutoCommit = 0;
847   my $dbh = dbh;
848
849   if ( $opt->{'cust_location'} &&
850        ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
851     my $error = $opt->{'cust_location'}->insert;
852     if ( $error ) {
853       $dbh->rollback if $oldAutoCommit;
854       return "inserting cust_location (transaction rolled back): $error";
855     }
856     $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
857   }
858
859   $cust_pkg->custnum( $self->custnum );
860
861   my $error = $cust_pkg->insert( %insert_params );
862   if ( $error ) {
863     $dbh->rollback if $oldAutoCommit;
864     return "inserting cust_pkg (transaction rolled back): $error";
865   }
866
867   foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
868     if ( $svc_something->svcnum ) {
869       my $old_cust_svc = $svc_something->cust_svc;
870       my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
871       $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
872       $error = $new_cust_svc->replace($old_cust_svc);
873     } else {
874       $svc_something->pkgnum( $cust_pkg->pkgnum );
875       if ( $svc_something->isa('FS::svc_acct') ) {
876         foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
877                        qw( seconds upbytes downbytes totalbytes )      ) {
878           $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
879           ${ $opt->{$_.'_ref'} } = 0;
880         }
881       }
882       $error = $svc_something->insert(%svc_options);
883     }
884     if ( $error ) {
885       $dbh->rollback if $oldAutoCommit;
886       return "inserting svc_ (transaction rolled back): $error";
887     }
888   }
889
890   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
891   ''; #no error
892
893 }
894
895 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
896 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
897
898 Like the insert method on an existing record, this method orders multiple
899 packages and included services atomicaly.  Pass a Tie::RefHash data structure
900 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
901 There should be a better explanation of this, but until then, here's an
902 example:
903
904   use Tie::RefHash;
905   tie %hash, 'Tie::RefHash'; #this part is important
906   %hash = (
907     $cust_pkg => [ $svc_acct ],
908     ...
909   );
910   $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
911
912 Services can be new, in which case they are inserted, or existing unaudited
913 services, in which case they are linked to the newly-created package.
914
915 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
916 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
917
918 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
919 on the supplied jobnum (they will not run until the specific job completes).
920 This can be used to defer provisioning until some action completes (such
921 as running the customer's credit card successfully).
922
923 The I<noexport> option is deprecated.  If I<noexport> is set true, no
924 provisioning jobs (exports) are scheduled.  (You can schedule them later with
925 the B<reexport> method for each cust_pkg object.  Using the B<reexport> method
926 on the cust_main object is not recommended, as existing services will also be
927 reexported.)
928
929 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
930 provided, the scalars (provided by references) will be incremented by the
931 values of the prepaid card.`
932
933 =cut
934
935 sub order_pkgs {
936   my $self = shift;
937   my $cust_pkgs = shift;
938   my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
939   my %options = @_;
940   $seconds_ref ||= $options{'seconds_ref'};
941
942   warn "$me order_pkgs called with options ".
943        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
944     if $DEBUG;
945
946   local $SIG{HUP} = 'IGNORE';
947   local $SIG{INT} = 'IGNORE';
948   local $SIG{QUIT} = 'IGNORE';
949   local $SIG{TERM} = 'IGNORE';
950   local $SIG{TSTP} = 'IGNORE';
951   local $SIG{PIPE} = 'IGNORE';
952
953   my $oldAutoCommit = $FS::UID::AutoCommit;
954   local $FS::UID::AutoCommit = 0;
955   my $dbh = dbh;
956
957   local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
958
959   foreach my $cust_pkg ( keys %$cust_pkgs ) {
960
961     my $error = $self->order_pkg(
962       'cust_pkg'     => $cust_pkg,
963       'svcs'         => $cust_pkgs->{$cust_pkg},
964       'seconds_ref'  => $seconds_ref,
965       map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
966                                      depend_jobnum
967                                    )
968     );
969     if ( $error ) {
970       $dbh->rollback if $oldAutoCommit;
971       return $error;
972     }
973
974   }
975
976   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
977   ''; #no error
978 }
979
980 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
981
982 Recharges this (existing) customer with the specified prepaid card (see
983 L<FS::prepay_credit>), specified either by I<identifier> or as an
984 FS::prepay_credit object.  If there is an error, returns the error, otherwise
985 returns false.
986
987 Optionally, five scalar references can be passed as well.  They will have their
988 values filled in with the amount, number of seconds, and number of upload,
989 download, and total bytes applied by this prepaid card.
990
991 =cut
992
993 #the ref bullshit here should be refactored like get_prepay.  MyAccount.pm is
994 #the only place that uses these args
995 sub recharge_prepay { 
996   my( $self, $prepay_credit, $amountref, $secondsref, 
997       $upbytesref, $downbytesref, $totalbytesref ) = @_;
998
999   local $SIG{HUP} = 'IGNORE';
1000   local $SIG{INT} = 'IGNORE';
1001   local $SIG{QUIT} = 'IGNORE';
1002   local $SIG{TERM} = 'IGNORE';
1003   local $SIG{TSTP} = 'IGNORE';
1004   local $SIG{PIPE} = 'IGNORE';
1005
1006   my $oldAutoCommit = $FS::UID::AutoCommit;
1007   local $FS::UID::AutoCommit = 0;
1008   my $dbh = dbh;
1009
1010   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
1011
1012   my $error = $self->get_prepay( $prepay_credit,
1013                                  'amount_ref'     => \$amount,
1014                                  'seconds_ref'    => \$seconds,
1015                                  'upbytes_ref'    => \$upbytes,
1016                                  'downbytes_ref'  => \$downbytes,
1017                                  'totalbytes_ref' => \$totalbytes,
1018                                )
1019            || $self->increment_seconds($seconds)
1020            || $self->increment_upbytes($upbytes)
1021            || $self->increment_downbytes($downbytes)
1022            || $self->increment_totalbytes($totalbytes)
1023            || $self->insert_cust_pay_prepay( $amount,
1024                                              ref($prepay_credit)
1025                                                ? $prepay_credit->identifier
1026                                                : $prepay_credit
1027                                            );
1028
1029   if ( $error ) {
1030     $dbh->rollback if $oldAutoCommit;
1031     return $error;
1032   }
1033
1034   if ( defined($amountref)  ) { $$amountref  = $amount;  }
1035   if ( defined($secondsref) ) { $$secondsref = $seconds; }
1036   if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1037   if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1038   if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1039
1040   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1041   '';
1042
1043 }
1044
1045 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1046
1047 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1048 specified either by I<identifier> or as an FS::prepay_credit object.
1049
1050 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.  The scalars (provided by references) will be
1051 incremented by the values of the prepaid card.
1052
1053 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1054 check or set this customer's I<agentnum>.
1055
1056 If there is an error, returns the error, otherwise returns false.
1057
1058 =cut
1059
1060
1061 sub get_prepay {
1062   my( $self, $prepay_credit, %opt ) = @_;
1063
1064   local $SIG{HUP} = 'IGNORE';
1065   local $SIG{INT} = 'IGNORE';
1066   local $SIG{QUIT} = 'IGNORE';
1067   local $SIG{TERM} = 'IGNORE';
1068   local $SIG{TSTP} = 'IGNORE';
1069   local $SIG{PIPE} = 'IGNORE';
1070
1071   my $oldAutoCommit = $FS::UID::AutoCommit;
1072   local $FS::UID::AutoCommit = 0;
1073   my $dbh = dbh;
1074
1075   unless ( ref($prepay_credit) ) {
1076
1077     my $identifier = $prepay_credit;
1078
1079     $prepay_credit = qsearchs(
1080       'prepay_credit',
1081       { 'identifier' => $prepay_credit },
1082       '',
1083       'FOR UPDATE'
1084     );
1085
1086     unless ( $prepay_credit ) {
1087       $dbh->rollback if $oldAutoCommit;
1088       return "Invalid prepaid card: ". $identifier;
1089     }
1090
1091   }
1092
1093   if ( $prepay_credit->agentnum ) {
1094     if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1095       $dbh->rollback if $oldAutoCommit;
1096       return "prepaid card not valid for agent ". $self->agentnum;
1097     }
1098     $self->agentnum($prepay_credit->agentnum);
1099   }
1100
1101   my $error = $prepay_credit->delete;
1102   if ( $error ) {
1103     $dbh->rollback if $oldAutoCommit;
1104     return "removing prepay_credit (transaction rolled back): $error";
1105   }
1106
1107   ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1108     for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1109
1110   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1111   '';
1112
1113 }
1114
1115 =item increment_upbytes SECONDS
1116
1117 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1118 the specified number of upbytes.  If there is an error, returns the error,
1119 otherwise returns false.
1120
1121 =cut
1122
1123 sub increment_upbytes {
1124   _increment_column( shift, 'upbytes', @_);
1125 }
1126
1127 =item increment_downbytes SECONDS
1128
1129 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1130 the specified number of downbytes.  If there is an error, returns the error,
1131 otherwise returns false.
1132
1133 =cut
1134
1135 sub increment_downbytes {
1136   _increment_column( shift, 'downbytes', @_);
1137 }
1138
1139 =item increment_totalbytes SECONDS
1140
1141 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1142 the specified number of totalbytes.  If there is an error, returns the error,
1143 otherwise returns false.
1144
1145 =cut
1146
1147 sub increment_totalbytes {
1148   _increment_column( shift, 'totalbytes', @_);
1149 }
1150
1151 =item increment_seconds SECONDS
1152
1153 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1154 the specified number of seconds.  If there is an error, returns the error,
1155 otherwise returns false.
1156
1157 =cut
1158
1159 sub increment_seconds {
1160   _increment_column( shift, 'seconds', @_);
1161 }
1162
1163 =item _increment_column AMOUNT
1164
1165 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1166 the specified number of seconds or bytes.  If there is an error, returns
1167 the error, otherwise returns false.
1168
1169 =cut
1170
1171 sub _increment_column {
1172   my( $self, $column, $amount ) = @_;
1173   warn "$me increment_column called: $column, $amount\n"
1174     if $DEBUG;
1175
1176   return '' unless $amount;
1177
1178   my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1179                       $self->ncancelled_pkgs;
1180
1181   if ( ! @cust_pkg ) {
1182     return 'No packages with primary or single services found'.
1183            ' to apply pre-paid time';
1184   } elsif ( scalar(@cust_pkg) > 1 ) {
1185     #maybe have a way to specify the package/account?
1186     return 'Multiple packages found to apply pre-paid time';
1187   }
1188
1189   my $cust_pkg = $cust_pkg[0];
1190   warn "  found package pkgnum ". $cust_pkg->pkgnum. "\n"
1191     if $DEBUG > 1;
1192
1193   my @cust_svc =
1194     $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1195
1196   if ( ! @cust_svc ) {
1197     return 'No account found to apply pre-paid time';
1198   } elsif ( scalar(@cust_svc) > 1 ) {
1199     return 'Multiple accounts found to apply pre-paid time';
1200   }
1201   
1202   my $svc_acct = $cust_svc[0]->svc_x;
1203   warn "  found service svcnum ". $svc_acct->pkgnum.
1204        ' ('. $svc_acct->email. ")\n"
1205     if $DEBUG > 1;
1206
1207   $column = "increment_$column";
1208   $svc_acct->$column($amount);
1209
1210 }
1211
1212 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1213
1214 Inserts a prepayment in the specified amount for this customer.  An optional
1215 second argument can specify the prepayment identifier for tracking purposes.
1216 If there is an error, returns the error, otherwise returns false.
1217
1218 =cut
1219
1220 sub insert_cust_pay_prepay {
1221   shift->insert_cust_pay('PREP', @_);
1222 }
1223
1224 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1225
1226 Inserts a cash payment in the specified amount for this customer.  An optional
1227 second argument can specify the payment identifier for tracking purposes.
1228 If there is an error, returns the error, otherwise returns false.
1229
1230 =cut
1231
1232 sub insert_cust_pay_cash {
1233   shift->insert_cust_pay('CASH', @_);
1234 }
1235
1236 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1237
1238 Inserts a Western Union payment in the specified amount for this customer.  An
1239 optional second argument can specify the prepayment identifier for tracking
1240 purposes.  If there is an error, returns the error, otherwise returns false.
1241
1242 =cut
1243
1244 sub insert_cust_pay_west {
1245   shift->insert_cust_pay('WEST', @_);
1246 }
1247
1248 sub insert_cust_pay {
1249   my( $self, $payby, $amount ) = splice(@_, 0, 3);
1250   my $payinfo = scalar(@_) ? shift : '';
1251
1252   my $cust_pay = new FS::cust_pay {
1253     'custnum' => $self->custnum,
1254     'paid'    => sprintf('%.2f', $amount),
1255     #'_date'   => #date the prepaid card was purchased???
1256     'payby'   => $payby,
1257     'payinfo' => $payinfo,
1258   };
1259   $cust_pay->insert;
1260
1261 }
1262
1263 =item reexport
1264
1265 This method is deprecated.  See the I<depend_jobnum> option to the insert and
1266 order_pkgs methods for a better way to defer provisioning.
1267
1268 Re-schedules all exports by calling the B<reexport> method of all associated
1269 packages (see L<FS::cust_pkg>).  If there is an error, returns the error;
1270 otherwise returns false.
1271
1272 =cut
1273
1274 sub reexport {
1275   my $self = shift;
1276
1277   carp "WARNING: FS::cust_main::reexport is deprectated; ".
1278        "use the depend_jobnum option to insert or order_pkgs to delay export";
1279
1280   local $SIG{HUP} = 'IGNORE';
1281   local $SIG{INT} = 'IGNORE';
1282   local $SIG{QUIT} = 'IGNORE';
1283   local $SIG{TERM} = 'IGNORE';
1284   local $SIG{TSTP} = 'IGNORE';
1285   local $SIG{PIPE} = 'IGNORE';
1286
1287   my $oldAutoCommit = $FS::UID::AutoCommit;
1288   local $FS::UID::AutoCommit = 0;
1289   my $dbh = dbh;
1290
1291   foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1292     my $error = $cust_pkg->reexport;
1293     if ( $error ) {
1294       $dbh->rollback if $oldAutoCommit;
1295       return $error;
1296     }
1297   }
1298
1299   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1300   '';
1301
1302 }
1303
1304 =item delete [ OPTION => VALUE ... ]
1305
1306 This deletes the customer.  If there is an error, returns the error, otherwise
1307 returns false.
1308
1309 This will completely remove all traces of the customer record.  This is not
1310 what you want when a customer cancels service; for that, cancel all of the
1311 customer's packages (see L</cancel>).
1312
1313 If the customer has any uncancelled packages, you need to pass a new (valid)
1314 customer number for those packages to be transferred to, as the "new_customer"
1315 option.  Cancelled packages will be deleted.  Did I mention that this is NOT
1316 what you want when a customer cancels service and that you really should be
1317 looking at L<FS::cust_pkg/cancel>?  
1318
1319 You can't delete a customer with invoices (see L<FS::cust_bill>),
1320 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1321 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1322 set the "delete_financials" option to a true value.
1323
1324 =cut
1325
1326 sub delete {
1327   my( $self, %opt ) = @_;
1328
1329   local $SIG{HUP} = 'IGNORE';
1330   local $SIG{INT} = 'IGNORE';
1331   local $SIG{QUIT} = 'IGNORE';
1332   local $SIG{TERM} = 'IGNORE';
1333   local $SIG{TSTP} = 'IGNORE';
1334   local $SIG{PIPE} = 'IGNORE';
1335
1336   my $oldAutoCommit = $FS::UID::AutoCommit;
1337   local $FS::UID::AutoCommit = 0;
1338   my $dbh = dbh;
1339
1340   if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1341      $dbh->rollback if $oldAutoCommit;
1342      return "Can't delete a master agent customer";
1343   }
1344
1345   #use FS::access_user
1346   if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1347      $dbh->rollback if $oldAutoCommit;
1348      return "Can't delete a master employee customer";
1349   }
1350
1351   tie my %financial_tables, 'Tie::IxHash',
1352     'cust_bill'      => 'invoices',
1353     'cust_statement' => 'statements',
1354     'cust_credit'    => 'credits',
1355     'cust_pay'       => 'payments',
1356     'cust_refund'    => 'refunds',
1357   ;
1358    
1359   foreach my $table ( keys %financial_tables ) {
1360
1361     my @records = $self->$table();
1362
1363     if ( @records && ! $opt{'delete_financials'} ) {
1364       $dbh->rollback if $oldAutoCommit;
1365       return "Can't delete a customer with ". $financial_tables{$table};
1366     }
1367
1368     foreach my $record ( @records ) {
1369       my $error = $record->delete;
1370       if ( $error ) {
1371         $dbh->rollback if $oldAutoCommit;
1372         return "Error deleting ". $financial_tables{$table}. ": $error\n";
1373       }
1374     }
1375
1376   }
1377
1378   my @cust_pkg = $self->ncancelled_pkgs;
1379   if ( @cust_pkg ) {
1380     my $new_custnum = $opt{'new_custnum'};
1381     unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1382       $dbh->rollback if $oldAutoCommit;
1383       return "Invalid new customer number: $new_custnum";
1384     }
1385     foreach my $cust_pkg ( @cust_pkg ) {
1386       my %hash = $cust_pkg->hash;
1387       $hash{'custnum'} = $new_custnum;
1388       my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1389       my $error = $new_cust_pkg->replace($cust_pkg,
1390                                          options => { $cust_pkg->options },
1391                                         );
1392       if ( $error ) {
1393         $dbh->rollback if $oldAutoCommit;
1394         return $error;
1395       }
1396     }
1397   }
1398   my @cancelled_cust_pkg = $self->all_pkgs;
1399   foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1400     my $error = $cust_pkg->delete;
1401     if ( $error ) {
1402       $dbh->rollback if $oldAutoCommit;
1403       return $error;
1404     }
1405   }
1406
1407   #cust_tax_adjustment in financials?
1408   #cust_pay_pending?  ouch
1409   #cust_recon?
1410   foreach my $table (qw(
1411     cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1412     cust_location cust_main_note cust_tax_adjustment
1413     cust_pay_void cust_pay_batch queue cust_tax_exempt
1414   )) {
1415     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1416       my $error = $record->delete;
1417       if ( $error ) {
1418         $dbh->rollback if $oldAutoCommit;
1419         return $error;
1420       }
1421     }
1422   }
1423
1424   my $sth = $dbh->prepare(
1425     'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1426   ) or do {
1427     my $errstr = $dbh->errstr;
1428     $dbh->rollback if $oldAutoCommit;
1429     return $errstr;
1430   };
1431   $sth->execute($self->custnum) or do {
1432     my $errstr = $sth->errstr;
1433     $dbh->rollback if $oldAutoCommit;
1434     return $errstr;
1435   };
1436
1437   #tickets
1438
1439   my $ticket_dbh = '';
1440   if ($conf->config('ticket_system') eq 'RT_Internal') {
1441     $ticket_dbh = $dbh;
1442   } elsif ($conf->config('ticket_system') eq 'RT_External') {
1443     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1444     $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1445       #or die "RT_External DBI->connect error: $DBI::errstr\n";
1446   }
1447
1448   if ( $ticket_dbh ) {
1449
1450     my $ticket_sth = $ticket_dbh->prepare(
1451       'DELETE FROM Links WHERE Target = ?'
1452     ) or do {
1453       my $errstr = $ticket_dbh->errstr;
1454       $dbh->rollback if $oldAutoCommit;
1455       return $errstr;
1456     };
1457     $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1458       or do {
1459         my $errstr = $ticket_sth->errstr;
1460         $dbh->rollback if $oldAutoCommit;
1461         return $errstr;
1462       };
1463
1464     #check and see if the customer is the only link on the ticket, and
1465     #if so, set the ticket to deleted status in RT?
1466     #maybe someday, for now this will at least fix tickets not displaying
1467
1468   }
1469
1470   #delete the customer record
1471
1472   my $error = $self->SUPER::delete;
1473   if ( $error ) {
1474     $dbh->rollback if $oldAutoCommit;
1475     return $error;
1476   }
1477
1478   # cust_main exports!
1479
1480   #my $export_args = $options{'export_args'} || [];
1481
1482   my @part_export =
1483     map qsearch( 'part_export', {exportnum=>$_} ),
1484       $conf->config('cust_main-exports'); #, $agentnum
1485
1486   foreach my $part_export ( @part_export ) {
1487     my $error = $part_export->export_delete( $self ); #, @$export_args);
1488     if ( $error ) {
1489       $dbh->rollback if $oldAutoCommit;
1490       return "exporting to ". $part_export->exporttype.
1491              " (transaction rolled back): $error";
1492     }
1493   }
1494
1495   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1496   '';
1497
1498 }
1499
1500 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1501
1502
1503 Replaces the OLD_RECORD with this one in the database.  If there is an error,
1504 returns the error, otherwise returns false.
1505
1506 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1507 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
1508 expected and rollback the entire transaction; it is not necessary to call 
1509 check_invoicing_list first.  Here's an example:
1510
1511   $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1512
1513 Currently available options are: I<tax_exemption>.
1514
1515 The I<tax_exemption> option can be set to an arrayref of tax names.
1516 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1517
1518 =cut
1519
1520 sub replace {
1521   my $self = shift;
1522
1523   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1524               ? shift
1525               : $self->replace_old;
1526
1527   my @param = @_;
1528
1529   warn "$me replace called\n"
1530     if $DEBUG;
1531
1532   my $curuser = $FS::CurrentUser::CurrentUser;
1533   if (    $self->payby eq 'COMP'
1534        && $self->payby ne $old->payby
1535        && ! $curuser->access_right('Complimentary customer')
1536      )
1537   {
1538     return "You are not permitted to create complimentary accounts.";
1539   }
1540
1541   local($ignore_expired_card) = 1
1542     if $old->payby  =~ /^(CARD|DCRD)$/
1543     && $self->payby =~ /^(CARD|DCRD)$/
1544     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1545
1546   local $SIG{HUP} = 'IGNORE';
1547   local $SIG{INT} = 'IGNORE';
1548   local $SIG{QUIT} = 'IGNORE';
1549   local $SIG{TERM} = 'IGNORE';
1550   local $SIG{TSTP} = 'IGNORE';
1551   local $SIG{PIPE} = 'IGNORE';
1552
1553   my $oldAutoCommit = $FS::UID::AutoCommit;
1554   local $FS::UID::AutoCommit = 0;
1555   my $dbh = dbh;
1556
1557   my $error = $self->SUPER::replace($old);
1558
1559   if ( $error ) {
1560     $dbh->rollback if $oldAutoCommit;
1561     return $error;
1562   }
1563
1564   if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1565     my $invoicing_list = shift @param;
1566     $error = $self->check_invoicing_list( $invoicing_list );
1567     if ( $error ) {
1568       $dbh->rollback if $oldAutoCommit;
1569       return $error;
1570     }
1571     $self->invoicing_list( $invoicing_list );
1572   }
1573
1574   if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1575
1576     #this could be more efficient than deleting and re-inserting, if it matters
1577     foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1578       my $error = $cust_tag->delete;
1579       if ( $error ) {
1580         $dbh->rollback if $oldAutoCommit;
1581         return $error;
1582       }
1583     }
1584     foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1585       my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
1586                                         'custnum' => $self->custnum };
1587       my $error = $cust_tag->insert;
1588       if ( $error ) {
1589         $dbh->rollback if $oldAutoCommit;
1590         return $error;
1591       }
1592     }
1593
1594   }
1595
1596   my %options = @param;
1597
1598   my $tax_exemption = delete $options{'tax_exemption'};
1599   if ( $tax_exemption ) {
1600
1601     my %cust_main_exemption =
1602       map { $_->taxname => $_ }
1603           qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1604
1605     foreach my $taxname ( @$tax_exemption ) {
1606
1607       next if delete $cust_main_exemption{$taxname};
1608
1609       my $cust_main_exemption = new FS::cust_main_exemption {
1610         'custnum' => $self->custnum,
1611         'taxname' => $taxname,
1612       };
1613       my $error = $cust_main_exemption->insert;
1614       if ( $error ) {
1615         $dbh->rollback if $oldAutoCommit;
1616         return "inserting cust_main_exemption (transaction rolled back): $error";
1617       }
1618     }
1619
1620     foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1621       my $error = $cust_main_exemption->delete;
1622       if ( $error ) {
1623         $dbh->rollback if $oldAutoCommit;
1624         return "deleting cust_main_exemption (transaction rolled back): $error";
1625       }
1626     }
1627
1628   }
1629
1630   if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1631        && ( ( $self->get('payinfo') ne $old->get('payinfo')
1632               && $self->get('payinfo') !~ /^99\d{14}$/ 
1633             )
1634             || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1635           )
1636      )
1637   {
1638
1639     # card/check/lec info has changed, want to retry realtime_ invoice events
1640     my $error = $self->retry_realtime;
1641     if ( $error ) {
1642       $dbh->rollback if $oldAutoCommit;
1643       return $error;
1644     }
1645   }
1646
1647   unless ( $import || $skip_fuzzyfiles ) {
1648     $error = $self->queue_fuzzyfiles_update;
1649     if ( $error ) {
1650       $dbh->rollback if $oldAutoCommit;
1651       return "updating fuzzy search cache: $error";
1652     }
1653   }
1654
1655   # cust_main exports!
1656
1657   my $export_args = $options{'export_args'} || [];
1658
1659   my @part_export =
1660     map qsearch( 'part_export', {exportnum=>$_} ),
1661       $conf->config('cust_main-exports'); #, $agentnum
1662
1663   foreach my $part_export ( @part_export ) {
1664     my $error = $part_export->export_replace( $self, $old, @$export_args);
1665     if ( $error ) {
1666       $dbh->rollback if $oldAutoCommit;
1667       return "exporting to ". $part_export->exporttype.
1668              " (transaction rolled back): $error";
1669     }
1670   }
1671
1672   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1673   '';
1674
1675 }
1676
1677 =item queue_fuzzyfiles_update
1678
1679 Used by insert & replace to update the fuzzy search cache
1680
1681 =cut
1682
1683 sub queue_fuzzyfiles_update {
1684   my $self = shift;
1685
1686   local $SIG{HUP} = 'IGNORE';
1687   local $SIG{INT} = 'IGNORE';
1688   local $SIG{QUIT} = 'IGNORE';
1689   local $SIG{TERM} = 'IGNORE';
1690   local $SIG{TSTP} = 'IGNORE';
1691   local $SIG{PIPE} = 'IGNORE';
1692
1693   my $oldAutoCommit = $FS::UID::AutoCommit;
1694   local $FS::UID::AutoCommit = 0;
1695   my $dbh = dbh;
1696
1697   my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1698   my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1699   if ( $error ) {
1700     $dbh->rollback if $oldAutoCommit;
1701     return "queueing job (transaction rolled back): $error";
1702   }
1703
1704   if ( $self->ship_last ) {
1705     $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1706     $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1707     if ( $error ) {
1708       $dbh->rollback if $oldAutoCommit;
1709       return "queueing job (transaction rolled back): $error";
1710     }
1711   }
1712
1713   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1714   '';
1715
1716 }
1717
1718 =item check
1719
1720 Checks all fields to make sure this is a valid customer record.  If there is
1721 an error, returns the error, otherwise returns false.  Called by the insert
1722 and replace methods.
1723
1724 =cut
1725
1726 sub check {
1727   my $self = shift;
1728
1729   warn "$me check BEFORE: \n". $self->_dump
1730     if $DEBUG > 2;
1731
1732   my $error =
1733     $self->ut_numbern('custnum')
1734     || $self->ut_number('agentnum')
1735     || $self->ut_textn('agent_custid')
1736     || $self->ut_number('refnum')
1737     || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1738     || $self->ut_textn('custbatch')
1739     || $self->ut_name('last')
1740     || $self->ut_name('first')
1741     || $self->ut_snumbern('birthdate')
1742     || $self->ut_snumbern('signupdate')
1743     || $self->ut_textn('company')
1744     || $self->ut_text('address1')
1745     || $self->ut_textn('address2')
1746     || $self->ut_text('city')
1747     || $self->ut_textn('county')
1748     || $self->ut_textn('state')
1749     || $self->ut_country('country')
1750     || $self->ut_anything('comments')
1751     || $self->ut_numbern('referral_custnum')
1752     || $self->ut_textn('stateid')
1753     || $self->ut_textn('stateid_state')
1754     || $self->ut_textn('invoice_terms')
1755     || $self->ut_alphan('geocode')
1756     || $self->ut_floatn('cdr_termination_percentage')
1757   ;
1758
1759   #barf.  need message catalogs.  i18n.  etc.
1760   $error .= "Please select an advertising source."
1761     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1762   return $error if $error;
1763
1764   return "Unknown agent"
1765     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1766
1767   return "Unknown refnum"
1768     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1769
1770   return "Unknown referring custnum: ". $self->referral_custnum
1771     unless ! $self->referral_custnum 
1772            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1773
1774   if ( $self->censustract ne '' ) {
1775     $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1776       or return "Illegal census tract: ". $self->censustract;
1777     
1778     $self->censustract("$1.$2");
1779   }
1780
1781   if ( $self->ss eq '' ) {
1782     $self->ss('');
1783   } else {
1784     my $ss = $self->ss;
1785     $ss =~ s/\D//g;
1786     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1787       or return "Illegal social security number: ". $self->ss;
1788     $self->ss("$1-$2-$3");
1789   }
1790
1791
1792 # bad idea to disable, causes billing to fail because of no tax rates later
1793 # except we don't fail any more
1794   unless ( $import ) {
1795     unless ( qsearch('cust_main_county', {
1796       'country' => $self->country,
1797       'state'   => '',
1798      } ) ) {
1799       return "Unknown state/county/country: ".
1800         $self->state. "/". $self->county. "/". $self->country
1801         unless qsearch('cust_main_county',{
1802           'state'   => $self->state,
1803           'county'  => $self->county,
1804           'country' => $self->country,
1805         } );
1806     }
1807   }
1808
1809   $error =
1810     $self->ut_phonen('daytime', $self->country)
1811     || $self->ut_phonen('night', $self->country)
1812     || $self->ut_phonen('fax', $self->country)
1813     || $self->ut_zip('zip', $self->country)
1814   ;
1815   return $error if $error;
1816
1817   if ( $conf->exists('cust_main-require_phone')
1818        && ! length($self->daytime) && ! length($self->night)
1819      ) {
1820
1821     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1822                           ? 'Day Phone'
1823                           : FS::Msgcat::_gettext('daytime');
1824     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1825                         ? 'Night Phone'
1826                         : FS::Msgcat::_gettext('night');
1827   
1828     return "$daytime_label or $night_label is required"
1829   
1830   }
1831
1832   if ( $self->has_ship_address
1833        && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1834                         $self->addr_fields )
1835      )
1836   {
1837     my $error =
1838       $self->ut_name('ship_last')
1839       || $self->ut_name('ship_first')
1840       || $self->ut_textn('ship_company')
1841       || $self->ut_text('ship_address1')
1842       || $self->ut_textn('ship_address2')
1843       || $self->ut_text('ship_city')
1844       || $self->ut_textn('ship_county')
1845       || $self->ut_textn('ship_state')
1846       || $self->ut_country('ship_country')
1847     ;
1848     return $error if $error;
1849
1850     #false laziness with above
1851     unless ( qsearchs('cust_main_county', {
1852       'country' => $self->ship_country,
1853       'state'   => '',
1854      } ) ) {
1855       return "Unknown ship_state/ship_county/ship_country: ".
1856         $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1857         unless qsearch('cust_main_county',{
1858           'state'   => $self->ship_state,
1859           'county'  => $self->ship_county,
1860           'country' => $self->ship_country,
1861         } );
1862     }
1863     #eofalse
1864
1865     $error =
1866       $self->ut_phonen('ship_daytime', $self->ship_country)
1867       || $self->ut_phonen('ship_night', $self->ship_country)
1868       || $self->ut_phonen('ship_fax', $self->ship_country)
1869       || $self->ut_zip('ship_zip', $self->ship_country)
1870     ;
1871     return $error if $error;
1872
1873     return "Unit # is required."
1874       if $self->ship_address2 =~ /^\s*$/
1875       && $conf->exists('cust_main-require_address2');
1876
1877   } else { # ship_ info eq billing info, so don't store dup info in database
1878
1879     $self->setfield("ship_$_", '')
1880       foreach $self->addr_fields;
1881
1882     return "Unit # is required."
1883       if $self->address2 =~ /^\s*$/
1884       && $conf->exists('cust_main-require_address2');
1885
1886   }
1887
1888   #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1889   #  or return "Illegal payby: ". $self->payby;
1890   #$self->payby($1);
1891   FS::payby->can_payby($self->table, $self->payby)
1892     or return "Illegal payby: ". $self->payby;
1893
1894   $error =    $self->ut_numbern('paystart_month')
1895            || $self->ut_numbern('paystart_year')
1896            || $self->ut_numbern('payissue')
1897            || $self->ut_textn('paytype')
1898   ;
1899   return $error if $error;
1900
1901   if ( $self->payip eq '' ) {
1902     $self->payip('');
1903   } else {
1904     $error = $self->ut_ip('payip');
1905     return $error if $error;
1906   }
1907
1908   # If it is encrypted and the private key is not availaible then we can't
1909   # check the credit card.
1910   my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1911
1912   if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1913
1914     my $payinfo = $self->payinfo;
1915     $payinfo =~ s/\D//g;
1916     $payinfo =~ /^(\d{13,16})$/
1917       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1918     $payinfo = $1;
1919     $self->payinfo($payinfo);
1920     validate($payinfo)
1921       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1922
1923     return gettext('unknown_card_type')
1924       if $self->payinfo !~ /^99\d{14}$/ #token
1925       && cardtype($self->payinfo) eq "Unknown";
1926
1927     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1928     if ( $ban ) {
1929       return 'Banned credit card: banned on '.
1930              time2str('%a %h %o at %r', $ban->_date).
1931              ' by '. $ban->otaker.
1932              ' (ban# '. $ban->bannum. ')';
1933     }
1934
1935     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1936       if ( cardtype($self->payinfo) eq 'American Express card' ) {
1937         $self->paycvv =~ /^(\d{4})$/
1938           or return "CVV2 (CID) for American Express cards is four digits.";
1939         $self->paycvv($1);
1940       } else {
1941         $self->paycvv =~ /^(\d{3})$/
1942           or return "CVV2 (CVC2/CID) is three digits.";
1943         $self->paycvv($1);
1944       }
1945     } else {
1946       $self->paycvv('');
1947     }
1948
1949     my $cardtype = cardtype($payinfo);
1950     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1951
1952       return "Start date or issue number is required for $cardtype cards"
1953         unless $self->paystart_month && $self->paystart_year or $self->payissue;
1954
1955       return "Start month must be between 1 and 12"
1956         if $self->paystart_month
1957            and $self->paystart_month < 1 || $self->paystart_month > 12;
1958
1959       return "Start year must be 1990 or later"
1960         if $self->paystart_year
1961            and $self->paystart_year < 1990;
1962
1963       return "Issue number must be beween 1 and 99"
1964         if $self->payissue
1965           and $self->payissue < 1 || $self->payissue > 99;
1966
1967     } else {
1968       $self->paystart_month('');
1969       $self->paystart_year('');
1970       $self->payissue('');
1971     }
1972
1973   } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1974
1975     my $payinfo = $self->payinfo;
1976     $payinfo =~ s/[^\d\@]//g;
1977     if ( $conf->exists('echeck-nonus') ) {
1978       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1979       $payinfo = "$1\@$2";
1980     } else {
1981       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1982       $payinfo = "$1\@$2";
1983     }
1984     $self->payinfo($payinfo);
1985     $self->paycvv('');
1986
1987     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1988     if ( $ban ) {
1989       return 'Banned ACH account: banned on '.
1990              time2str('%a %h %o at %r', $ban->_date).
1991              ' by '. $ban->otaker.
1992              ' (ban# '. $ban->bannum. ')';
1993     }
1994
1995   } elsif ( $self->payby eq 'LECB' ) {
1996
1997     my $payinfo = $self->payinfo;
1998     $payinfo =~ s/\D//g;
1999     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2000     $payinfo = $1;
2001     $self->payinfo($payinfo);
2002     $self->paycvv('');
2003
2004   } elsif ( $self->payby eq 'BILL' ) {
2005
2006     $error = $self->ut_textn('payinfo');
2007     return "Illegal P.O. number: ". $self->payinfo if $error;
2008     $self->paycvv('');
2009
2010   } elsif ( $self->payby eq 'COMP' ) {
2011
2012     my $curuser = $FS::CurrentUser::CurrentUser;
2013     if (    ! $self->custnum
2014          && ! $curuser->access_right('Complimentary customer')
2015        )
2016     {
2017       return "You are not permitted to create complimentary accounts."
2018     }
2019
2020     $error = $self->ut_textn('payinfo');
2021     return "Illegal comp account issuer: ". $self->payinfo if $error;
2022     $self->paycvv('');
2023
2024   } elsif ( $self->payby eq 'PREPAY' ) {
2025
2026     my $payinfo = $self->payinfo;
2027     $payinfo =~ s/\W//g; #anything else would just confuse things
2028     $self->payinfo($payinfo);
2029     $error = $self->ut_alpha('payinfo');
2030     return "Illegal prepayment identifier: ". $self->payinfo if $error;
2031     return "Unknown prepayment identifier"
2032       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2033     $self->paycvv('');
2034
2035   }
2036
2037   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2038     return "Expiration date required"
2039       unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2040     $self->paydate('');
2041   } else {
2042     my( $m, $y );
2043     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2044       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2045     } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2046       ( $m, $y ) = ( $2, "19$1" );
2047     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2048       ( $m, $y ) = ( $3, "20$2" );
2049     } else {
2050       return "Illegal expiration date: ". $self->paydate;
2051     }
2052     $self->paydate("$y-$m-01");
2053     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2054     return gettext('expired_card')
2055       if !$import
2056       && !$ignore_expired_card 
2057       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2058   }
2059
2060   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2061        ( ! $conf->exists('require_cardname')
2062          || $self->payby !~ /^(CARD|DCRD)$/  ) 
2063   ) {
2064     $self->payname( $self->first. " ". $self->getfield('last') );
2065   } else {
2066     $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2067       or return gettext('illegal_name'). " payname: ". $self->payname;
2068     $self->payname($1);
2069   }
2070
2071   foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2072     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2073     $self->$flag($1);
2074   }
2075
2076   $self->otaker(getotaker) unless $self->otaker;
2077
2078   warn "$me check AFTER: \n". $self->_dump
2079     if $DEBUG > 2;
2080
2081   $self->SUPER::check;
2082 }
2083
2084 =item addr_fields 
2085
2086 Returns a list of fields which have ship_ duplicates.
2087
2088 =cut
2089
2090 sub addr_fields {
2091   qw( last first company
2092       address1 address2 city county state zip country
2093       daytime night fax
2094     );
2095 }
2096
2097 =item has_ship_address
2098
2099 Returns true if this customer record has a separate shipping address.
2100
2101 =cut
2102
2103 sub has_ship_address {
2104   my $self = shift;
2105   scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2106 }
2107
2108 =item location_hash
2109
2110 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2111 city, county, state, zip, country.  The shipping address is used if present.
2112
2113 =cut
2114
2115 #geocode?  dependent on tax-ship_address config, not available in cust_location
2116 #mostly.  not yet then.
2117
2118 sub location_hash {
2119   my $self = shift;
2120   my $prefix = $self->has_ship_address ? 'ship_' : '';
2121
2122   map { $_ => $self->get($prefix.$_) }
2123       qw( address1 address2 city county state zip country geocode );
2124       #fields that cust_location has
2125 }
2126
2127 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2128
2129 Returns all packages (see L<FS::cust_pkg>) for this customer.
2130
2131 =cut
2132
2133 sub all_pkgs {
2134   my $self = shift;
2135   my $extra_qsearch = ref($_[0]) ? shift : {};
2136
2137   return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
2138
2139   my @cust_pkg = ();
2140   if ( $self->{'_pkgnum'} ) {
2141     @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2142   } else {
2143     @cust_pkg = $self->_cust_pkg($extra_qsearch);
2144   }
2145
2146   sort sort_packages @cust_pkg;
2147 }
2148
2149 =item cust_pkg
2150
2151 Synonym for B<all_pkgs>.
2152
2153 =cut
2154
2155 sub cust_pkg {
2156   shift->all_pkgs(@_);
2157 }
2158
2159 =item cust_location
2160
2161 Returns all locations (see L<FS::cust_location>) for this customer.
2162
2163 =cut
2164
2165 sub cust_location {
2166   my $self = shift;
2167   qsearch('cust_location', { 'custnum' => $self->custnum } );
2168 }
2169
2170 =item location_label [ OPTION => VALUE ... ]
2171
2172 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2173
2174 Options are
2175
2176 =over 4
2177
2178 =item join_string
2179
2180 used to separate the address elements (defaults to ', ')
2181
2182 =item escape_function
2183
2184 a callback used for escaping the text of the address elements
2185
2186 =back
2187
2188 =cut
2189
2190 # false laziness with FS::cust_location::line
2191
2192 sub location_label {
2193   my $self = shift;
2194   my %opt = @_;
2195
2196   my $separator = $opt{join_string} || ', ';
2197   my $escape = $opt{escape_function} || sub{ shift };
2198   my $line = '';
2199   my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2200   my $prefix = length($self->ship_last) ? 'ship_' : '';
2201
2202   my $notfirst = 0;
2203   foreach (qw ( address1 address2 ) ) {
2204     my $method = "$prefix$_";
2205     $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2206       if $self->$method;
2207     $notfirst++;
2208   }
2209   $notfirst = 0;
2210   foreach (qw ( city county state zip ) ) {
2211     my $method = "$prefix$_";
2212     if ( $self->$method ) {
2213       $line .= ' (' if $method eq 'county';
2214       $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2215       $line .= ' )' if $method eq 'county';
2216       $notfirst++;
2217     }
2218   }
2219   $line .= $separator. &$escape(code2country($self->country))
2220     if $self->country ne $cydefault;
2221
2222   $line;
2223 }
2224
2225 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2226
2227 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2228
2229 =cut
2230
2231 sub ncancelled_pkgs {
2232   my $self = shift;
2233   my $extra_qsearch = ref($_[0]) ? shift : {};
2234
2235   return $self->num_ncancelled_pkgs unless wantarray;
2236
2237   my @cust_pkg = ();
2238   if ( $self->{'_pkgnum'} ) {
2239
2240     warn "$me ncancelled_pkgs: returning cached objects"
2241       if $DEBUG > 1;
2242
2243     @cust_pkg = grep { ! $_->getfield('cancel') }
2244                 values %{ $self->{'_pkgnum'}->cache };
2245
2246   } else {
2247
2248     warn "$me ncancelled_pkgs: searching for packages with custnum ".
2249          $self->custnum. "\n"
2250       if $DEBUG > 1;
2251
2252     $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2253
2254     @cust_pkg = $self->_cust_pkg($extra_qsearch);
2255
2256   }
2257
2258   sort sort_packages @cust_pkg;
2259
2260 }
2261
2262 sub _cust_pkg {
2263   my $self = shift;
2264   my $extra_qsearch = ref($_[0]) ? shift : {};
2265
2266   $extra_qsearch->{'select'} ||= '*';
2267   $extra_qsearch->{'select'} .=
2268    ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2269      AS _num_cust_svc';
2270
2271   map {
2272         $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2273         $_;
2274       }
2275   qsearch({
2276     %$extra_qsearch,
2277     'table'   => 'cust_pkg',
2278     'hashref' => { 'custnum' => $self->custnum },
2279   });
2280
2281 }
2282
2283 # This should be generalized to use config options to determine order.
2284 sub sort_packages {
2285   
2286   my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2287   return $locationsort if $locationsort;
2288
2289   if ( $a->get('cancel') xor $b->get('cancel') ) {
2290     return -1 if $b->get('cancel');
2291     return  1 if $a->get('cancel');
2292     #shouldn't get here...
2293     return 0;
2294   } else {
2295     my $a_num_cust_svc = $a->num_cust_svc;
2296     my $b_num_cust_svc = $b->num_cust_svc;
2297     return 0  if !$a_num_cust_svc && !$b_num_cust_svc;
2298     return -1 if  $a_num_cust_svc && !$b_num_cust_svc;
2299     return 1  if !$a_num_cust_svc &&  $b_num_cust_svc;
2300     my @a_cust_svc = $a->cust_svc;
2301     my @b_cust_svc = $b->cust_svc;
2302     return 0  if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2303     return -1 if  scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2304     return 1  if !scalar(@a_cust_svc) &&  scalar(@b_cust_svc);
2305     $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2306   }
2307
2308 }
2309
2310 =item suspended_pkgs
2311
2312 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2313
2314 =cut
2315
2316 sub suspended_pkgs {
2317   my $self = shift;
2318   grep { $_->susp } $self->ncancelled_pkgs;
2319 }
2320
2321 =item unflagged_suspended_pkgs
2322
2323 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2324 customer (thouse packages without the `manual_flag' set).
2325
2326 =cut
2327
2328 sub unflagged_suspended_pkgs {
2329   my $self = shift;
2330   return $self->suspended_pkgs
2331     unless dbdef->table('cust_pkg')->column('manual_flag');
2332   grep { ! $_->manual_flag } $self->suspended_pkgs;
2333 }
2334
2335 =item unsuspended_pkgs
2336
2337 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2338 this customer.
2339
2340 =cut
2341
2342 sub unsuspended_pkgs {
2343   my $self = shift;
2344   grep { ! $_->susp } $self->ncancelled_pkgs;
2345 }
2346
2347 =item next_bill_date
2348
2349 Returns the next date this customer will be billed, as a UNIX timestamp, or
2350 undef if no active package has a next bill date.
2351
2352 =cut
2353
2354 sub next_bill_date {
2355   my $self = shift;
2356   min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2357 }
2358
2359 =item num_cancelled_pkgs
2360
2361 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2362 customer.
2363
2364 =cut
2365
2366 sub num_cancelled_pkgs {
2367   shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2368 }
2369
2370 sub num_ncancelled_pkgs {
2371   shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2372 }
2373
2374 sub num_pkgs {
2375   my( $self ) = shift;
2376   my $sql = scalar(@_) ? shift : '';
2377   $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2378   my $sth = dbh->prepare(
2379     "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2380   ) or die dbh->errstr;
2381   $sth->execute($self->custnum) or die $sth->errstr;
2382   $sth->fetchrow_arrayref->[0];
2383 }
2384
2385 =item unsuspend
2386
2387 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2388 and L<FS::cust_pkg>) for this customer.  Always returns a list: an empty list
2389 on success or a list of errors.
2390
2391 =cut
2392
2393 sub unsuspend {
2394   my $self = shift;
2395   grep { $_->unsuspend } $self->suspended_pkgs;
2396 }
2397
2398 =item suspend
2399
2400 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2401
2402 Returns a list: an empty list on success or a list of errors.
2403
2404 =cut
2405
2406 sub suspend {
2407   my $self = shift;
2408   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2409 }
2410
2411 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2412
2413 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2414 PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref instead
2415 of a list of pkgparts; the hashref has the following keys:
2416
2417 =over 4
2418
2419 =item pkgparts - listref of pkgparts
2420
2421 =item (other options are passed to the suspend method)
2422
2423 =back
2424
2425
2426 Returns a list: an empty list on success or a list of errors.
2427
2428 =cut
2429
2430 sub suspend_if_pkgpart {
2431   my $self = shift;
2432   my (@pkgparts, %opt);
2433   if (ref($_[0]) eq 'HASH'){
2434     @pkgparts = @{$_[0]{pkgparts}};
2435     %opt      = %{$_[0]};
2436   }else{
2437     @pkgparts = @_;
2438   }
2439   grep { $_->suspend(%opt) }
2440     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2441       $self->unsuspended_pkgs;
2442 }
2443
2444 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2445
2446 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2447 given PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref
2448 instead of a list of pkgparts; the hashref has the following keys:
2449
2450 =over 4
2451
2452 =item pkgparts - listref of pkgparts
2453
2454 =item (other options are passed to the suspend method)
2455
2456 =back
2457
2458 Returns a list: an empty list on success or a list of errors.
2459
2460 =cut
2461
2462 sub suspend_unless_pkgpart {
2463   my $self = shift;
2464   my (@pkgparts, %opt);
2465   if (ref($_[0]) eq 'HASH'){
2466     @pkgparts = @{$_[0]{pkgparts}};
2467     %opt      = %{$_[0]};
2468   }else{
2469     @pkgparts = @_;
2470   }
2471   grep { $_->suspend(%opt) }
2472     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2473       $self->unsuspended_pkgs;
2474 }
2475
2476 =item cancel [ OPTION => VALUE ... ]
2477
2478 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2479
2480 Available options are:
2481
2482 =over 4
2483
2484 =item quiet - can be set true to supress email cancellation notices.
2485
2486 =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.
2487
2488 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2489
2490 =item nobill - can be set true to skip billing if it might otherwise be done.
2491
2492 =back
2493
2494 Always returns a list: an empty list on success or a list of errors.
2495
2496 =cut
2497
2498 # nb that dates are not specified as valid options to this method
2499
2500 sub cancel {
2501   my( $self, %opt ) = @_;
2502
2503   warn "$me cancel called on customer ". $self->custnum. " with options ".
2504        join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2505     if $DEBUG;
2506
2507   return ( 'access denied' )
2508     unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2509
2510   if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2511
2512     #should try decryption (we might have the private key)
2513     # and if not maybe queue a job for the server that does?
2514     return ( "Can't (yet) ban encrypted credit cards" )
2515       if $self->is_encrypted($self->payinfo);
2516
2517     my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2518     my $error = $ban->insert;
2519     return ( $error ) if $error;
2520
2521   }
2522
2523   my @pkgs = $self->ncancelled_pkgs;
2524
2525   if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2526     $opt{nobill} = 1;
2527     my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2528     warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2529       if $error;
2530   }
2531
2532   warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2533        scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2534     if $DEBUG;
2535
2536   grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2537 }
2538
2539 sub _banned_pay_hashref {
2540   my $self = shift;
2541
2542   my %payby2ban = (
2543     'CARD' => 'CARD',
2544     'DCRD' => 'CARD',
2545     'CHEK' => 'CHEK',
2546     'DCHK' => 'CHEK'
2547   );
2548
2549   {
2550     'payby'   => $payby2ban{$self->payby},
2551     'payinfo' => md5_base64($self->payinfo),
2552     #don't ever *search* on reason! #'reason'  =>
2553   };
2554 }
2555
2556 =item notes
2557
2558 Returns all notes (see L<FS::cust_main_note>) for this customer.
2559
2560 =cut
2561
2562 sub notes {
2563   my $self = shift;
2564   #order by?
2565   qsearch( 'cust_main_note',
2566            { 'custnum' => $self->custnum },
2567            '',
2568            'ORDER BY _DATE DESC'
2569          );
2570 }
2571
2572 =item agent
2573
2574 Returns the agent (see L<FS::agent>) for this customer.
2575
2576 =cut
2577
2578 sub agent {
2579   my $self = shift;
2580   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2581 }
2582
2583 =item agent_name
2584
2585 Returns the agent name (see L<FS::agent>) for this customer.
2586
2587 =cut
2588
2589 sub agent_name {
2590   my $self = shift;
2591   $self->agent->agent;
2592 }
2593
2594 =item cust_tag
2595
2596 Returns any tags associated with this customer, as FS::cust_tag objects,
2597 or an empty list if there are no tags.
2598
2599 =cut
2600
2601 sub cust_tag {
2602   my $self = shift;
2603   qsearch('cust_tag', { 'custnum' => $self->custnum } );
2604 }
2605
2606 =item part_tag
2607
2608 Returns any tags associated with this customer, as FS::part_tag objects,
2609 or an empty list if there are no tags.
2610
2611 =cut
2612
2613 sub part_tag {
2614   my $self = shift;
2615   map $_->part_tag, $self->cust_tag; 
2616 }
2617
2618
2619 =item cust_class
2620
2621 Returns the customer class, as an FS::cust_class object, or the empty string
2622 if there is no customer class.
2623
2624 =cut
2625
2626 sub cust_class {
2627   my $self = shift;
2628   if ( $self->classnum ) {
2629     qsearchs('cust_class', { 'classnum' => $self->classnum } );
2630   } else {
2631     return '';
2632   } 
2633 }
2634
2635 =item categoryname 
2636
2637 Returns the customer category name, or the empty string if there is no customer
2638 category.
2639
2640 =cut
2641
2642 sub categoryname {
2643   my $self = shift;
2644   my $cust_class = $self->cust_class;
2645   $cust_class
2646     ? $cust_class->categoryname
2647     : '';
2648 }
2649
2650 =item classname 
2651
2652 Returns the customer class name, or the empty string if there is no customer
2653 class.
2654
2655 =cut
2656
2657 sub classname {
2658   my $self = shift;
2659   my $cust_class = $self->cust_class;
2660   $cust_class
2661     ? $cust_class->classname
2662     : '';
2663 }
2664
2665
2666 =item bill_and_collect 
2667
2668 Cancels and suspends any packages due, generates bills, applies payments and
2669 credits, and applies collection events to run cards, send bills and notices,
2670 etc.
2671
2672 By default, warns on errors and continues with the next operation (but see the
2673 "fatal" flag below).
2674
2675 Options are passed as name-value pairs.  Currently available options are:
2676
2677 =over 4
2678
2679 =item time
2680
2681 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:
2682
2683  use Date::Parse;
2684  ...
2685  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2686
2687 =item invoice_time
2688
2689 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.
2690
2691 =item check_freq
2692
2693 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2694
2695 =item resetup
2696
2697 If set true, re-charges setup fees.
2698
2699 =item fatal
2700
2701 If set any errors prevent subsequent operations from continusing.  If set
2702 specifically to "return", returns the error (or false, if there is no error).
2703 Any other true value causes errors to die.
2704
2705 =item debug
2706
2707 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)
2708
2709 =item job
2710
2711 Optional FS::queue entry to receive status updates.
2712
2713 =back
2714
2715 Options are passed to the B<bill> and B<collect> methods verbatim, so all
2716 options of those methods are also available.
2717
2718 =cut
2719
2720 sub bill_and_collect {
2721   my( $self, %options ) = @_;
2722
2723   my $error;
2724
2725   #$options{actual_time} not $options{time} because freeside-daily -d is for
2726   #pre-printing invoices
2727
2728   $options{'actual_time'} ||= time;
2729   my $job = $options{'job'};
2730
2731   $job->update_statustext('0,cleaning expired packages') if $job;
2732   $error = $self->cancel_expired_pkgs( $options{actual_time} );
2733   if ( $error ) {
2734     $error = "Error expiring custnum ". $self->custnum. ": $error";
2735     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2736     elsif ( $options{fatal}                                ) { die    $error; }
2737     else                                                     { warn   $error; }
2738   }
2739
2740   $error = $self->suspend_adjourned_pkgs( $options{actual_time} );
2741   if ( $error ) {
2742     $error = "Error adjourning custnum ". $self->custnum. ": $error";
2743     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2744     elsif ( $options{fatal}                                ) { die    $error; }
2745     else                                                     { warn   $error; }
2746   }
2747
2748   $job->update_statustext('20,billing packages') if $job;
2749   $error = $self->bill( %options );
2750   if ( $error ) {
2751     $error = "Error billing custnum ". $self->custnum. ": $error";
2752     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2753     elsif ( $options{fatal}                                ) { die    $error; }
2754     else                                                     { warn   $error; }
2755   }
2756
2757   $job->update_statustext('50,applying payments and credits') if $job;
2758   $error = $self->apply_payments_and_credits;
2759   if ( $error ) {
2760     $error = "Error applying custnum ". $self->custnum. ": $error";
2761     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
2762     elsif ( $options{fatal}                                ) { die    $error; }
2763     else                                                     { warn   $error; }
2764   }
2765
2766   $job->update_statustext('70,running collection events') if $job;
2767   unless ( $conf->exists('cancelled_cust-noevents')
2768            && ! $self->num_ncancelled_pkgs
2769   ) {
2770     $error = $self->collect( %options );
2771     if ( $error ) {
2772       $error = "Error collecting custnum ". $self->custnum. ": $error";
2773       if    ($options{fatal} && $options{fatal} eq 'return') { return $error; }
2774       elsif ($options{fatal}                               ) { die    $error; }
2775       else                                                   { warn   $error; }
2776     }
2777   }
2778   $job->update_statustext('100,finished') if $job;
2779
2780   '';
2781
2782 }
2783
2784 sub cancel_expired_pkgs {
2785   my ( $self, $time, %options ) = @_;
2786
2787   my @cancel_pkgs = $self->ncancelled_pkgs( { 
2788     'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
2789   } );
2790
2791   my @errors = ();
2792
2793   foreach my $cust_pkg ( @cancel_pkgs ) {
2794     my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
2795     my $error = $cust_pkg->cancel($cpr ? ( 'reason'        => $cpr->reasonnum,
2796                                            'reason_otaker' => $cpr->otaker
2797                                          )
2798                                        : ()
2799                                  );
2800     push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2801   }
2802
2803   scalar(@errors) ? join(' / ', @errors) : '';
2804
2805 }
2806
2807 sub suspend_adjourned_pkgs {
2808   my ( $self, $time, %options ) = @_;
2809
2810   my @susp_pkgs = $self->ncancelled_pkgs( {
2811     'extra_sql' =>
2812       " AND ( susp IS NULL OR susp = 0 )
2813         AND (    ( bill    IS NOT NULL AND bill    != 0 AND bill    <  $time )
2814               OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
2815             )
2816       ",
2817   } );
2818
2819   #only because there's no SQL test for is_prepaid :/
2820   @susp_pkgs = 
2821     grep {     (    $_->part_pkg->is_prepaid
2822                  && $_->bill
2823                  && $_->bill < $time
2824                )
2825             || (    $_->adjourn
2826                  && $_->adjourn <= $time
2827                )
2828            
2829          }
2830          @susp_pkgs;
2831
2832   my @errors = ();
2833
2834   foreach my $cust_pkg ( @susp_pkgs ) {
2835     my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
2836       if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
2837     my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
2838                                             'reason_otaker' => $cpr->otaker
2839                                           )
2840                                         : ()
2841                                   );
2842     push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
2843   }
2844
2845   scalar(@errors) ? join(' / ', @errors) : '';
2846
2847 }
2848
2849 =item bill OPTIONS
2850
2851 Generates invoices (see L<FS::cust_bill>) for this customer.  Usually used in
2852 conjunction with the collect method by calling B<bill_and_collect>.
2853
2854 If there is an error, returns the error, otherwise returns false.
2855
2856 Options are passed as name-value pairs.  Currently available options are:
2857
2858 =over 4
2859
2860 =item resetup
2861
2862 If set true, re-charges setup fees.
2863
2864 =item time
2865
2866 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:
2867
2868  use Date::Parse;
2869  ...
2870  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2871
2872 =item pkg_list
2873
2874 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2875
2876  $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2877
2878 =item not_pkgpart
2879
2880 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
2881
2882 =item invoice_time
2883
2884 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.
2885
2886 =item cancel
2887
2888 This boolean value informs the us that the package is being cancelled.  This
2889 typically might mean not charging the normal recurring fee but only usage
2890 fees since the last billing. Setup charges may be charged.  Not all package
2891 plans support this feature (they tend to charge 0).
2892
2893 =item invoice_terms
2894
2895 Optional terms to be printed on this invoice.  Otherwise, customer-specific
2896 terms or the default terms are used.
2897
2898 =back
2899
2900 =cut
2901
2902 sub bill {
2903   my( $self, %options ) = @_;
2904   return '' if $self->payby eq 'COMP';
2905   warn "$me bill customer ". $self->custnum. "\n"
2906     if $DEBUG;
2907
2908   my $time = $options{'time'} || time;
2909   my $invoice_time = $options{'invoice_time'} || $time;
2910
2911   $options{'not_pkgpart'} ||= {};
2912   $options{'not_pkgpart'} = { map { $_ => 1 }
2913                                   split(/\s*,\s*/, $options{'not_pkgpart'})
2914                             }
2915     unless ref($options{'not_pkgpart'});
2916
2917   local $SIG{HUP} = 'IGNORE';
2918   local $SIG{INT} = 'IGNORE';
2919   local $SIG{QUIT} = 'IGNORE';
2920   local $SIG{TERM} = 'IGNORE';
2921   local $SIG{TSTP} = 'IGNORE';
2922   local $SIG{PIPE} = 'IGNORE';
2923
2924   my $oldAutoCommit = $FS::UID::AutoCommit;
2925   local $FS::UID::AutoCommit = 0;
2926   my $dbh = dbh;
2927
2928   warn "$me acquiring lock on customer ". $self->custnum. "\n"
2929     if $DEBUG;
2930
2931   $self->select_for_update; #mutex
2932
2933   warn "$me running pre-bill events for customer ". $self->custnum. "\n"
2934     if $DEBUG;
2935
2936   my $error = $self->do_cust_event(
2937     'debug'      => ( $options{'debug'} || 0 ),
2938     'time'       => $invoice_time,
2939     'check_freq' => $options{'check_freq'},
2940     'stage'      => 'pre-bill',
2941   );
2942   if ( $error ) {
2943     $dbh->rollback if $oldAutoCommit;
2944     return $error;
2945   }
2946
2947   warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
2948     if $DEBUG;
2949
2950   #keep auto-charge and non-auto-charge line items separate
2951   my @passes = ( '', 'no_auto' );
2952
2953   my %cust_bill_pkg = map { $_ => [] } @passes;
2954
2955   ###
2956   # find the packages which are due for billing, find out how much they are
2957   # & generate invoice database.
2958   ###
2959
2960   my %total_setup   = map { my $z = 0; $_ => \$z; } @passes;
2961   my %total_recur   = map { my $z = 0; $_ => \$z; } @passes;
2962
2963   my %taxlisthash = map { $_ => {} } @passes;
2964
2965   my @precommit_hooks = ();
2966
2967   $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ];  #param checks?
2968   foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
2969
2970     next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
2971
2972     warn "  bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2973
2974     #? to avoid use of uninitialized value errors... ?
2975     $cust_pkg->setfield('bill', '')
2976       unless defined($cust_pkg->bill);
2977  
2978     #my $part_pkg = $cust_pkg->part_pkg;
2979
2980     my $real_pkgpart = $cust_pkg->pkgpart;
2981     my %hash = $cust_pkg->hash;
2982
2983     # we could implement this bit as FS::part_pkg::has_hidden, but we already
2984     # suffer from performance issues
2985     $options{has_hidden} = 0;
2986     my @part_pkg = $cust_pkg->part_pkg->self_and_bill_linked;
2987     $options{has_hidden} = 1 if ($part_pkg[1] && $part_pkg[1]->hidden);
2988  
2989     foreach my $part_pkg ( @part_pkg ) {
2990
2991       $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2992
2993       my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
2994
2995       my $error =
2996         $self->_make_lines( 'part_pkg'            => $part_pkg,
2997                             'cust_pkg'            => $cust_pkg,
2998                             'precommit_hooks'     => \@precommit_hooks,
2999                             'line_items'          => $cust_bill_pkg{$pass},
3000                             'setup'               => $total_setup{$pass},
3001                             'recur'               => $total_recur{$pass},
3002                             'tax_matrix'          => $taxlisthash{$pass},
3003                             'time'                => $time,
3004                             'real_pkgpart'        => $real_pkgpart,
3005                             'options'             => \%options,
3006                           );
3007       if ($error) {
3008         $dbh->rollback if $oldAutoCommit;
3009         return $error;
3010       }
3011
3012     } #foreach my $part_pkg
3013
3014   } #foreach my $cust_pkg
3015
3016   #if the customer isn't on an automatic payby, everything can go on a single
3017   #invoice anyway?
3018   #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
3019     #merge everything into one list
3020   #}
3021
3022   foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
3023
3024     my @cust_bill_pkg = _omit_zero_value_bundles(@{ $cust_bill_pkg{$pass} });
3025
3026     next unless @cust_bill_pkg; #don't create an invoice w/o line items
3027
3028     if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
3029            !$conf->exists('postal_invoice-recurring_only')
3030        )
3031     {
3032
3033       my $postal_pkg = $self->charge_postal_fee();
3034       if ( $postal_pkg && !ref( $postal_pkg ) ) {
3035
3036         $dbh->rollback if $oldAutoCommit;
3037         return "can't charge postal invoice fee for customer ".
3038           $self->custnum. ": $postal_pkg";
3039
3040       } elsif ( $postal_pkg ) {
3041
3042         my $real_pkgpart = $postal_pkg->pkgpart;
3043         # we could implement this bit as FS::part_pkg::has_hidden, but we already
3044         # suffer from performance issues
3045         $options{has_hidden} = 0;
3046         my @part_pkg = $postal_pkg->part_pkg->self_and_bill_linked;
3047         $options{has_hidden} = 1 if ($part_pkg[1] && $part_pkg[1]->hidden);
3048
3049         foreach my $part_pkg ( @part_pkg ) {
3050           my %postal_options = %options;
3051           delete $postal_options{cancel};
3052           my $error =
3053             $self->_make_lines( 'part_pkg'            => $part_pkg,
3054                                 'cust_pkg'            => $postal_pkg,
3055                                 'precommit_hooks'     => \@precommit_hooks,
3056                                 'line_items'          => \@cust_bill_pkg,
3057                                 'setup'               => $total_setup{$pass},
3058                                 'recur'               => $total_recur{$pass},
3059                                 'tax_matrix'          => $taxlisthash{$pass},
3060                                 'time'                => $time,
3061                                 'real_pkgpart'        => $real_pkgpart,
3062                                 'options'             => \%postal_options,
3063                               );
3064           if ($error) {
3065             $dbh->rollback if $oldAutoCommit;
3066             return $error;
3067           }
3068         }
3069
3070         # it's silly to have a zero value postal_pkg, but....
3071         @cust_bill_pkg = _omit_zero_value_bundles(@cust_bill_pkg);
3072
3073       }
3074
3075     }
3076
3077     my $listref_or_error =
3078       $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
3079
3080     unless ( ref( $listref_or_error ) ) {
3081       $dbh->rollback if $oldAutoCommit;
3082       return $listref_or_error;
3083     }
3084
3085     foreach my $taxline ( @$listref_or_error ) {
3086       ${ $total_setup{$pass} } =
3087         sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
3088       push @cust_bill_pkg, $taxline;
3089     }
3090
3091     #add tax adjustments
3092     warn "adding tax adjustments...\n" if $DEBUG > 2;
3093     foreach my $cust_tax_adjustment (
3094       qsearch('cust_tax_adjustment', { 'custnum'    => $self->custnum,
3095                                        'billpkgnum' => '',
3096                                      }
3097              )
3098     ) {
3099
3100       my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
3101
3102       my $itemdesc = $cust_tax_adjustment->taxname;
3103       $itemdesc = '' if $itemdesc eq 'Tax';
3104
3105       push @cust_bill_pkg, new FS::cust_bill_pkg {
3106         'pkgnum'      => 0,
3107         'setup'       => $tax,
3108         'recur'       => 0,
3109         'sdate'       => '',
3110         'edate'       => '',
3111         'itemdesc'    => $itemdesc,
3112         'itemcomment' => $cust_tax_adjustment->comment,
3113         'cust_tax_adjustment' => $cust_tax_adjustment,
3114         #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3115       };
3116
3117     }
3118
3119     my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
3120
3121     my @cust_bill = $self->cust_bill;
3122     my $balance = $self->balance;
3123     my $previous_balance = scalar(@cust_bill)
3124                              ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
3125                              : 0;
3126
3127     $previous_balance += $cust_bill[$#cust_bill]->charged
3128       if scalar(@cust_bill);
3129     #my $balance_adjustments =
3130     #  sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
3131
3132     #create the new invoice
3133     my $cust_bill = new FS::cust_bill ( {
3134       'custnum'             => $self->custnum,
3135       '_date'               => ( $invoice_time ),
3136       'charged'             => $charged,
3137       'billing_balance'     => $balance,
3138       'previous_balance'    => $previous_balance,
3139       'invoice_terms'       => $options{'invoice_terms'},
3140     } );
3141     $error = $cust_bill->insert;
3142     if ( $error ) {
3143       $dbh->rollback if $oldAutoCommit;
3144       return "can't create invoice for customer #". $self->custnum. ": $error";
3145     }
3146
3147     foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
3148       $cust_bill_pkg->invnum($cust_bill->invnum); 
3149       my $error = $cust_bill_pkg->insert;
3150       if ( $error ) {
3151         $dbh->rollback if $oldAutoCommit;
3152         return "can't create invoice line item: $error";
3153       }
3154     }
3155
3156   } #foreach my $pass ( keys %cust_bill_pkg )
3157
3158   foreach my $hook ( @precommit_hooks ) { 
3159     eval {
3160       &{$hook}; #($self) ?
3161     };
3162     if ( $@ ) {
3163       $dbh->rollback if $oldAutoCommit;
3164       return "$@ running precommit hook $hook\n";
3165     }
3166   }
3167   
3168   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3169   ''; #no error
3170 }
3171
3172 #discard bundled packages of 0 value
3173 sub _omit_zero_value_bundles {
3174
3175   my @cust_bill_pkg = ();
3176   my @cust_bill_pkg_bundle = ();
3177   my $sum = 0;
3178
3179   foreach my $cust_bill_pkg ( @_ ) {
3180     if (scalar(@cust_bill_pkg_bundle) && !$cust_bill_pkg->pkgpart_override) {
3181       push @cust_bill_pkg, @cust_bill_pkg_bundle if $sum > 0;
3182       @cust_bill_pkg_bundle = ();
3183       $sum = 0;
3184     }
3185     $sum += $cust_bill_pkg->setup + $cust_bill_pkg->recur;
3186     push @cust_bill_pkg_bundle, $cust_bill_pkg;
3187   }
3188   push @cust_bill_pkg, @cust_bill_pkg_bundle if $sum > 0;
3189
3190   (@cust_bill_pkg);
3191
3192 }
3193
3194 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
3195
3196 This is a weird one.  Perhaps it should not even be exposed.
3197
3198 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
3199 Usually used internally by bill method B<bill>.
3200
3201 If there is an error, returns the error, otherwise returns reference to a
3202 list of line items suitable for insertion.
3203
3204 =over 4
3205
3206 =item LINEITEMREF
3207
3208 An array ref of the line items being billed.
3209
3210 =item TAXHASHREF
3211
3212 A strange beast.  The keys to this hash are internal identifiers consisting
3213 of the name of the tax object type, a space, and its unique identifier ( e.g.
3214  'cust_main_county 23' ).  The values of the hash are listrefs.  The first
3215 item in the list is the tax object.  The remaining items are either line
3216 items or floating point values (currency amounts).
3217
3218 The taxes are calculated on this entity.  Calculated exemption records are
3219 transferred to the LINEITEMREF items on the assumption that they are related.
3220
3221 Read the source.
3222
3223 =item INVOICE_TIME
3224
3225 This specifies the date appearing on the associated invoice.  Some
3226 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
3227
3228 =back
3229
3230 =cut
3231 sub calculate_taxes {
3232   my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
3233
3234   my @tax_line_items = ();
3235
3236   warn "having a look at the taxes we found...\n" if $DEBUG > 2;
3237
3238   # keys are tax names (as printed on invoices / itemdesc )
3239   # values are listrefs of taxlisthash keys (internal identifiers)
3240   my %taxname = ();
3241
3242   # keys are taxlisthash keys (internal identifiers)
3243   # values are (cumulative) amounts
3244   my %tax = ();
3245
3246   # keys are taxlisthash keys (internal identifiers)
3247   # values are listrefs of cust_bill_pkg_tax_location hashrefs
3248   my %tax_location = ();
3249
3250   # keys are taxlisthash keys (internal identifiers)
3251   # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
3252   my %tax_rate_location = ();
3253
3254   foreach my $tax ( keys %$taxlisthash ) {
3255     my $tax_object = shift @{ $taxlisthash->{$tax} };
3256     warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
3257     warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
3258     my $hashref_or_error =
3259       $tax_object->taxline( $taxlisthash->{$tax},
3260                             'custnum'      => $self->custnum,
3261                             'invoice_time' => $invoice_time
3262                           );
3263     return $hashref_or_error unless ref($hashref_or_error);
3264
3265     unshift @{ $taxlisthash->{$tax} }, $tax_object;
3266
3267     my $name   = $hashref_or_error->{'name'};
3268     my $amount = $hashref_or_error->{'amount'};
3269
3270     #warn "adding $amount as $name\n";
3271     $taxname{ $name } ||= [];
3272     push @{ $taxname{ $name } }, $tax;
3273
3274     $tax{ $tax } += $amount;
3275
3276     $tax_location{ $tax } ||= [];
3277     if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
3278       push @{ $tax_location{ $tax }  },
3279         {
3280           'taxnum'      => $tax_object->taxnum, 
3281           'taxtype'     => ref($tax_object),
3282           'pkgnum'      => $tax_object->get('pkgnum'),
3283           'locationnum' => $tax_object->get('locationnum'),
3284           'amount'      => sprintf('%.2f', $amount ),
3285         };
3286     }
3287
3288     $tax_rate_location{ $tax } ||= [];
3289     if ( ref($tax_object) eq 'FS::tax_rate' ) {
3290       my $taxratelocationnum =
3291         $tax_object->tax_rate_location->taxratelocationnum;
3292       push @{ $tax_rate_location{ $tax }  },
3293         {
3294           'taxnum'             => $tax_object->taxnum, 
3295           'taxtype'            => ref($tax_object),
3296           'amount'             => sprintf('%.2f', $amount ),
3297           'locationtaxid'      => $tax_object->location,
3298           'taxratelocationnum' => $taxratelocationnum,
3299         };
3300     }
3301
3302   }
3303
3304   #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
3305   my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
3306   foreach my $tax ( keys %$taxlisthash ) {
3307     foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
3308       next unless ref($_) eq 'FS::cust_bill_pkg';
3309
3310       push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg }, 
3311         splice( @{ $_->_cust_tax_exempt_pkg } );
3312     }
3313   }
3314
3315   #consolidate and create tax line items
3316   warn "consolidating and generating...\n" if $DEBUG > 2;
3317   foreach my $taxname ( keys %taxname ) {
3318     my $tax = 0;
3319     my %seen = ();
3320     my @cust_bill_pkg_tax_location = ();
3321     my @cust_bill_pkg_tax_rate_location = ();
3322     warn "adding $taxname\n" if $DEBUG > 1;
3323     foreach my $taxitem ( @{ $taxname{$taxname} } ) {
3324       next if $seen{$taxitem}++;
3325       warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
3326       $tax += $tax{$taxitem};
3327       push @cust_bill_pkg_tax_location,
3328         map { new FS::cust_bill_pkg_tax_location $_ }
3329             @{ $tax_location{ $taxitem } };
3330       push @cust_bill_pkg_tax_rate_location,
3331         map { new FS::cust_bill_pkg_tax_rate_location $_ }
3332             @{ $tax_rate_location{ $taxitem } };
3333     }
3334     next unless $tax;
3335
3336     $tax = sprintf('%.2f', $tax );
3337   
3338     my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
3339                                                    'disabled'     => '',
3340                                                  },
3341                                );
3342
3343     my @display = ();
3344     if ( $pkg_category and
3345          $conf->config('invoice_latexsummary') ||
3346          $conf->config('invoice_htmlsummary')
3347        )
3348     {
3349
3350       my %hash = (  'section' => $pkg_category->categoryname );
3351       push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3352
3353     }
3354
3355     push @tax_line_items, new FS::cust_bill_pkg {
3356       'pkgnum'   => 0,
3357       'setup'    => $tax,
3358       'recur'    => 0,
3359       'sdate'    => '',
3360       'edate'    => '',
3361       'itemdesc' => $taxname,
3362       'display'  => \@display,
3363       'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
3364       'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
3365     };
3366
3367   }
3368
3369   \@tax_line_items;
3370 }
3371
3372 sub _make_lines {
3373   my ($self, %params) = @_;
3374
3375   my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
3376   my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
3377   my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
3378   my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
3379   my $total_setup = $params{setup} or die "no setup accumulator specified";
3380   my $total_recur = $params{recur} or die "no recur accumulator specified";
3381   my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
3382   my $time = $params{'time'} or die "no time specified";
3383   my (%options) = %{$params{options}};
3384
3385   my $dbh = dbh;
3386   my $real_pkgpart = $params{real_pkgpart};
3387   my %hash = $cust_pkg->hash;
3388   my $old_cust_pkg = new FS::cust_pkg \%hash;
3389
3390   my @details = ();
3391   my @discounts = ();
3392   my $lineitems = 0;
3393
3394   $cust_pkg->pkgpart($part_pkg->pkgpart);
3395
3396   ###
3397   # bill setup
3398   ###
3399
3400   my $setup = 0;
3401   my $unitsetup = 0;
3402   if ( $options{'resetup'}
3403        || ( ! $cust_pkg->setup
3404             && ( ! $cust_pkg->start_date
3405                  || $cust_pkg->start_date <= $time
3406                )
3407             && ( ! $conf->exists('disable_setup_suspended_pkgs')
3408                  || ( $conf->exists('disable_setup_suspended_pkgs') &&
3409                       ! $cust_pkg->getfield('susp')
3410                     )
3411                )
3412           )
3413     )
3414   {
3415     
3416     warn "    bill setup\n" if $DEBUG > 1;
3417     $lineitems++;
3418
3419     $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
3420     return "$@ running calc_setup for $cust_pkg\n"
3421       if $@;
3422
3423     $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
3424
3425     $cust_pkg->setfield('setup', $time)
3426       unless $cust_pkg->setup;
3427           #do need it, but it won't get written to the db
3428           #|| $cust_pkg->pkgpart != $real_pkgpart;
3429
3430     $cust_pkg->setfield('start_date', '')
3431       if $cust_pkg->start_date;
3432
3433   }
3434
3435   ###
3436   # bill recurring fee
3437   ### 
3438
3439   #XXX unit stuff here too
3440   my $recur = 0;
3441   my $unitrecur = 0;
3442   my $sdate;
3443   if (     ! $cust_pkg->get('susp')
3444        and ! $cust_pkg->get('start_date')
3445        and ( $part_pkg->getfield('freq') ne '0'
3446              && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3447            )
3448         || ( $part_pkg->plan eq 'voip_cdr'
3449               && $part_pkg->option('bill_every_call')
3450            )
3451         || ( $options{cancel} )
3452   ) {
3453
3454     # XXX should this be a package event?  probably.  events are called
3455     # at collection time at the moment, though...
3456     $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
3457       if $part_pkg->can('reset_usage');
3458       #don't want to reset usage just cause we want a line item??
3459       #&& $part_pkg->pkgpart == $real_pkgpart;
3460
3461     warn "    bill recur\n" if $DEBUG > 1;
3462     $lineitems++;
3463
3464     # XXX shared with $recur_prog
3465     $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
3466              || $cust_pkg->setup
3467              || $time;
3468
3469     #over two params!  lets at least switch to a hashref for the rest...
3470     my $increment_next_bill = ( $part_pkg->freq ne '0'
3471                                 && ( $cust_pkg->getfield('bill') || 0 ) <= $time
3472                                 && !$options{cancel}
3473                               );
3474     my %param = ( 'precommit_hooks'     => $precommit_hooks,
3475                   'increment_next_bill' => $increment_next_bill,
3476                   'discounts'           => \@discounts,
3477                   'real_pkgpart'        => $real_pkgpart,
3478                 );
3479
3480     my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
3481     $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
3482     return "$@ running $method for $cust_pkg\n"
3483       if ( $@ );
3484
3485     if ( $increment_next_bill ) {
3486
3487       my $next_bill = $part_pkg->add_freq($sdate);
3488       return "unparsable frequency: ". $part_pkg->freq
3489         if $next_bill == -1;
3490   
3491       #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
3492       # only for figuring next bill date, nothing else, so, reset $sdate again
3493       # here
3494       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
3495       #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
3496       $cust_pkg->last_bill($sdate);
3497
3498       $cust_pkg->setfield('bill', $next_bill );
3499
3500     }
3501
3502   }
3503
3504   warn "\$setup is undefined" unless defined($setup);
3505   warn "\$recur is undefined" unless defined($recur);
3506   warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
3507   
3508   ###
3509   # If there's line items, create em cust_bill_pkg records
3510   # If $cust_pkg has been modified, update it (if we're a real pkgpart)
3511   ###
3512
3513   if ( $lineitems || $options{has_hidden} ) {
3514
3515     if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
3516       # hmm.. and if just the options are modified in some weird price plan?
3517   
3518       warn "  package ". $cust_pkg->pkgnum. " modified; updating\n"
3519         if $DEBUG >1;
3520   
3521       my $error = $cust_pkg->replace( $old_cust_pkg,
3522                                       'options' => { $cust_pkg->options },
3523                                     );
3524       return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
3525         if $error; #just in case
3526     }
3527   
3528     $setup = sprintf( "%.2f", $setup );
3529     $recur = sprintf( "%.2f", $recur );
3530     if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
3531       return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
3532     }
3533     if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
3534       return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
3535     }
3536
3537     if ( $setup != 0 ||
3538          $recur != 0 ||
3539          !$part_pkg->hidden && $options{has_hidden} ) #include some $0 lines
3540     {
3541
3542       warn "    charges (setup=$setup, recur=$recur); adding line items\n"
3543         if $DEBUG > 1;
3544
3545       my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
3546       if ( $DEBUG > 1 ) {
3547         warn "      adding customer package invoice detail: $_\n"
3548           foreach @cust_pkg_detail;
3549       }
3550       push @details, @cust_pkg_detail;
3551
3552       my $cust_bill_pkg = new FS::cust_bill_pkg {
3553         'pkgnum'    => $cust_pkg->pkgnum,
3554         'setup'     => $setup,
3555         'unitsetup' => $unitsetup,
3556         'recur'     => $recur,
3557         'unitrecur' => $unitrecur,
3558         'quantity'  => $cust_pkg->quantity,
3559         'details'   => \@details,
3560         'discounts' => \@discounts,
3561         'hidden'    => $part_pkg->hidden,
3562       };
3563
3564       if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
3565         $cust_bill_pkg->sdate( $hash{last_bill} );
3566         $cust_bill_pkg->edate( $sdate - 86399   ); #60s*60m*24h-1
3567         $cust_bill_pkg->edate( $time ) if $options{cancel};
3568       } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
3569         $cust_bill_pkg->sdate( $sdate );
3570         $cust_bill_pkg->edate( $cust_pkg->bill );
3571         #$cust_bill_pkg->edate( $time ) if $options{cancel};
3572       }
3573
3574       $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
3575         unless $part_pkg->pkgpart == $real_pkgpart;
3576
3577       $$total_setup += $setup;
3578       $$total_recur += $recur;
3579
3580       ###
3581       # handle taxes
3582       ###
3583
3584       my $error = 
3585         $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
3586       return $error if $error;
3587
3588       push @$cust_bill_pkgs, $cust_bill_pkg;
3589
3590     } #if $setup != 0 || $recur != 0
3591       
3592   } #if $line_items
3593
3594   '';
3595
3596 }
3597
3598 sub _handle_taxes {
3599   my $self = shift;
3600   my $part_pkg = shift;
3601   my $taxlisthash = shift;
3602   my $cust_bill_pkg = shift;
3603   my $cust_pkg = shift;
3604   my $invoice_time = shift;
3605   my $real_pkgpart = shift;
3606   my $options = shift;
3607
3608   my %cust_bill_pkg = ();
3609   my %taxes = ();
3610     
3611   my @classes;
3612   #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
3613   push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
3614   push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
3615   push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
3616
3617   if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
3618
3619     if ( $conf->exists('enable_taxproducts')
3620          && ( scalar($part_pkg->part_pkg_taxoverride)
3621               || $part_pkg->has_taxproduct
3622             )
3623        )
3624     {
3625
3626       if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3627         return "fatal: Can't (yet) use tax-pkg_address with taxproducts";
3628       }
3629
3630       foreach my $class (@classes) {
3631         my $err_or_ref = $self->_gather_taxes( $part_pkg, $class );
3632         return $err_or_ref unless ref($err_or_ref);
3633         $taxes{$class} = $err_or_ref;
3634       }
3635
3636       unless (exists $taxes{''}) {
3637         my $err_or_ref = $self->_gather_taxes( $part_pkg, '' );
3638         return $err_or_ref unless ref($err_or_ref);
3639         $taxes{''} = $err_or_ref;
3640       }
3641
3642     } else {
3643
3644       my @loc_keys = qw( city county state country );
3645       my %taxhash;
3646       if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3647         my $cust_location = $cust_pkg->cust_location;
3648         %taxhash = map { $_ => $cust_location->$_()    } @loc_keys;
3649       } else {
3650         my $prefix = 
3651           ( $conf->exists('tax-ship_address') && length($self->ship_last) )
3652           ? 'ship_'
3653           : '';
3654         %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
3655       }
3656
3657       $taxhash{'taxclass'} = $part_pkg->taxclass;
3658
3659       my @taxes = ();
3660       my %taxhash_elim = %taxhash;
3661       my @elim = qw( city county state );
3662       do { 
3663
3664         #first try a match with taxclass
3665         @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
3666
3667         if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
3668           #then try a match without taxclass
3669           my %no_taxclass = %taxhash_elim;
3670           $no_taxclass{ 'taxclass' } = '';
3671           @taxes = qsearch( 'cust_main_county', \%no_taxclass );
3672         }
3673
3674         $taxhash_elim{ shift(@elim) } = '';
3675
3676       } while ( !scalar(@taxes) && scalar(@elim) );
3677
3678       @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
3679                     @taxes
3680         if $self->cust_main_exemption; #just to be safe
3681
3682       if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
3683         foreach (@taxes) {
3684           $_->set('pkgnum',      $cust_pkg->pkgnum );
3685           $_->set('locationnum', $cust_pkg->locationnum );
3686         }
3687       }
3688
3689       $taxes{''} = [ @taxes ];
3690       $taxes{'setup'} = [ @taxes ];
3691       $taxes{'recur'} = [ @taxes ];
3692       $taxes{$_} = [ @taxes ] foreach (@classes);
3693
3694       # # maybe eliminate this entirely, along with all the 0% records
3695       # unless ( @taxes ) {
3696       #   return
3697       #     "fatal: can't find tax rate for state/county/country/taxclass ".
3698       #     join('/', map $taxhash{$_}, qw(state county country taxclass) );
3699       # }
3700
3701     } #if $conf->exists('enable_taxproducts') ...
3702
3703   }
3704  
3705   my @display = ();
3706   my $separate = $conf->exists('separate_usage');
3707   my $temp_pkg = new FS::cust_pkg { pkgpart => $real_pkgpart };
3708   my $usage_mandate = $temp_pkg->part_pkg->option('usage_mandate', 'Hush!');
3709   my $section = $temp_pkg->part_pkg->categoryname;
3710   if ( $separate || $section || $usage_mandate ) {
3711
3712     my %hash = ( 'section' => $section );
3713
3714     $section = $temp_pkg->part_pkg->option('usage_section', 'Hush!');
3715     my $summary = $temp_pkg->part_pkg->option('summarize_usage', 'Hush!');
3716     if ( $separate ) {
3717       push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
3718       push @display, new FS::cust_bill_pkg_display { type => 'R', %hash };
3719     } else {
3720       push @display, new FS::cust_bill_pkg_display
3721                        { type => '',
3722                          %hash,
3723                          ( ( $usage_mandate ) ? ( 'summary' => 'Y' ) : () ),
3724                        };
3725     }
3726
3727     if ($separate && $section && $summary) {
3728       push @display, new FS::cust_bill_pkg_display { type    => 'U',
3729                                                      summary => 'Y',
3730                                                      %hash,
3731                                                    };
3732     }
3733     if ($usage_mandate || $section && $summary) {
3734       $hash{post_total} = 'Y';
3735     }
3736
3737     if ($separate || $usage_mandate) {
3738       $hash{section} = $section if ($separate || $usage_mandate);
3739       push @display, new FS::cust_bill_pkg_display { type => 'U', %hash };
3740     }
3741
3742   }
3743   $cust_bill_pkg->set('display', \@display);
3744
3745   my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
3746   foreach my $key (keys %tax_cust_bill_pkg) {
3747     my @taxes = @{ $taxes{$key} || [] };
3748     my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
3749
3750     my %localtaxlisthash = ();
3751     foreach my $tax ( @taxes ) {
3752
3753       my $taxname = ref( $tax ). ' '. $tax->taxnum;
3754 #      $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
3755 #                  ' locationnum'. $cust_pkg->locationnum
3756 #        if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
3757
3758       $taxlisthash->{ $taxname } ||= [ $tax ];
3759       push @{ $taxlisthash->{ $taxname  } }, $tax_cust_bill_pkg;
3760
3761       $localtaxlisthash{ $taxname } ||= [ $tax ];
3762       push @{ $localtaxlisthash{ $taxname  } }, $tax_cust_bill_pkg;
3763
3764     }
3765
3766     warn "finding taxed taxes...\n" if $DEBUG > 2;
3767     foreach my $tax ( keys %localtaxlisthash ) {
3768       my $tax_object = shift @{ $localtaxlisthash{$tax} };
3769       warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
3770         if $DEBUG > 2;
3771       next unless $tax_object->can('tax_on_tax');
3772
3773       foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
3774         my $totname = ref( $tot ). ' '. $tot->taxnum;
3775
3776         warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
3777           if $DEBUG > 2;
3778         next unless exists( $localtaxlisthash{ $totname } ); # only increase
3779                                                              # existing taxes
3780         warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
3781         my $hashref_or_error = 
3782           $tax_object->taxline( $localtaxlisthash{$tax},
3783                                 'custnum'      => $self->custnum,
3784                                 'invoice_time' => $invoice_time,
3785                               );
3786         return $hashref_or_error
3787           unless ref($hashref_or_error);
3788         
3789         $taxlisthash->{ $totname } ||= [ $tot ];
3790         push @{ $taxlisthash->{ $totname  } }, $hashref_or_error->{amount};
3791
3792       }
3793     }
3794
3795   }
3796
3797   '';
3798 }
3799
3800 sub _gather_taxes {
3801   my $self = shift;
3802   my $part_pkg = shift;
3803   my $class = shift;
3804
3805   my @taxes = ();
3806   my $geocode = $self->geocode('cch');
3807
3808   my @taxclassnums = map { $_->taxclassnum }
3809                      $part_pkg->part_pkg_taxoverride($class);
3810
3811   unless (@taxclassnums) {
3812     @taxclassnums = map { $_->taxclassnum }
3813                     grep { $_->taxable eq 'Y' }
3814                     $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
3815   }
3816   warn "Found taxclassnum values of ". join(',', @taxclassnums)
3817     if $DEBUG;
3818
3819   my $extra_sql =
3820     "AND (".
3821     join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
3822
3823   @taxes = qsearch({ 'table' => 'tax_rate',
3824                      'hashref' => { 'geocode' => $geocode, },
3825                      'extra_sql' => $extra_sql,
3826                   })
3827     if scalar(@taxclassnums);
3828
3829   warn "Found taxes ".
3830        join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n" 
3831    if $DEBUG;
3832
3833   [ @taxes ];
3834
3835 }
3836
3837 =item collect [ HASHREF | OPTION => VALUE ... ]
3838
3839 (Attempt to) collect money for this customer's outstanding invoices (see
3840 L<FS::cust_bill>).  Usually used after the bill method.
3841
3842 Actions are now triggered by billing events; see L<FS::part_event> and the
3843 billing events web interface.  Old-style invoice events (see
3844 L<FS::part_bill_event>) have been deprecated.
3845
3846 If there is an error, returns the error, otherwise returns false.
3847
3848 Options are passed as name-value pairs.
3849
3850 Currently available options are:
3851
3852 =over 4
3853
3854 =item invoice_time
3855
3856 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.
3857
3858 =item retry
3859
3860 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3861
3862 =item check_freq
3863
3864 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3865
3866 =item quiet
3867
3868 set true to surpress email card/ACH decline notices.
3869
3870 =item debug
3871
3872 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)
3873
3874 =back
3875
3876 # =item payby
3877 #
3878 # allows for one time override of normal customer billing method
3879
3880 =cut
3881
3882 sub collect {
3883   my( $self, %options ) = @_;
3884   my $invoice_time = $options{'invoice_time'} || time;
3885
3886   #put below somehow?
3887   local $SIG{HUP} = 'IGNORE';
3888   local $SIG{INT} = 'IGNORE';
3889   local $SIG{QUIT} = 'IGNORE';
3890   local $SIG{TERM} = 'IGNORE';
3891   local $SIG{TSTP} = 'IGNORE';
3892   local $SIG{PIPE} = 'IGNORE';
3893
3894   my $oldAutoCommit = $FS::UID::AutoCommit;
3895   local $FS::UID::AutoCommit = 0;
3896   my $dbh = dbh;
3897
3898   $self->select_for_update; #mutex
3899
3900   if ( $DEBUG ) {
3901     my $balance = $self->balance;
3902     warn "$me collect customer ". $self->custnum. ": balance $balance\n"
3903   }
3904
3905   if ( exists($options{'retry_card'}) ) {
3906     carp 'retry_card option passed to collect is deprecated; use retry';
3907     $options{'retry'} ||= $options{'retry_card'};
3908   }
3909   if ( exists($options{'retry'}) && $options{'retry'} ) {
3910     my $error = $self->retry_realtime;
3911     if ( $error ) {
3912       $dbh->rollback if $oldAutoCommit;
3913       return $error;
3914     }
3915   }
3916
3917   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3918
3919   #never want to roll back an event just because it returned an error
3920   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
3921
3922   $self->do_cust_event(
3923     'debug'      => ( $options{'debug'} || 0 ),
3924     'time'       => $invoice_time,
3925     'check_freq' => $options{'check_freq'},
3926     'stage'      => 'collect',
3927   );
3928
3929 }
3930
3931 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
3932
3933 Runs billing events; see L<FS::part_event> and the billing events web
3934 interface.
3935
3936 If there is an error, returns the error, otherwise returns false.
3937
3938 Options are passed as name-value pairs.
3939
3940 Currently available options are:
3941
3942 =over 4
3943
3944 =item time
3945
3946 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.
3947
3948 =item check_freq
3949
3950 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
3951
3952 =item stage
3953
3954 "collect" (the default) or "pre-bill"
3955
3956 =item quiet
3957  
3958 set true to surpress email card/ACH decline notices.
3959
3960 =item debug
3961
3962 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)
3963
3964 =cut
3965
3966 # =item payby
3967 #
3968 # allows for one time override of normal customer billing method
3969
3970 # =item retry
3971 #
3972 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
3973
3974 sub do_cust_event {
3975   my( $self, %options ) = @_;
3976   my $time = $options{'time'} || time;
3977
3978   #put below somehow?
3979   local $SIG{HUP} = 'IGNORE';
3980   local $SIG{INT} = 'IGNORE';
3981   local $SIG{QUIT} = 'IGNORE';
3982   local $SIG{TERM} = 'IGNORE';
3983   local $SIG{TSTP} = 'IGNORE';
3984   local $SIG{PIPE} = 'IGNORE';
3985
3986   my $oldAutoCommit = $FS::UID::AutoCommit;
3987   local $FS::UID::AutoCommit = 0;
3988   my $dbh = dbh;
3989
3990   $self->select_for_update; #mutex
3991
3992   if ( $DEBUG ) {
3993     my $balance = $self->balance;
3994     warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
3995   }
3996
3997 #  if ( exists($options{'retry_card'}) ) {
3998 #    carp 'retry_card option passed to collect is deprecated; use retry';
3999 #    $options{'retry'} ||= $options{'retry_card'};
4000 #  }
4001 #  if ( exists($options{'retry'}) && $options{'retry'} ) {
4002 #    my $error = $self->retry_realtime;
4003 #    if ( $error ) {
4004 #      $dbh->rollback if $oldAutoCommit;
4005 #      return $error;
4006 #    }
4007 #  }
4008
4009   # false laziness w/pay_batch::import_results
4010
4011   my $due_cust_event = $self->due_cust_event(
4012     'debug'      => ( $options{'debug'} || 0 ),
4013     'time'       => $time,
4014     'check_freq' => $options{'check_freq'},
4015     'stage'      => ( $options{'stage'} || 'collect' ),
4016   );
4017   unless( ref($due_cust_event) ) {
4018     $dbh->rollback if $oldAutoCommit;
4019     return $due_cust_event;
4020   }
4021
4022   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4023   #never want to roll back an event just because it or a different one
4024   # returned an error
4025   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
4026
4027   foreach my $cust_event ( @$due_cust_event ) {
4028
4029     #XXX lock event
4030     
4031     #re-eval event conditions (a previous event could have changed things)
4032     unless ( $cust_event->test_conditions( 'time' => $time ) ) {
4033       #don't leave stray "new/locked" records around
4034       my $error = $cust_event->delete;
4035       return $error if $error;
4036       next;
4037     }
4038
4039     {
4040       local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
4041       warn "  running cust_event ". $cust_event->eventnum. "\n"
4042         if $DEBUG > 1;
4043
4044       #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
4045       if ( my $error = $cust_event->do_event() ) {
4046         #XXX wtf is this?  figure out a proper dealio with return value
4047         #from do_event
4048         return $error;
4049       }
4050     }
4051
4052   }
4053
4054   '';
4055
4056 }
4057
4058 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
4059
4060 Inserts database records for and returns an ordered listref of new events due
4061 for this customer, as FS::cust_event objects (see L<FS::cust_event>).  If no
4062 events are due, an empty listref is returned.  If there is an error, returns a
4063 scalar error message.
4064
4065 To actually run the events, call each event's test_condition method, and if
4066 still true, call the event's do_event method.
4067
4068 Options are passed as a hashref or as a list of name-value pairs.  Available
4069 options are:
4070
4071 =over 4
4072
4073 =item check_freq
4074
4075 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.
4076
4077 =item stage
4078
4079 "collect" (the default) or "pre-bill"
4080
4081 =item time
4082
4083 "Current time" for the events.
4084
4085 =item debug
4086
4087 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)
4088
4089 =item eventtable
4090
4091 Only return events for the specified eventtable (by default, events of all eventtables are returned)
4092
4093 =item objects
4094
4095 Explicitly pass the objects to be tested (typically used with eventtable).
4096
4097 =item testonly
4098
4099 Set to true to return the objects, but not actually insert them into the
4100 database.
4101
4102 =back
4103
4104 =cut
4105
4106 sub due_cust_event {
4107   my $self = shift;
4108   my %opt = ref($_[0]) ? %{ $_[0] } : @_;
4109
4110   #???
4111   #my $DEBUG = $opt{'debug'}
4112   local($DEBUG) = $opt{'debug'}
4113     if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
4114
4115   warn "$me due_cust_event called with options ".
4116        join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
4117     if $DEBUG;
4118
4119   $opt{'time'} ||= time;
4120
4121   local $SIG{HUP} = 'IGNORE';
4122   local $SIG{INT} = 'IGNORE';
4123   local $SIG{QUIT} = 'IGNORE';
4124   local $SIG{TERM} = 'IGNORE';
4125   local $SIG{TSTP} = 'IGNORE';
4126   local $SIG{PIPE} = 'IGNORE';
4127
4128   my $oldAutoCommit = $FS::UID::AutoCommit;
4129   local $FS::UID::AutoCommit = 0;
4130   my $dbh = dbh;
4131
4132   $self->select_for_update #mutex
4133     unless $opt{testonly};
4134
4135   ###
4136   # find possible events (initial search)
4137   ###
4138   
4139   my @cust_event = ();
4140
4141   my @eventtable = $opt{'eventtable'}
4142                      ? ( $opt{'eventtable'} )
4143                      : FS::part_event->eventtables_runorder;
4144
4145   foreach my $eventtable ( @eventtable ) {
4146
4147     my @objects;
4148     if ( $opt{'objects'} ) {
4149
4150       @objects = @{ $opt{'objects'} };
4151
4152     } else {
4153
4154       #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
4155       @objects = ( $eventtable eq 'cust_main' )
4156                    ? ( $self )
4157                    : ( $self->$eventtable() );
4158
4159     }
4160
4161     my @e_cust_event = ();
4162
4163     my $cross = "CROSS JOIN $eventtable";
4164     $cross .= ' LEFT JOIN cust_main USING ( custnum )'
4165       unless $eventtable eq 'cust_main';
4166
4167     foreach my $object ( @objects ) {
4168
4169       #this first search uses the condition_sql magic for optimization.
4170       #the more possible events we can eliminate in this step the better
4171
4172       my $cross_where = '';
4173       my $pkey = $object->primary_key;
4174       $cross_where = "$eventtable.$pkey = ". $object->$pkey();
4175
4176       my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
4177       my $extra_sql =
4178         FS::part_event_condition->where_conditions_sql( $eventtable,
4179                                                         'time'=>$opt{'time'}
4180                                                       );
4181       my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
4182
4183       $extra_sql = "AND $extra_sql" if $extra_sql;
4184
4185       #here is the agent virtualization
4186       $extra_sql .= " AND (    part_event.agentnum IS NULL
4187                             OR part_event.agentnum = ". $self->agentnum. ' )';
4188
4189       $extra_sql .= " $order";
4190
4191       warn "searching for events for $eventtable ". $object->$pkey. "\n"
4192         if $opt{'debug'} > 2;
4193       my @part_event = qsearch( {
4194         'debug'     => ( $opt{'debug'} > 3 ? 1 : 0 ),
4195         'select'    => 'part_event.*',
4196         'table'     => 'part_event',
4197         'addl_from' => "$cross $join",
4198         'hashref'   => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
4199                          'eventtable' => $eventtable,
4200                          'disabled'   => '',
4201                        },
4202         'extra_sql' => "AND $cross_where $extra_sql",
4203       } );
4204
4205       if ( $DEBUG > 2 ) {
4206         my $pkey = $object->primary_key;
4207         warn "      ". scalar(@part_event).
4208              " possible events found for $eventtable ". $object->$pkey(). "\n";
4209       }
4210
4211       push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
4212
4213     }
4214
4215     warn "    ". scalar(@e_cust_event).
4216          " subtotal possible cust events found for $eventtable\n"
4217       if $DEBUG > 1;
4218
4219     push @cust_event, @e_cust_event;
4220
4221   }
4222
4223   warn "  ". scalar(@cust_event).
4224        " total possible cust events found in initial search\n"
4225     if $DEBUG; # > 1;
4226
4227
4228   ##
4229   # test stage
4230   ##
4231
4232   $opt{stage} ||= 'collect';
4233   @cust_event =
4234     grep { my $stage = $_->part_event->event_stage;
4235            $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
4236          }
4237          @cust_event;
4238
4239   ##
4240   # test conditions
4241   ##
4242   
4243   my %unsat = ();
4244
4245   @cust_event = grep $_->test_conditions( 'time'          => $opt{'time'},
4246                                           'stats_hashref' => \%unsat ),
4247                      @cust_event;
4248
4249   warn "  ". scalar(@cust_event). " cust events left satisfying conditions\n"
4250     if $DEBUG; # > 1;
4251
4252   warn "    invalid conditions not eliminated with condition_sql:\n".
4253        join('', map "      $_: ".$unsat{$_}."\n", keys %unsat )
4254     if keys %unsat && $DEBUG; # > 1;
4255
4256   ##
4257   # insert
4258   ##
4259
4260   unless( $opt{testonly} ) {
4261     foreach my $cust_event ( @cust_event ) {
4262
4263       my $error = $cust_event->insert();
4264       if ( $error ) {
4265         $dbh->rollback if $oldAutoCommit;
4266         return $error;
4267       }
4268                                        
4269     }
4270   }
4271
4272   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4273
4274   ##
4275   # return
4276   ##
4277
4278   warn "  returning events: ". Dumper(@cust_event). "\n"
4279     if $DEBUG > 2;
4280
4281   \@cust_event;
4282
4283 }
4284
4285 =item retry_realtime
4286
4287 Schedules realtime / batch  credit card / electronic check / LEC billing
4288 events for for retry.  Useful if card information has changed or manual
4289 retry is desired.  The 'collect' method must be called to actually retry
4290 the transaction.
4291
4292 Implementation details: For either this customer, or for each of this
4293 customer's open invoices, changes the status of the first "done" (with
4294 statustext error) realtime processing event to "failed".
4295
4296 =cut
4297
4298 sub retry_realtime {
4299   my $self = shift;
4300
4301   local $SIG{HUP} = 'IGNORE';
4302   local $SIG{INT} = 'IGNORE';
4303   local $SIG{QUIT} = 'IGNORE';
4304   local $SIG{TERM} = 'IGNORE';
4305   local $SIG{TSTP} = 'IGNORE';
4306   local $SIG{PIPE} = 'IGNORE';
4307
4308   my $oldAutoCommit = $FS::UID::AutoCommit;
4309   local $FS::UID::AutoCommit = 0;
4310   my $dbh = dbh;
4311
4312   #a little false laziness w/due_cust_event (not too bad, really)
4313
4314   my $join = FS::part_event_condition->join_conditions_sql;
4315   my $order = FS::part_event_condition->order_conditions_sql;
4316   my $mine = 
4317   '( '
4318    . join ( ' OR ' , map { 
4319     "( part_event.eventtable = " . dbh->quote($_) 
4320     . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
4321    } FS::part_event->eventtables)
4322    . ') ';
4323
4324   #here is the agent virtualization
4325   my $agent_virt = " (    part_event.agentnum IS NULL
4326                        OR part_event.agentnum = ". $self->agentnum. ' )';
4327
4328   #XXX this shouldn't be hardcoded, actions should declare it...
4329   my @realtime_events = qw(
4330     cust_bill_realtime_card
4331     cust_bill_realtime_check
4332     cust_bill_realtime_lec
4333     cust_bill_batch
4334   );
4335
4336   my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
4337                                                   @realtime_events
4338                                      ).
4339                           ' ) ';
4340
4341   my @cust_event = qsearchs({
4342     'table'     => 'cust_event',
4343     'select'    => 'cust_event.*',
4344     'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
4345     'hashref'   => { 'status' => 'done' },
4346     'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
4347                    " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
4348   });
4349
4350   my %seen_invnum = ();
4351   foreach my $cust_event (@cust_event) {
4352
4353     #max one for the customer, one for each open invoice
4354     my $cust_X = $cust_event->cust_X;
4355     next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
4356                           ? $cust_X->invnum
4357                           : 0
4358                         }++
4359          or $cust_event->part_event->eventtable eq 'cust_bill'
4360             && ! $cust_X->owed;
4361
4362     my $error = $cust_event->retry;
4363     if ( $error ) {
4364       $dbh->rollback if $oldAutoCommit;
4365       return "error scheduling event for retry: $error";
4366     }
4367
4368   }
4369
4370   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4371   '';
4372
4373 }
4374
4375
4376 =cut
4377
4378 =item realtime_collect [ OPTION => VALUE ... ]
4379
4380 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4381 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
4382 gateway.  See L<http://420.am/business-onlinepayment> and 
4383 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
4384
4385 On failure returns an error message.
4386
4387 Returns false or a hashref upon success.  The hashref contains keys popup_url reference, and collectitems.  The first is a URL to which a browser should be redirected for completion of collection.  The second is a reference id for the transaction suitable for the end user.  The collectitems is a reference to a list of name value pairs suitable for assigning to a html form and posted to popup_url.
4388
4389 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
4390
4391 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>.  If none is specified
4392 then it is deduced from the customer record.
4393
4394 If no I<amount> is specified, then the customer balance is used.
4395
4396 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4397 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
4398 if set, will override the value from the customer record.
4399
4400 I<description> is a free-text field passed to the gateway.  It defaults to
4401 the value defined by the business-onlinepayment-description configuration
4402 option, or "Internet services" if that is unset.
4403
4404 If an I<invnum> is specified, this payment (if successful) is applied to the
4405 specified invoice.  If you don't specify an I<invnum> you might want to
4406 call the B<apply_payments> method or set the I<apply> option.
4407
4408 I<apply> can be set to true to apply a resulting payment.
4409
4410 I<quiet> can be set true to surpress email decline notices.
4411
4412 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
4413 resulting paynum, if any.
4414
4415 I<payunique> is a unique identifier for this payment.
4416
4417 I<session_id> is a session identifier associated with this payment.
4418
4419 I<depend_jobnum> allows payment capture to unlock export jobs
4420
4421 =cut
4422
4423 sub realtime_collect {
4424   my( $self, %options ) = @_;
4425
4426   if ( $DEBUG ) {
4427     warn "$me realtime_collect:\n";
4428     warn "  $_ => $options{$_}\n" foreach keys %options;
4429   }
4430
4431   $options{amount} = $self->balance unless exists( $options{amount} );
4432   $options{method} = FS::payby->payby2bop($self->payby)
4433     unless exists( $options{method} );
4434
4435   return $self->realtime_bop({%options});
4436
4437 }
4438
4439 =item realtime_bop { [ ARG => VALUE ... ] }
4440
4441 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
4442 via a Business::OnlinePayment realtime gateway.  See
4443 L<http://420.am/business-onlinepayment> for supported gateways.
4444
4445 Required arguments in the hashref are I<method>, and I<amount>
4446
4447 Available methods are: I<CC>, I<ECHECK> and I<LEC>
4448
4449 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
4450
4451 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
4452 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
4453 if set, will override the value from the customer record.
4454
4455 I<description> is a free-text field passed to the gateway.  It defaults to
4456 the value defined by the business-onlinepayment-description configuration
4457 option, or "Internet services" if that is unset.
4458
4459 If an I<invnum> is specified, this payment (if successful) is applied to the
4460 specified invoice.  If you don't specify an I<invnum> you might want to
4461 call the B<apply_payments> method or set the I<apply> option.
4462
4463 I<apply> can be set to true to apply a resulting payment.
4464
4465 I<quiet> can be set true to surpress email decline notices.
4466
4467 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
4468 resulting paynum, if any.
4469
4470 I<payunique> is a unique identifier for this payment.
4471
4472 I<session_id> is a session identifier associated with this payment.
4473
4474 I<depend_jobnum> allows payment capture to unlock export jobs
4475
4476 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
4477
4478 =cut
4479
4480 # some helper routines
4481 sub _bop_recurring_billing {
4482   my( $self, %opt ) = @_;
4483
4484   my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
4485
4486   if ( defined($method) && $method eq 'transaction_is_recur' ) {
4487
4488     return 1 if $opt{'trans_is_recur'};
4489
4490   } else {
4491
4492     my %hash = ( 'custnum' => $self->custnum,
4493                  'payby'   => 'CARD',
4494                );
4495
4496     return 1 
4497       if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
4498       || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
4499                                                                $opt{'payinfo'} )
4500                              } );
4501
4502   }
4503
4504   return 0;
4505
4506 }
4507
4508 sub _payment_gateway {
4509   my ($self, $options) = @_;
4510
4511   $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
4512     unless exists($options->{payment_gateway});
4513
4514   $options->{payment_gateway};
4515 }
4516
4517 sub _bop_auth {
4518   my ($self, $options) = @_;
4519
4520   (
4521     'login'    => $options->{payment_gateway}->gateway_username,
4522     'password' => $options->{payment_gateway}->gateway_password,
4523   );
4524 }
4525
4526 sub _bop_options {
4527   my ($self, $options) = @_;
4528
4529   $options->{payment_gateway}->gatewaynum
4530     ? $options->{payment_gateway}->options
4531     : @{ $options->{payment_gateway}->get('options') };
4532
4533 }
4534
4535 sub _bop_defaults {
4536   my ($self, $options) = @_;
4537
4538   unless ( $options->{'description'} ) {
4539     if ( $conf->exists('business-onlinepayment-description') ) {
4540       my $dtempl = $conf->config('business-onlinepayment-description');
4541
4542       my $agent = $self->agent->agent;
4543       #$pkgs... not here
4544       $options->{'description'} = eval qq("$dtempl");
4545     } else {
4546       $options->{'description'} = 'Internet services';
4547     }
4548   }
4549
4550   $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
4551   $options->{invnum} ||= '';
4552   $options->{payname} = $self->payname unless exists( $options->{payname} );
4553 }
4554
4555 sub _bop_content {
4556   my ($self, $options) = @_;
4557   my %content = ();
4558
4559   my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
4560   $content{customer_ip} = $payip if length($payip);
4561
4562   $content{invoice_number} = $options->{'invnum'}
4563     if exists($options->{'invnum'}) && length($options->{'invnum'});
4564
4565   $content{email_customer} = 
4566     (    $conf->exists('business-onlinepayment-email_customer')
4567       || $conf->exists('business-onlinepayment-email-override') );
4568       
4569   my ($payname, $payfirst, $paylast);
4570   if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
4571     ($payname = $options->{payname}) =~
4572       /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
4573       or return "Illegal payname $payname";
4574     ($payfirst, $paylast) = ($1, $2);
4575   } else {
4576     $payfirst = $self->getfield('first');
4577     $paylast = $self->getfield('last');
4578     $payname = "$payfirst $paylast";
4579   }
4580
4581   $content{last_name} = $paylast;
4582   $content{first_name} = $payfirst;
4583
4584   $content{name} = $payname;
4585
4586   $content{address} = exists($options->{'address1'})
4587                         ? $options->{'address1'}
4588                         : $self->address1;
4589   my $address2 = exists($options->{'address2'})
4590                    ? $options->{'address2'}
4591                    : $self->address2;
4592   $content{address} .= ", ". $address2 if length($address2);
4593
4594   $content{city} = exists($options->{city})
4595                      ? $options->{city}
4596                      : $self->city;
4597   $content{state} = exists($options->{state})
4598                       ? $options->{state}
4599                       : $self->state;
4600   $content{zip} = exists($options->{zip})
4601                     ? $options->{'zip'}
4602                     : $self->zip;
4603   $content{country} = exists($options->{country})
4604                         ? $options->{country}
4605                         : $self->country;
4606
4607   $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
4608   $content{phone} = $self->daytime || $self->night;
4609
4610   \%content;
4611 }
4612
4613 my %bop_method2payby = (
4614   'CC'     => 'CARD',
4615   'ECHECK' => 'CHEK',
4616   'LEC'    => 'LECB',
4617 );
4618
4619 sub realtime_bop {
4620   my $self = shift;
4621
4622   my %options = ();
4623   if (ref($_[0]) eq 'HASH') {
4624     %options = %{$_[0]};
4625   } else {
4626     my ( $method, $amount ) = ( shift, shift );
4627     %options = @_;
4628     $options{method} = $method;
4629     $options{amount} = $amount;
4630   }
4631   
4632   if ( $DEBUG ) {
4633     warn "$me realtime_bop (new): $options{method} $options{amount}\n";
4634     warn "  $_ => $options{$_}\n" foreach keys %options;
4635   }
4636
4637   return $self->fake_bop(%options) if $options{'fake'};
4638
4639   $self->_bop_defaults(\%options);
4640
4641   ###
4642   # set trans_is_recur based on invnum if there is one
4643   ###
4644
4645   my $trans_is_recur = 0;
4646   if ( $options{'invnum'} ) {
4647
4648     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
4649     die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
4650
4651     my @part_pkg =
4652       map  { $_->part_pkg }
4653       grep { $_ }
4654       map  { $_->cust_pkg }
4655       $cust_bill->cust_bill_pkg;
4656
4657     $trans_is_recur = 1
4658       if grep { $_->freq ne '0' } @part_pkg;
4659
4660   }
4661
4662   ###
4663   # select a gateway
4664   ###
4665
4666   my $payment_gateway =  $self->_payment_gateway( \%options );
4667   my $namespace = $payment_gateway->gateway_namespace;
4668
4669   eval "use $namespace";  
4670   die $@ if $@;
4671
4672   ###
4673   # check for banned credit card/ACH
4674   ###
4675
4676   my $ban = qsearchs('banned_pay', {
4677     'payby'   => $bop_method2payby{$options{method}},
4678     'payinfo' => md5_base64($options{payinfo}),
4679   } );
4680   return "Banned credit card" if $ban;
4681
4682   ###
4683   # massage data
4684   ###
4685
4686   my $bop_content = $self->_bop_content(\%options);
4687   return $bop_content unless ref($bop_content);
4688
4689   my @invoicing_list = $self->invoicing_list_emailonly;
4690   if ( $conf->exists('emailinvoiceautoalways')
4691        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
4692        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
4693     push @invoicing_list, $self->all_emails;
4694   }
4695
4696   my $email = ($conf->exists('business-onlinepayment-email-override'))
4697               ? $conf->config('business-onlinepayment-email-override')
4698               : $invoicing_list[0];
4699
4700   my $paydate = '';
4701   my %content = ();
4702   if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
4703
4704     $content{card_number} = $options{payinfo};
4705     $paydate = exists($options{'paydate'})
4706                     ? $options{'paydate'}
4707                     : $self->paydate;
4708     $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4709     $content{expiration} = "$2/$1";
4710
4711     my $paycvv = exists($options{'paycvv'})
4712                    ? $options{'paycvv'}
4713                    : $self->paycvv;
4714     $content{cvv2} = $paycvv
4715       if length($paycvv);
4716
4717     my $paystart_month = exists($options{'paystart_month'})
4718                            ? $options{'paystart_month'}
4719                            : $self->paystart_month;
4720
4721     my $paystart_year  = exists($options{'paystart_year'})
4722                            ? $options{'paystart_year'}
4723                            : $self->paystart_year;
4724
4725     $content{card_start} = "$paystart_month/$paystart_year"
4726       if $paystart_month && $paystart_year;
4727
4728     my $payissue       = exists($options{'payissue'})
4729                            ? $options{'payissue'}
4730                            : $self->payissue;
4731     $content{issue_number} = $payissue if $payissue;
4732
4733     if ( $self->_bop_recurring_billing( 'payinfo'        => $options{'payinfo'},
4734                                         'trans_is_recur' => $trans_is_recur,
4735                                       )
4736        )
4737     {
4738       $content{recurring_billing} = 'YES';
4739       $content{acct_code} = 'rebill'
4740         if $conf->exists('credit_card-recurring_billing_acct_code');
4741     }
4742
4743   } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
4744     ( $content{account_number}, $content{routing_code} ) =
4745       split('@', $options{payinfo});
4746     $content{bank_name} = $options{payname};
4747     $content{bank_state} = exists($options{'paystate'})
4748                              ? $options{'paystate'}
4749                              : $self->getfield('paystate');
4750     $content{account_type} = exists($options{'paytype'})
4751                                ? uc($options{'paytype'}) || 'CHECKING'
4752                                : uc($self->getfield('paytype')) || 'CHECKING';
4753     $content{account_name} = $self->getfield('first'). ' '.
4754                              $self->getfield('last');
4755
4756     $content{customer_org} = $self->company ? 'B' : 'I';
4757     $content{state_id}       = exists($options{'stateid'})
4758                                  ? $options{'stateid'}
4759                                  : $self->getfield('stateid');
4760     $content{state_id_state} = exists($options{'stateid_state'})
4761                                  ? $options{'stateid_state'}
4762                                  : $self->getfield('stateid_state');
4763     $content{customer_ssn} = exists($options{'ss'})
4764                                ? $options{'ss'}
4765                                : $self->ss;
4766   } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
4767     $content{phone} = $options{payinfo};
4768   } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4769     #move along
4770   } else {
4771     #die an evil death
4772   }
4773
4774   ###
4775   # run transaction(s)
4776   ###
4777
4778   my $balance = exists( $options{'balance'} )
4779                   ? $options{'balance'}
4780                   : $self->balance;
4781
4782   $self->select_for_update; #mutex ... just until we get our pending record in
4783
4784   #the checks here are intended to catch concurrent payments
4785   #double-form-submission prevention is taken care of in cust_pay_pending::check
4786
4787   #check the balance
4788   return "The customer's balance has changed; $options{method} transaction aborted."
4789     if $self->balance < $balance;
4790     #&& $self->balance < $options{amount}; #might as well anyway?
4791
4792   #also check and make sure there aren't *other* pending payments for this cust
4793
4794   my @pending = qsearch('cust_pay_pending', {
4795     'custnum' => $self->custnum,
4796     'status'  => { op=>'!=', value=>'done' } 
4797   });
4798   return "A payment is already being processed for this customer (".
4799          join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
4800          "); $options{method} transaction aborted."
4801     if scalar(@pending);
4802
4803   #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
4804
4805   my $cust_pay_pending = new FS::cust_pay_pending {
4806     'custnum'           => $self->custnum,
4807     #'invnum'            => $options{'invnum'},
4808     'paid'              => $options{amount},
4809     '_date'             => '',
4810     'payby'             => $bop_method2payby{$options{method}},
4811     'payinfo'           => $options{payinfo},
4812     'paydate'           => $paydate,
4813     'recurring_billing' => $content{recurring_billing},
4814     'pkgnum'            => $options{'pkgnum'},
4815     'status'            => 'new',
4816     'gatewaynum'        => $payment_gateway->gatewaynum || '',
4817     'session_id'        => $options{session_id} || '',
4818     'jobnum'            => $options{depend_jobnum} || '',
4819   };
4820   $cust_pay_pending->payunique( $options{payunique} )
4821     if defined($options{payunique}) && length($options{payunique});
4822   my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
4823   return $cpp_new_err if $cpp_new_err;
4824
4825   my( $action1, $action2 ) =
4826     split( /\s*\,\s*/, $payment_gateway->gateway_action );
4827
4828   my $transaction = new $namespace( $payment_gateway->gateway_module,
4829                                     $self->_bop_options(\%options),
4830                                   );
4831
4832   $transaction->content(
4833     'type'           => $options{method},
4834     $self->_bop_auth(\%options),          
4835     'action'         => $action1,
4836     'description'    => $options{'description'},
4837     'amount'         => $options{amount},
4838     #'invoice_number' => $options{'invnum'},
4839     'customer_id'    => $self->custnum,
4840     %$bop_content,
4841     'reference'      => $cust_pay_pending->paypendingnum, #for now
4842     'email'          => $email,
4843     %content, #after
4844   );
4845
4846   $cust_pay_pending->status('pending');
4847   my $cpp_pending_err = $cust_pay_pending->replace;
4848   return $cpp_pending_err if $cpp_pending_err;
4849
4850   #config?
4851   my $BOP_TESTING = 0;
4852   my $BOP_TESTING_SUCCESS = 1;
4853
4854   unless ( $BOP_TESTING ) {
4855     $transaction->test_transaction(1)
4856       if $conf->exists('business-onlinepayment-test_transaction');
4857     $transaction->submit();
4858   } else {
4859     if ( $BOP_TESTING_SUCCESS ) {
4860       $transaction->is_success(1);
4861       $transaction->authorization('fake auth');
4862     } else {
4863       $transaction->is_success(0);
4864       $transaction->error_message('fake failure');
4865     }
4866   }
4867
4868   if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
4869
4870     return { reference => $cust_pay_pending->paypendingnum,
4871              map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
4872
4873   } elsif ( $transaction->is_success() && $action2 ) {
4874
4875     $cust_pay_pending->status('authorized');
4876     my $cpp_authorized_err = $cust_pay_pending->replace;
4877     return $cpp_authorized_err if $cpp_authorized_err;
4878
4879     my $auth = $transaction->authorization;
4880     my $ordernum = $transaction->can('order_number')
4881                    ? $transaction->order_number
4882                    : '';
4883
4884     my $capture =
4885       new Business::OnlinePayment( $payment_gateway->gateway_module,
4886                                    $self->_bop_options(\%options),
4887                                  );
4888
4889     my %capture = (
4890       %content,
4891       type           => $options{method},
4892       action         => $action2,
4893       $self->_bop_auth(\%options),          
4894       order_number   => $ordernum,
4895       amount         => $options{amount},
4896       authorization  => $auth,
4897       description    => $options{'description'},
4898     );
4899
4900     foreach my $field (qw( authorization_source_code returned_ACI
4901                            transaction_identifier validation_code           
4902                            transaction_sequence_num local_transaction_date    
4903                            local_transaction_time AVS_result_code          )) {
4904       $capture{$field} = $transaction->$field() if $transaction->can($field);
4905     }
4906
4907     $capture->content( %capture );
4908
4909     $capture->test_transaction(1)
4910       if $conf->exists('business-onlinepayment-test_transaction');
4911     $capture->submit();
4912
4913     unless ( $capture->is_success ) {
4914       my $e = "Authorization successful but capture failed, custnum #".
4915               $self->custnum. ': '.  $capture->result_code.
4916               ": ". $capture->error_message;
4917       warn $e;
4918       return $e;
4919     }
4920
4921   }
4922
4923   ###
4924   # remove paycvv after initial transaction
4925   ###
4926
4927   #false laziness w/misc/process/payment.cgi - check both to make sure working
4928   # correctly
4929   if ( length($self->paycvv)
4930        && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
4931   ) {
4932     my $error = $self->remove_cvv;
4933     if ( $error ) {
4934       warn "WARNING: error removing cvv: $error\n";
4935     }
4936   }
4937
4938   ###
4939   # Tokenize
4940   ###
4941
4942
4943   if ( $transaction->can('card_token') && $transaction->card_token ) {
4944
4945     $self->card_token($transaction->card_token);
4946
4947     if ( $options{'payinfo'} eq $self->payinfo ) {
4948       $self->payinfo($transaction->card_token);
4949       my $error = $self->replace;
4950       if ( $error ) {
4951         warn "WARNING: error storing token: $error, but proceeding anyway\n";
4952       }
4953     }
4954
4955   }
4956
4957   ###
4958   # result handling
4959   ###
4960
4961   $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
4962
4963 }
4964
4965 =item fake_bop
4966
4967 =cut
4968
4969 sub fake_bop {
4970   my $self = shift;
4971
4972   my %options = ();
4973   if (ref($_[0]) eq 'HASH') {
4974     %options = %{$_[0]};
4975   } else {
4976     my ( $method, $amount ) = ( shift, shift );
4977     %options = @_;
4978     $options{method} = $method;
4979     $options{amount} = $amount;
4980   }
4981   
4982   if ( $options{'fake_failure'} ) {
4983      return "Error: No error; test failure requested with fake_failure";
4984   }
4985
4986   #my $paybatch = '';
4987   #if ( $payment_gateway->gatewaynum ) { # agent override
4988   #  $paybatch = $payment_gateway->gatewaynum. '-';
4989   #}
4990   #
4991   #$paybatch .= "$processor:". $transaction->authorization;
4992   #
4993   #$paybatch .= ':'. $transaction->order_number
4994   #  if $transaction->can('order_number')
4995   #  && length($transaction->order_number);
4996
4997   my $paybatch = 'FakeProcessor:54:32';
4998
4999   my $cust_pay = new FS::cust_pay ( {
5000      'custnum'  => $self->custnum,
5001      'invnum'   => $options{'invnum'},
5002      'paid'     => $options{amount},
5003      '_date'    => '',
5004      'payby'    => $bop_method2payby{$options{method}},
5005      #'payinfo'  => $payinfo,
5006      'payinfo'  => '4111111111111111',
5007      'paybatch' => $paybatch,
5008      #'paydate'  => $paydate,
5009      'paydate'  => '2012-05-01',
5010   } );
5011   $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
5012
5013   my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
5014
5015   if ( $error ) {
5016     $cust_pay->invnum(''); #try again with no specific invnum
5017     my $error2 = $cust_pay->insert( $options{'manual'} ?
5018                                     ( 'manual' => 1 ) : ()
5019                                   );
5020     if ( $error2 ) {
5021       # gah, even with transactions.
5022       my $e = 'WARNING: Card/ACH debited but database not updated - '.
5023               "error inserting (fake!) payment: $error2".
5024               " (previously tried insert with invnum #$options{'invnum'}" .
5025               ": $error )";
5026       warn $e;
5027       return $e;
5028     }
5029   }
5030
5031   if ( $options{'paynum_ref'} ) {
5032     ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5033   }
5034
5035   return ''; #no error
5036
5037 }
5038
5039
5040 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
5041
5042 # Wraps up processing of a realtime credit card, ACH (electronic check) or
5043 # phone bill transaction.
5044
5045 sub _realtime_bop_result {
5046   my( $self, $cust_pay_pending, $transaction, %options ) = @_;
5047   if ( $DEBUG ) {
5048     warn "$me _realtime_bop_result: pending transaction ".
5049       $cust_pay_pending->paypendingnum. "\n";
5050     warn "  $_ => $options{$_}\n" foreach keys %options;
5051   }
5052
5053   my $payment_gateway = $options{payment_gateway}
5054     or return "no payment gateway in arguments to _realtime_bop_result";
5055
5056   $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
5057   my $cpp_captured_err = $cust_pay_pending->replace;
5058   return $cpp_captured_err if $cpp_captured_err;
5059
5060   if ( $transaction->is_success() ) {
5061
5062     my $paybatch = '';
5063     if ( $payment_gateway->gatewaynum ) { # agent override
5064       $paybatch = $payment_gateway->gatewaynum. '-';
5065     }
5066
5067     $paybatch .= $payment_gateway->gateway_module. ":".
5068       $transaction->authorization;
5069
5070     $paybatch .= ':'. $transaction->order_number
5071       if $transaction->can('order_number')
5072       && length($transaction->order_number);
5073
5074     my $cust_pay = new FS::cust_pay ( {
5075        'custnum'  => $self->custnum,
5076        'invnum'   => $options{'invnum'},
5077        'paid'     => $cust_pay_pending->paid,
5078        '_date'    => '',
5079        'payby'    => $cust_pay_pending->payby,
5080        'payinfo'  => $options{'payinfo'},
5081        'paybatch' => $paybatch,
5082        'paydate'  => $cust_pay_pending->paydate,
5083        'pkgnum'   => $cust_pay_pending->pkgnum,
5084     } );
5085     #doesn't hurt to know, even though the dup check is in cust_pay_pending now
5086     $cust_pay->payunique( $options{payunique} )
5087       if defined($options{payunique}) && length($options{payunique});
5088
5089     my $oldAutoCommit = $FS::UID::AutoCommit;
5090     local $FS::UID::AutoCommit = 0;
5091     my $dbh = dbh;
5092
5093     #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
5094
5095     my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
5096
5097     if ( $error ) {
5098       $cust_pay->invnum(''); #try again with no specific invnum
5099       my $error2 = $cust_pay->insert( $options{'manual'} ?
5100                                       ( 'manual' => 1 ) : ()
5101                                     );
5102       if ( $error2 ) {
5103         # gah.  but at least we have a record of the state we had to abort in
5104         # from cust_pay_pending now.
5105         my $e = "WARNING: $options{method} captured but payment not recorded -".
5106                 " error inserting payment (". $payment_gateway->gateway_module.
5107                 "): $error2".
5108                 " (previously tried insert with invnum #$options{'invnum'}" .
5109                 ": $error ) - pending payment saved as paypendingnum ".
5110                 $cust_pay_pending->paypendingnum. "\n";
5111         warn $e;
5112         return $e;
5113       }
5114     }
5115
5116     my $jobnum = $cust_pay_pending->jobnum;
5117     if ( $jobnum ) {
5118        my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5119       
5120        unless ( $placeholder ) {
5121          $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5122          my $e = "WARNING: $options{method} captured but job $jobnum not ".
5123              "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
5124          warn $e;
5125          return $e;
5126        }
5127
5128        $error = $placeholder->delete;
5129
5130        if ( $error ) {
5131          $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5132          my $e = "WARNING: $options{method} captured but could not delete ".
5133               "job $jobnum for paypendingnum ".
5134               $cust_pay_pending->paypendingnum. ": $error\n";
5135          warn $e;
5136          return $e;
5137        }
5138
5139     }
5140     
5141     if ( $options{'paynum_ref'} ) {
5142       ${ $options{'paynum_ref'} } = $cust_pay->paynum;
5143     }
5144
5145     $cust_pay_pending->status('done');
5146     $cust_pay_pending->statustext('captured');
5147     $cust_pay_pending->paynum($cust_pay->paynum);
5148     my $cpp_done_err = $cust_pay_pending->replace;
5149
5150     if ( $cpp_done_err ) {
5151
5152       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
5153       my $e = "WARNING: $options{method} captured but payment not recorded - ".
5154               "error updating status for paypendingnum ".
5155               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5156       warn $e;
5157       return $e;
5158
5159     } else {
5160
5161       $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5162
5163       if ( $options{'apply'} ) {
5164         my $apply_error = $self->apply_payments_and_credits;
5165         if ( $apply_error ) {
5166           warn "WARNING: error applying payment: $apply_error\n";
5167           #but we still should return no error cause the payment otherwise went
5168           #through...
5169         }
5170       }
5171
5172       return ''; #no error
5173
5174     }
5175
5176   } else {
5177
5178     my $perror = $payment_gateway->gateway_module. " error: ".
5179       $transaction->error_message;
5180
5181     my $jobnum = $cust_pay_pending->jobnum;
5182     if ( $jobnum ) {
5183        my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
5184       
5185        if ( $placeholder ) {
5186          my $error = $placeholder->depended_delete;
5187          $error ||= $placeholder->delete;
5188          warn "error removing provisioning jobs after declined paypendingnum ".
5189            $cust_pay_pending->paypendingnum. "\n";
5190        } else {
5191          my $e = "error finding job $jobnum for declined paypendingnum ".
5192               $cust_pay_pending->paypendingnum. "\n";
5193          warn $e;
5194        }
5195
5196     }
5197     
5198     unless ( $transaction->error_message ) {
5199
5200       my $t_response;
5201       if ( $transaction->can('response_page') ) {
5202         $t_response = {
5203                         'page'    => ( $transaction->can('response_page')
5204                                          ? $transaction->response_page
5205                                          : ''
5206                                      ),
5207                         'code'    => ( $transaction->can('response_code')
5208                                          ? $transaction->response_code
5209                                          : ''
5210                                      ),
5211                         'headers' => ( $transaction->can('response_headers')
5212                                          ? $transaction->response_headers
5213                                          : ''
5214                                      ),
5215                       };
5216       } else {
5217         $t_response .=
5218           "No additional debugging information available for ".
5219             $payment_gateway->gateway_module;
5220       }
5221
5222       $perror .= "No error_message returned from ".
5223                    $payment_gateway->gateway_module. " -- ".
5224                  ( ref($t_response) ? Dumper($t_response) : $t_response );
5225
5226     }
5227
5228     if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
5229          && $conf->exists('emaildecline')
5230          && grep { $_ ne 'POST' } $self->invoicing_list
5231          && ! grep { $transaction->error_message =~ /$_/ }
5232                    $conf->config('emaildecline-exclude')
5233     ) {
5234
5235       # Send a decline alert to the customer.
5236       my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
5237       my $error = '';
5238       if ( $msgnum ) {
5239         # include the raw error message in the transaction state
5240         $cust_pay_pending->setfield('error', $transaction->error_message);
5241         my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
5242         $error = $msg_template->send( 'cust_main' => $self,
5243                                       'object'    => $cust_pay_pending );
5244       }
5245       else { #!$msgnum
5246
5247         my @templ = $conf->config('declinetemplate');
5248         my $template = new Text::Template (
5249           TYPE   => 'ARRAY',
5250           SOURCE => [ map "$_\n", @templ ],
5251         ) or return "($perror) can't create template: $Text::Template::ERROR";
5252         $template->compile()
5253           or return "($perror) can't compile template: $Text::Template::ERROR";
5254
5255         my $templ_hash = {
5256           'company_name'    =>
5257             scalar( $conf->config('company_name', $self->agentnum ) ),
5258           'company_address' =>
5259             join("\n", $conf->config('company_address', $self->agentnum ) ),
5260           'error'           => $transaction->error_message,
5261         };
5262
5263         my $error = send_email(
5264           'from'    => $conf->config('invoice_from', $self->agentnum ),
5265           'to'      => [ grep { $_ ne 'POST' } $self->invoicing_list ],
5266           'subject' => 'Your payment could not be processed',
5267           'body'    => [ $template->fill_in(HASH => $templ_hash) ],
5268         );
5269       }
5270
5271       $perror .= " (also received error sending decline notification: $error)"
5272         if $error;
5273
5274     }
5275
5276     $cust_pay_pending->status('done');
5277     $cust_pay_pending->statustext("declined: $perror");
5278     my $cpp_done_err = $cust_pay_pending->replace;
5279     if ( $cpp_done_err ) {
5280       my $e = "WARNING: $options{method} declined but pending payment not ".
5281               "resolved - error updating status for paypendingnum ".
5282               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
5283       warn $e;
5284       $perror = "$e ($perror)";
5285     }
5286
5287     return $perror;
5288   }
5289
5290 }
5291
5292 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
5293
5294 Verifies successful third party processing of a realtime credit card,
5295 ACH (electronic check) or phone bill transaction via a
5296 Business::OnlineThirdPartyPayment realtime gateway.  See
5297 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
5298
5299 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
5300
5301 The additional options I<payname>, I<city>, I<state>,
5302 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
5303 if set, will override the value from the customer record.
5304
5305 I<description> is a free-text field passed to the gateway.  It defaults to
5306 "Internet services".
5307
5308 If an I<invnum> is specified, this payment (if successful) is applied to the
5309 specified invoice.  If you don't specify an I<invnum> you might want to
5310 call the B<apply_payments> method.
5311
5312 I<quiet> can be set true to surpress email decline notices.
5313
5314 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
5315 resulting paynum, if any.
5316
5317 I<payunique> is a unique identifier for this payment.
5318
5319 Returns a hashref containing elements bill_error (which will be undefined
5320 upon success) and session_id of any associated session.
5321
5322 =cut
5323
5324 sub realtime_botpp_capture {
5325   my( $self, $cust_pay_pending, %options ) = @_;
5326   if ( $DEBUG ) {
5327     warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
5328     warn "  $_ => $options{$_}\n" foreach keys %options;
5329   }
5330
5331   eval "use Business::OnlineThirdPartyPayment";  
5332   die $@ if $@;
5333
5334   ###
5335   # select the gateway
5336   ###
5337
5338   my $method = FS::payby->payby2bop($cust_pay_pending->payby);
5339
5340   my $payment_gateway = $cust_pay_pending->gatewaynum
5341     ? qsearchs( 'payment_gateway',
5342                 { gatewaynum => $cust_pay_pending->gatewaynum }
5343               )
5344     : $self->agent->payment_gateway( 'method' => $method,
5345                                      # 'invnum'  => $cust_pay_pending->invnum,
5346                                      # 'payinfo' => $cust_pay_pending->payinfo,
5347                                    );
5348
5349   $options{payment_gateway} = $payment_gateway; # for the helper subs
5350
5351   ###
5352   # massage data
5353   ###
5354
5355   my @invoicing_list = $self->invoicing_list_emailonly;
5356   if ( $conf->exists('emailinvoiceautoalways')
5357        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5358        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5359     push @invoicing_list, $self->all_emails;
5360   }
5361
5362   my $email = ($conf->exists('business-onlinepayment-email-override'))
5363               ? $conf->config('business-onlinepayment-email-override')
5364               : $invoicing_list[0];
5365
5366   my %content = ();
5367
5368   $content{email_customer} = 
5369     (    $conf->exists('business-onlinepayment-email_customer')
5370       || $conf->exists('business-onlinepayment-email-override') );
5371       
5372   ###
5373   # run transaction(s)
5374   ###
5375
5376   my $transaction =
5377     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
5378                                            $self->_bop_options(\%options),
5379                                          );
5380
5381   $transaction->reference({ %options }); 
5382
5383   $transaction->content(
5384     'type'           => $method,
5385     $self->_bop_auth(\%options),
5386     'action'         => 'Post Authorization',
5387     'description'    => $options{'description'},
5388     'amount'         => $cust_pay_pending->paid,
5389     #'invoice_number' => $options{'invnum'},
5390     'customer_id'    => $self->custnum,
5391     'referer'        => 'http://cleanwhisker.420.am/',
5392     'reference'      => $cust_pay_pending->paypendingnum,
5393     'email'          => $email,
5394     'phone'          => $self->daytime || $self->night,
5395     %content, #after
5396     # plus whatever is required for bogus capture avoidance
5397   );
5398
5399   $transaction->submit();
5400
5401   my $error =
5402     $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
5403
5404   {
5405     bill_error => $error,
5406     session_id => $cust_pay_pending->session_id,
5407   }
5408
5409 }
5410
5411 =item default_payment_gateway DEPRECATED -- use agent->payment_gateway
5412
5413 =cut
5414
5415 sub default_payment_gateway {
5416   my( $self, $method ) = @_;
5417
5418   die "Real-time processing not enabled\n"
5419     unless $conf->exists('business-onlinepayment');
5420
5421   #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
5422
5423   #load up config
5424   my $bop_config = 'business-onlinepayment';
5425   $bop_config .= '-ach'
5426     if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
5427   my ( $processor, $login, $password, $action, @bop_options ) =
5428     $conf->config($bop_config);
5429   $action ||= 'normal authorization';
5430   pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
5431   die "No real-time processor is enabled - ".
5432       "did you set the business-onlinepayment configuration value?\n"
5433     unless $processor;
5434
5435   ( $processor, $login, $password, $action, @bop_options )
5436 }
5437
5438 =item remove_cvv
5439
5440 Removes the I<paycvv> field from the database directly.
5441
5442 If there is an error, returns the error, otherwise returns false.
5443
5444 =cut
5445
5446 sub remove_cvv {
5447   my $self = shift;
5448   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
5449     or return dbh->errstr;
5450   $sth->execute($self->custnum)
5451     or return $sth->errstr;
5452   $self->paycvv('');
5453   '';
5454 }
5455
5456 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
5457
5458 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
5459 via a Business::OnlinePayment realtime gateway.  See
5460 L<http://420.am/business-onlinepayment> for supported gateways.
5461
5462 Available methods are: I<CC>, I<ECHECK> and I<LEC>
5463
5464 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
5465
5466 Most gateways require a reference to an original payment transaction to refund,
5467 so you probably need to specify a I<paynum>.
5468
5469 I<amount> defaults to the original amount of the payment if not specified.
5470
5471 I<reason> specifies a reason for the refund.
5472
5473 I<paydate> specifies the expiration date for a credit card overriding the
5474 value from the customer record or the payment record. Specified as yyyy-mm-dd
5475
5476 Implementation note: If I<amount> is unspecified or equal to the amount of the
5477 orignal payment, first an attempt is made to "void" the transaction via
5478 the gateway (to cancel a not-yet settled transaction) and then if that fails,
5479 the normal attempt is made to "refund" ("credit") the transaction via the
5480 gateway is attempted.
5481
5482 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
5483 #I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
5484 #if set, will override the value from the customer record.
5485
5486 #If an I<invnum> is specified, this payment (if successful) is applied to the
5487 #specified invoice.  If you don't specify an I<invnum> you might want to
5488 #call the B<apply_payments> method.
5489
5490 =cut
5491
5492 #some false laziness w/realtime_bop, not enough to make it worth merging
5493 #but some useful small subs should be pulled out
5494 sub realtime_refund_bop {
5495   my $self = shift;
5496
5497   my %options = ();
5498   if (ref($_[0]) eq 'HASH') {
5499     %options = %{$_[0]};
5500   } else {
5501     my $method = shift;
5502     %options = @_;
5503     $options{method} = $method;
5504   }
5505
5506   if ( $DEBUG ) {
5507     warn "$me realtime_refund_bop (new): $options{method} refund\n";
5508     warn "  $_ => $options{$_}\n" foreach keys %options;
5509   }
5510
5511   ###
5512   # look up the original payment and optionally a gateway for that payment
5513   ###
5514
5515   my $cust_pay = '';
5516   my $amount = $options{'amount'};
5517
5518   my( $processor, $login, $password, @bop_options, $namespace ) ;
5519   my( $auth, $order_number ) = ( '', '', '' );
5520
5521   if ( $options{'paynum'} ) {
5522
5523     warn "  paynum: $options{paynum}\n" if $DEBUG > 1;
5524     $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
5525       or return "Unknown paynum $options{'paynum'}";
5526     $amount ||= $cust_pay->paid;
5527
5528     $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
5529       or return "Can't parse paybatch for paynum $options{'paynum'}: ".
5530                 $cust_pay->paybatch;
5531     my $gatewaynum = '';
5532     ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
5533
5534     if ( $gatewaynum ) { #gateway for the payment to be refunded
5535
5536       my $payment_gateway =
5537         qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
5538       die "payment gateway $gatewaynum not found"
5539         unless $payment_gateway;
5540
5541       $processor   = $payment_gateway->gateway_module;
5542       $login       = $payment_gateway->gateway_username;
5543       $password    = $payment_gateway->gateway_password;
5544       $namespace   = $payment_gateway->gateway_namespace;
5545       @bop_options = $payment_gateway->options;
5546
5547     } else { #try the default gateway
5548
5549       my $conf_processor;
5550       my $payment_gateway =
5551         $self->agent->payment_gateway('method' => $options{method});
5552
5553       ( $conf_processor, $login, $password, $namespace ) =
5554         map { my $method = "gateway_$_"; $payment_gateway->$method }
5555           qw( module username password namespace );
5556
5557       @bop_options = $payment_gateway->gatewaynum
5558                        ? $payment_gateway->options
5559                        : @{ $payment_gateway->get('options') };
5560
5561       return "processor of payment $options{'paynum'} $processor does not".
5562              " match default processor $conf_processor"
5563         unless $processor eq $conf_processor;
5564
5565     }
5566
5567
5568   } else { # didn't specify a paynum, so look for agent gateway overrides
5569            # like a normal transaction 
5570  
5571     my $payment_gateway =
5572       $self->agent->payment_gateway( 'method'  => $options{method},
5573                                      #'payinfo' => $payinfo,
5574                                    );
5575     my( $processor, $login, $password, $namespace ) =
5576       map { my $method = "gateway_$_"; $payment_gateway->$method }
5577         qw( module username password namespace );
5578
5579     my @bop_options = $payment_gateway->gatewaynum
5580                         ? $payment_gateway->options
5581                         : @{ $payment_gateway->get('options') };
5582
5583   }
5584   return "neither amount nor paynum specified" unless $amount;
5585
5586   eval "use $namespace";  
5587   die $@ if $@;
5588
5589   my %content = (
5590     'type'           => $options{method},
5591     'login'          => $login,
5592     'password'       => $password,
5593     'order_number'   => $order_number,
5594     'amount'         => $amount,
5595     'referer'        => 'http://cleanwhisker.420.am/', #XXX fix referer :/
5596   );
5597   $content{authorization} = $auth
5598     if length($auth); #echeck/ACH transactions have an order # but no auth
5599                       #(at least with authorize.net)
5600
5601   my $disable_void_after;
5602   if ($conf->exists('disable_void_after')
5603       && $conf->config('disable_void_after') =~ /^(\d+)$/) {
5604     $disable_void_after = $1;
5605   }
5606
5607   #first try void if applicable
5608   if ( $cust_pay && $cust_pay->paid == $amount
5609     && (
5610       ( not defined($disable_void_after) )
5611       || ( time < ($cust_pay->_date + $disable_void_after ) )
5612     )
5613   ) {
5614     warn "  attempting void\n" if $DEBUG > 1;
5615     my $void = new Business::OnlinePayment( $processor, @bop_options );
5616     if ( $void->can('info') ) {
5617       if ( $cust_pay->payby eq 'CARD'
5618            && $void->info('CC_void_requires_card') )
5619       {
5620         $content{'card_number'} = $cust_pay->payinfo;
5621       } elsif ( $cust_pay->payby eq 'CHEK'
5622                 && $void->info('ECHECK_void_requires_account') )
5623       {
5624         ( $content{'account_number'}, $content{'routing_code'} ) =
5625           split('@', $cust_pay->payinfo);
5626         $content{'name'} = $self->get('first'). ' '. $self->get('last');
5627       }
5628     }
5629     $void->content( 'action' => 'void', %content );
5630     $void->test_transaction(1)
5631       if $conf->exists('business-onlinepayment-test_transaction');
5632     $void->submit();
5633     if ( $void->is_success ) {
5634       my $error = $cust_pay->void($options{'reason'});
5635       if ( $error ) {
5636         # gah, even with transactions.
5637         my $e = 'WARNING: Card/ACH voided but database not updated - '.
5638                 "error voiding payment: $error";
5639         warn $e;
5640         return $e;
5641       }
5642       warn "  void successful\n" if $DEBUG > 1;
5643       return '';
5644     }
5645   }
5646
5647   warn "  void unsuccessful, trying refund\n"
5648     if $DEBUG > 1;
5649
5650   #massage data
5651   my $address = $self->address1;
5652   $address .= ", ". $self->address2 if $self->address2;
5653
5654   my($payname, $payfirst, $paylast);
5655   if ( $self->payname && $options{method} ne 'ECHECK' ) {
5656     $payname = $self->payname;
5657     $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
5658       or return "Illegal payname $payname";
5659     ($payfirst, $paylast) = ($1, $2);
5660   } else {
5661     $payfirst = $self->getfield('first');
5662     $paylast = $self->getfield('last');
5663     $payname =  "$payfirst $paylast";
5664   }
5665
5666   my @invoicing_list = $self->invoicing_list_emailonly;
5667   if ( $conf->exists('emailinvoiceautoalways')
5668        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
5669        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
5670     push @invoicing_list, $self->all_emails;
5671   }
5672
5673   my $email = ($conf->exists('business-onlinepayment-email-override'))
5674               ? $conf->config('business-onlinepayment-email-override')
5675               : $invoicing_list[0];
5676
5677   my $payip = exists($options{'payip'})
5678                 ? $options{'payip'}
5679                 : $self->payip;
5680   $content{customer_ip} = $payip
5681     if length($payip);
5682
5683   my $payinfo = '';
5684   if ( $options{method} eq 'CC' ) {
5685
5686     if ( $cust_pay ) {
5687       $content{card_number} = $payinfo = $cust_pay->payinfo;
5688       (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
5689         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
5690         ($content{expiration} = "$2/$1");  # where available
5691     } else {
5692       $content{card_number} = $payinfo = $self->payinfo;
5693       (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
5694         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
5695       $content{expiration} = "$2/$1";
5696     }
5697
5698   } elsif ( $options{method} eq 'ECHECK' ) {
5699
5700     if ( $cust_pay ) {
5701       $payinfo = $cust_pay->payinfo;
5702     } else {
5703       $payinfo = $self->payinfo;
5704     } 
5705     ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
5706     $content{bank_name} = $self->payname;
5707     $content{account_type} = 'CHECKING';
5708     $content{account_name} = $payname;
5709     $content{customer_org} = $self->company ? 'B' : 'I';
5710     $content{customer_ssn} = $self->ss;
5711   } elsif ( $options{method} eq 'LEC' ) {
5712     $content{phone} = $payinfo = $self->payinfo;
5713   }
5714
5715   #then try refund
5716   my $refund = new Business::OnlinePayment( $processor, @bop_options );
5717   my %sub_content = $refund->content(
5718     'action'         => 'credit',
5719     'customer_id'    => $self->custnum,
5720     'last_name'      => $paylast,
5721     'first_name'     => $payfirst,
5722     'name'           => $payname,
5723     'address'        => $address,
5724     'city'           => $self->city,
5725     'state'          => $self->state,
5726     'zip'            => $self->zip,
5727     'country'        => $self->country,
5728     'email'          => $email,
5729     'phone'          => $self->daytime || $self->night,
5730     %content, #after
5731   );
5732   warn join('', map { "  $_ => $sub_content{$_}\n" } keys %sub_content )
5733     if $DEBUG > 1;
5734   $refund->test_transaction(1)
5735     if $conf->exists('business-onlinepayment-test_transaction');
5736   $refund->submit();
5737
5738   return "$processor error: ". $refund->error_message
5739     unless $refund->is_success();
5740
5741   my $paybatch = "$processor:". $refund->authorization;
5742   $paybatch .= ':'. $refund->order_number
5743     if $refund->can('order_number') && $refund->order_number;
5744
5745   while ( $cust_pay && $cust_pay->unapplied < $amount ) {
5746     my @cust_bill_pay = $cust_pay->cust_bill_pay;
5747     last unless @cust_bill_pay;
5748     my $cust_bill_pay = pop @cust_bill_pay;
5749     my $error = $cust_bill_pay->delete;
5750     last if $error;
5751   }
5752
5753   my $cust_refund = new FS::cust_refund ( {
5754     'custnum'  => $self->custnum,
5755     'paynum'   => $options{'paynum'},
5756     'refund'   => $amount,
5757     '_date'    => '',
5758     'payby'    => $bop_method2payby{$options{method}},
5759     'payinfo'  => $payinfo,
5760     'paybatch' => $paybatch,
5761     'reason'   => $options{'reason'} || 'card or ACH refund',
5762   } );
5763   my $error = $cust_refund->insert;
5764   if ( $error ) {
5765     $cust_refund->paynum(''); #try again with no specific paynum
5766     my $error2 = $cust_refund->insert;
5767     if ( $error2 ) {
5768       # gah, even with transactions.
5769       my $e = 'WARNING: Card/ACH refunded but database not updated - '.
5770               "error inserting refund ($processor): $error2".
5771               " (previously tried insert with paynum #$options{'paynum'}" .
5772               ": $error )";
5773       warn $e;
5774       return $e;
5775     }
5776   }
5777
5778   ''; #no error
5779
5780 }
5781
5782 =item batch_card OPTION => VALUE...
5783
5784 Adds a payment for this invoice to the pending credit card batch (see
5785 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
5786 runs the payment using a realtime gateway.
5787
5788 =cut
5789
5790 sub batch_card {
5791   my ($self, %options) = @_;
5792
5793   my $amount;
5794   if (exists($options{amount})) {
5795     $amount = $options{amount};
5796   }else{
5797     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
5798   }
5799   return '' unless $amount > 0;
5800   
5801   my $invnum = delete $options{invnum};
5802   my $payby = $options{invnum} || $self->payby;  #dubious
5803
5804   if ($options{'realtime'}) {
5805     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
5806                                 $amount,
5807                                 %options,
5808                               );
5809   }
5810
5811   my $oldAutoCommit = $FS::UID::AutoCommit;
5812   local $FS::UID::AutoCommit = 0;
5813   my $dbh = dbh;
5814
5815   #this needs to handle mysql as well as Pg, like svc_acct.pm
5816   #(make it into a common function if folks need to do batching with mysql)
5817   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
5818     or return "Cannot lock pay_batch: " . $dbh->errstr;
5819
5820   my %pay_batch = (
5821     'status' => 'O',
5822     'payby'  => FS::payby->payby2payment($payby),
5823   );
5824
5825   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
5826
5827   unless ( $pay_batch ) {
5828     $pay_batch = new FS::pay_batch \%pay_batch;
5829     my $error = $pay_batch->insert;
5830     if ( $error ) {
5831       $dbh->rollback if $oldAutoCommit;
5832       die "error creating new batch: $error\n";
5833     }
5834   }
5835
5836   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
5837       'batchnum' => $pay_batch->batchnum,
5838       'custnum'  => $self->custnum,
5839   } );
5840
5841   foreach (qw( address1 address2 city state zip country payby payinfo paydate
5842                payname )) {
5843     $options{$_} = '' unless exists($options{$_});
5844   }
5845
5846   my $cust_pay_batch = new FS::cust_pay_batch ( {
5847     'batchnum' => $pay_batch->batchnum,
5848     'invnum'   => $invnum || 0,                    # is there a better value?
5849                                                    # this field should be
5850                                                    # removed...
5851                                                    # cust_bill_pay_batch now
5852     'custnum'  => $self->custnum,
5853     'last'     => $self->getfield('last'),
5854     'first'    => $self->getfield('first'),
5855     'address1' => $options{address1} || $self->address1,
5856     'address2' => $options{address2} || $self->address2,
5857     'city'     => $options{city}     || $self->city,
5858     'state'    => $options{state}    || $self->state,
5859     'zip'      => $options{zip}      || $self->zip,
5860     'country'  => $options{country}  || $self->country,
5861     'payby'    => $options{payby}    || $self->payby,
5862     'payinfo'  => $options{payinfo}  || $self->payinfo,
5863     'exp'      => $options{paydate}  || $self->paydate,
5864     'payname'  => $options{payname}  || $self->payname,
5865     'amount'   => $amount,                         # consolidating
5866   } );
5867   
5868   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
5869     if $old_cust_pay_batch;
5870
5871   my $error;
5872   if ($old_cust_pay_batch) {
5873     $error = $cust_pay_batch->replace($old_cust_pay_batch)
5874   } else {
5875     $error = $cust_pay_batch->insert;
5876   }
5877
5878   if ( $error ) {
5879     $dbh->rollback if $oldAutoCommit;
5880     die $error;
5881   }
5882
5883   my $unapplied =   $self->total_unapplied_credits
5884                   + $self->total_unapplied_payments
5885                   + $self->in_transit_payments;
5886   foreach my $cust_bill ($self->open_cust_bill) {
5887     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
5888     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
5889       'invnum' => $cust_bill->invnum,
5890       'paybatchnum' => $cust_pay_batch->paybatchnum,
5891       'amount' => $cust_bill->owed,
5892       '_date' => time,
5893     };
5894     if ($unapplied >= $cust_bill_pay_batch->amount){
5895       $unapplied -= $cust_bill_pay_batch->amount;
5896       next;
5897     }else{
5898       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
5899                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
5900     }
5901     $error = $cust_bill_pay_batch->insert;
5902     if ( $error ) {
5903       $dbh->rollback if $oldAutoCommit;
5904       die $error;
5905     }
5906   }
5907
5908   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5909   '';
5910 }
5911
5912 =item apply_payments_and_credits [ OPTION => VALUE ... ]
5913
5914 Applies unapplied payments and credits.
5915
5916 In most cases, this new method should be used in place of sequential
5917 apply_payments and apply_credits methods.
5918
5919 A hash of optional arguments may be passed.  Currently "manual" is supported.
5920 If true, a payment receipt is sent instead of a statement when
5921 'payment_receipt_email' configuration option is set.
5922
5923 If there is an error, returns the error, otherwise returns false.
5924
5925 =cut
5926
5927 sub apply_payments_and_credits {
5928   my( $self, %options ) = @_;
5929
5930   local $SIG{HUP} = 'IGNORE';
5931   local $SIG{INT} = 'IGNORE';
5932   local $SIG{QUIT} = 'IGNORE';
5933   local $SIG{TERM} = 'IGNORE';
5934   local $SIG{TSTP} = 'IGNORE';
5935   local $SIG{PIPE} = 'IGNORE';
5936
5937   my $oldAutoCommit = $FS::UID::AutoCommit;
5938   local $FS::UID::AutoCommit = 0;
5939   my $dbh = dbh;
5940
5941   $self->select_for_update; #mutex
5942
5943   foreach my $cust_bill ( $self->open_cust_bill ) {
5944     my $error = $cust_bill->apply_payments_and_credits(%options);
5945     if ( $error ) {
5946       $dbh->rollback if $oldAutoCommit;
5947       return "Error applying: $error";
5948     }
5949   }
5950
5951   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5952   ''; #no error
5953
5954 }
5955
5956 =item apply_credits OPTION => VALUE ...
5957
5958 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
5959 to outstanding invoice balances in chronological order (or reverse
5960 chronological order if the I<order> option is set to B<newest>) and returns the
5961 value of any remaining unapplied credits available for refund (see
5962 L<FS::cust_refund>).
5963
5964 Dies if there is an error.
5965
5966 =cut
5967
5968 sub apply_credits {
5969   my $self = shift;
5970   my %opt = @_;
5971
5972   local $SIG{HUP} = 'IGNORE';
5973   local $SIG{INT} = 'IGNORE';
5974   local $SIG{QUIT} = 'IGNORE';
5975   local $SIG{TERM} = 'IGNORE';
5976   local $SIG{TSTP} = 'IGNORE';
5977   local $SIG{PIPE} = 'IGNORE';
5978
5979   my $oldAutoCommit = $FS::UID::AutoCommit;
5980   local $FS::UID::AutoCommit = 0;
5981   my $dbh = dbh;
5982
5983   $self->select_for_update; #mutex
5984
5985   unless ( $self->total_unapplied_credits ) {
5986     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5987     return 0;
5988   }
5989
5990   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
5991       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
5992
5993   my @invoices = $self->open_cust_bill;
5994   @invoices = sort { $b->_date <=> $a->_date } @invoices
5995     if defined($opt{'order'}) && $opt{'order'} eq 'newest';
5996
5997   if ( $conf->exists('pkg-balances') ) {
5998     # limit @credits to those w/ a pkgnum grepped from $self
5999     my %pkgnums = ();
6000     foreach my $i (@invoices) {
6001       foreach my $li ( $i->cust_bill_pkg ) {
6002         $pkgnums{$li->pkgnum} = 1;
6003       }
6004     }
6005     @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
6006   }
6007
6008   my $credit;
6009
6010   foreach my $cust_bill ( @invoices ) {
6011
6012     if ( !defined($credit) || $credit->credited == 0) {
6013       $credit = pop @credits or last;
6014     }
6015
6016     my $owed;
6017     if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
6018       $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
6019     } else {
6020       $owed = $cust_bill->owed;
6021     }
6022     unless ( $owed > 0 ) {
6023       push @credits, $credit;
6024       next;
6025     }
6026
6027     my $amount = min( $credit->credited, $owed );
6028     
6029     my $cust_credit_bill = new FS::cust_credit_bill ( {
6030       'crednum' => $credit->crednum,
6031       'invnum'  => $cust_bill->invnum,
6032       'amount'  => $amount,
6033     } );
6034     $cust_credit_bill->pkgnum( $credit->pkgnum )
6035       if $conf->exists('pkg-balances') && $credit->pkgnum;
6036     my $error = $cust_credit_bill->insert;
6037     if ( $error ) {
6038       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6039       die $error;
6040     }
6041     
6042     redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6043
6044   }
6045
6046   my $total_unapplied_credits = $self->total_unapplied_credits;
6047
6048   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6049
6050   return $total_unapplied_credits;
6051 }
6052
6053 =item apply_payments  [ OPTION => VALUE ... ]
6054
6055 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
6056 to outstanding invoice balances in chronological order.
6057
6058  #and returns the value of any remaining unapplied payments.
6059
6060 A hash of optional arguments may be passed.  Currently "manual" is supported.
6061 If true, a payment receipt is sent instead of a statement when
6062 'payment_receipt_email' configuration option is set.
6063
6064 Dies if there is an error.
6065
6066 =cut
6067
6068 sub apply_payments {
6069   my( $self, %options ) = @_;
6070
6071   local $SIG{HUP} = 'IGNORE';
6072   local $SIG{INT} = 'IGNORE';
6073   local $SIG{QUIT} = 'IGNORE';
6074   local $SIG{TERM} = 'IGNORE';
6075   local $SIG{TSTP} = 'IGNORE';
6076   local $SIG{PIPE} = 'IGNORE';
6077
6078   my $oldAutoCommit = $FS::UID::AutoCommit;
6079   local $FS::UID::AutoCommit = 0;
6080   my $dbh = dbh;
6081
6082   $self->select_for_update; #mutex
6083
6084   #return 0 unless
6085
6086   my @payments = sort { $b->_date <=> $a->_date }
6087                  grep { $_->unapplied > 0 }
6088                  $self->cust_pay;
6089
6090   my @invoices = sort { $a->_date <=> $b->_date}
6091                  grep { $_->owed > 0 }
6092                  $self->cust_bill;
6093
6094   if ( $conf->exists('pkg-balances') ) {
6095     # limit @payments to those w/ a pkgnum grepped from $self
6096     my %pkgnums = ();
6097     foreach my $i (@invoices) {
6098       foreach my $li ( $i->cust_bill_pkg ) {
6099         $pkgnums{$li->pkgnum} = 1;
6100       }
6101     }
6102     @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
6103   }
6104
6105   my $payment;
6106
6107   foreach my $cust_bill ( @invoices ) {
6108
6109     if ( !defined($payment) || $payment->unapplied == 0 ) {
6110       $payment = pop @payments or last;
6111     }
6112
6113     my $owed;
6114     if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
6115       $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
6116     } else {
6117       $owed = $cust_bill->owed;
6118     }
6119     unless ( $owed > 0 ) {
6120       push @payments, $payment;
6121       next;
6122     }
6123
6124     my $amount = min( $payment->unapplied, $owed );
6125
6126     my $cust_bill_pay = new FS::cust_bill_pay ( {
6127       'paynum' => $payment->paynum,
6128       'invnum' => $cust_bill->invnum,
6129       'amount' => $amount,
6130     } );
6131     $cust_bill_pay->pkgnum( $payment->pkgnum )
6132       if $conf->exists('pkg-balances') && $payment->pkgnum;
6133     my $error = $cust_bill_pay->insert(%options);
6134     if ( $error ) {
6135       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
6136       die $error;
6137     }
6138
6139     redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
6140
6141   }
6142
6143   my $total_unapplied_payments = $self->total_unapplied_payments;
6144
6145   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6146
6147   return $total_unapplied_payments;
6148 }
6149
6150 =item total_owed
6151
6152 Returns the total owed for this customer on all invoices
6153 (see L<FS::cust_bill/owed>).
6154
6155 =cut
6156
6157 sub total_owed {
6158   my $self = shift;
6159   $self->total_owed_date(2145859200); #12/31/2037
6160 }
6161
6162 =item total_owed_date TIME
6163
6164 Returns the total owed for this customer on all invoices with date earlier than
6165 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
6166 see L<Time::Local> and L<Date::Parse> for conversion functions.
6167
6168 =cut
6169
6170 sub total_owed_date {
6171   my $self = shift;
6172   my $time = shift;
6173
6174   my $custnum = $self->custnum;
6175
6176   my $owed_sql = FS::cust_bill->owed_sql;
6177
6178   my $sql = "
6179     SELECT SUM($owed_sql) FROM cust_bill
6180       WHERE custnum = $custnum
6181         AND _date <= $time
6182   ";
6183
6184   sprintf( "%.2f", $self->scalar_sql($sql) );
6185
6186 }
6187
6188 =item total_owed_pkgnum PKGNUM
6189
6190 Returns the total owed on all invoices for this customer's specific package
6191 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
6192
6193 =cut
6194
6195 sub total_owed_pkgnum {
6196   my( $self, $pkgnum ) = @_;
6197   $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
6198 }
6199
6200 =item total_owed_date_pkgnum TIME PKGNUM
6201
6202 Returns the total owed for this customer's specific package when using
6203 experimental package balances on all invoices with date earlier than
6204 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
6205 see L<Time::Local> and L<Date::Parse> for conversion functions.
6206
6207 =cut
6208
6209 sub total_owed_date_pkgnum {
6210   my( $self, $time, $pkgnum ) = @_;
6211
6212   my $total_bill = 0;
6213   foreach my $cust_bill (
6214     grep { $_->_date <= $time }
6215       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
6216   ) {
6217     $total_bill += $cust_bill->owed_pkgnum($pkgnum);
6218   }
6219   sprintf( "%.2f", $total_bill );
6220
6221 }
6222
6223 =item total_paid
6224
6225 Returns the total amount of all payments.
6226
6227 =cut
6228
6229 sub total_paid {
6230   my $self = shift;
6231   my $total = 0;
6232   $total += $_->paid foreach $self->cust_pay;
6233   sprintf( "%.2f", $total );
6234 }
6235
6236 =item total_unapplied_credits
6237
6238 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6239 customer.  See L<FS::cust_credit/credited>.
6240
6241 =item total_credited
6242
6243 Old name for total_unapplied_credits.  Don't use.
6244
6245 =cut
6246
6247 sub total_credited {
6248   #carp "total_credited deprecated, use total_unapplied_credits";
6249   shift->total_unapplied_credits(@_);
6250 }
6251
6252 sub total_unapplied_credits {
6253   my $self = shift;
6254
6255   my $custnum = $self->custnum;
6256
6257   my $unapplied_sql = FS::cust_credit->unapplied_sql;
6258
6259   my $sql = "
6260     SELECT SUM($unapplied_sql) FROM cust_credit
6261       WHERE custnum = $custnum
6262   ";
6263
6264   sprintf( "%.2f", $self->scalar_sql($sql) );
6265
6266 }
6267
6268 =item total_unapplied_credits_pkgnum PKGNUM
6269
6270 Returns the total outstanding credit (see L<FS::cust_credit>) for this
6271 customer.  See L<FS::cust_credit/credited>.
6272
6273 =cut
6274
6275 sub total_unapplied_credits_pkgnum {
6276   my( $self, $pkgnum ) = @_;
6277   my $total_credit = 0;
6278   $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
6279   sprintf( "%.2f", $total_credit );
6280 }
6281
6282
6283 =item total_unapplied_payments
6284
6285 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
6286 See L<FS::cust_pay/unapplied>.
6287
6288 =cut
6289
6290 sub total_unapplied_payments {
6291   my $self = shift;
6292
6293   my $custnum = $self->custnum;
6294
6295   my $unapplied_sql = FS::cust_pay->unapplied_sql;
6296
6297   my $sql = "
6298     SELECT SUM($unapplied_sql) FROM cust_pay
6299       WHERE custnum = $custnum
6300   ";
6301
6302   sprintf( "%.2f", $self->scalar_sql($sql) );
6303
6304 }
6305
6306 =item total_unapplied_payments_pkgnum PKGNUM
6307
6308 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
6309 specific package when using experimental package balances.  See
6310 L<FS::cust_pay/unapplied>.
6311
6312 =cut
6313
6314 sub total_unapplied_payments_pkgnum {
6315   my( $self, $pkgnum ) = @_;
6316   my $total_unapplied = 0;
6317   $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
6318   sprintf( "%.2f", $total_unapplied );
6319 }
6320
6321
6322 =item total_unapplied_refunds
6323
6324 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
6325 customer.  See L<FS::cust_refund/unapplied>.
6326
6327 =cut
6328
6329 sub total_unapplied_refunds {
6330   my $self = shift;
6331   my $custnum = $self->custnum;
6332
6333   my $unapplied_sql = FS::cust_refund->unapplied_sql;
6334
6335   my $sql = "
6336     SELECT SUM($unapplied_sql) FROM cust_refund
6337       WHERE custnum = $custnum
6338   ";
6339
6340   sprintf( "%.2f", $self->scalar_sql($sql) );
6341
6342 }
6343
6344 =item balance
6345
6346 Returns the balance for this customer (total_owed plus total_unrefunded, minus
6347 total_unapplied_credits minus total_unapplied_payments).
6348
6349 =cut
6350
6351 sub balance {
6352   my $self = shift;
6353   $self->balance_date_range;
6354 }
6355
6356 =item balance_date TIME
6357
6358 Returns the balance for this customer, only considering invoices with date
6359 earlier than TIME (total_owed_date minus total_credited minus
6360 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
6361 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
6362 functions.
6363
6364 =cut
6365
6366 sub balance_date {
6367   my $self = shift;
6368   $self->balance_date_range(shift);
6369 }
6370
6371 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
6372
6373 Returns the balance for this customer, optionally considering invoices with
6374 date earlier than START_TIME, and not later than END_TIME
6375 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
6376
6377 Times are specified as SQL fragments or numeric
6378 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
6379 L<Date::Parse> for conversion functions.  The empty string can be passed
6380 to disable that time constraint completely.
6381
6382 Available options are:
6383
6384 =over 4
6385
6386 =item unapplied_date
6387
6388 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
6389
6390 =back
6391
6392 =cut
6393
6394 sub balance_date_range {
6395   my $self = shift;
6396   my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
6397             ') FROM cust_main WHERE custnum='. $self->custnum;
6398   sprintf( '%.2f', $self->scalar_sql($sql) );
6399 }
6400
6401 =item balance_pkgnum PKGNUM
6402
6403 Returns the balance for this customer's specific package when using
6404 experimental package balances (total_owed plus total_unrefunded, minus
6405 total_unapplied_credits minus total_unapplied_payments)
6406
6407 =cut
6408
6409 sub balance_pkgnum {
6410   my( $self, $pkgnum ) = @_;
6411
6412   sprintf( "%.2f",
6413       $self->total_owed_pkgnum($pkgnum)
6414 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
6415 #    + $self->total_unapplied_refunds_pkgnum($pkgnum)
6416     - $self->total_unapplied_credits_pkgnum($pkgnum)
6417     - $self->total_unapplied_payments_pkgnum($pkgnum)
6418   );
6419 }
6420
6421 =item in_transit_payments
6422
6423 Returns the total of requests for payments for this customer pending in 
6424 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
6425
6426 =cut
6427
6428 sub in_transit_payments {
6429   my $self = shift;
6430   my $in_transit_payments = 0;
6431   foreach my $pay_batch ( qsearch('pay_batch', {
6432     'status' => 'I',
6433   } ) ) {
6434     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
6435       'batchnum' => $pay_batch->batchnum,
6436       'custnum' => $self->custnum,
6437     } ) ) {
6438       $in_transit_payments += $cust_pay_batch->amount;
6439     }
6440   }
6441   sprintf( "%.2f", $in_transit_payments );
6442 }
6443
6444 =item payment_info
6445
6446 Returns a hash of useful information for making a payment.
6447
6448 =over 4
6449
6450 =item balance
6451
6452 Current balance.
6453
6454 =item payby
6455
6456 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
6457 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
6458 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
6459
6460 =back
6461
6462 For credit card transactions:
6463
6464 =over 4
6465
6466 =item card_type 1
6467
6468 =item payname
6469
6470 Exact name on card
6471
6472 =back
6473
6474 For electronic check transactions:
6475
6476 =over 4
6477
6478 =item stateid_state
6479
6480 =back
6481
6482 =cut
6483
6484 sub payment_info {
6485   my $self = shift;
6486
6487   my %return = ();
6488
6489   $return{balance} = $self->balance;
6490
6491   $return{payname} = $self->payname
6492                      || ( $self->first. ' '. $self->get('last') );
6493
6494   $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
6495
6496   $return{payby} = $self->payby;
6497   $return{stateid_state} = $self->stateid_state;
6498
6499   if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
6500     $return{card_type} = cardtype($self->payinfo);
6501     $return{payinfo} = $self->paymask;
6502
6503     @return{'month', 'year'} = $self->paydate_monthyear;
6504
6505   }
6506
6507   if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
6508     my ($payinfo1, $payinfo2) = split '@', $self->paymask;
6509     $return{payinfo1} = $payinfo1;
6510     $return{payinfo2} = $payinfo2;
6511     $return{paytype}  = $self->paytype;
6512     $return{paystate} = $self->paystate;
6513
6514   }
6515
6516   #doubleclick protection
6517   my $_date = time;
6518   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
6519
6520   %return;
6521
6522 }
6523
6524 =item paydate_monthyear
6525
6526 Returns a two-element list consisting of the month and year of this customer's
6527 paydate (credit card expiration date for CARD customers)
6528
6529 =cut
6530
6531 sub paydate_monthyear {
6532   my $self = shift;
6533   if ( $self->paydate  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
6534     ( $2, $1 );
6535   } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
6536     ( $1, $3 );
6537   } else {
6538     ('', '');
6539   }
6540 }
6541
6542 =item tax_exemption TAXNAME
6543
6544 =cut
6545
6546 sub tax_exemption {
6547   my( $self, $taxname ) = @_;
6548
6549   qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
6550                                      'taxname' => $taxname,
6551                                    },
6552           );
6553 }
6554
6555 =item cust_main_exemption
6556
6557 =cut
6558
6559 sub cust_main_exemption {
6560   my $self = shift;
6561   qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
6562 }
6563
6564 =item invoicing_list [ ARRAYREF ]
6565
6566 If an arguement is given, sets these email addresses as invoice recipients
6567 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
6568 (except as warnings), so use check_invoicing_list first.
6569
6570 Returns a list of email addresses (with svcnum entries expanded).
6571
6572 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
6573 check it without disturbing anything by passing nothing.
6574
6575 This interface may change in the future.
6576
6577 =cut
6578
6579 sub invoicing_list {
6580   my( $self, $arrayref ) = @_;
6581
6582   if ( $arrayref ) {
6583     my @cust_main_invoice;
6584     if ( $self->custnum ) {
6585       @cust_main_invoice = 
6586         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6587     } else {
6588       @cust_main_invoice = ();
6589     }
6590     foreach my $cust_main_invoice ( @cust_main_invoice ) {
6591       #warn $cust_main_invoice->destnum;
6592       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
6593         #warn $cust_main_invoice->destnum;
6594         my $error = $cust_main_invoice->delete;
6595         warn $error if $error;
6596       }
6597     }
6598     if ( $self->custnum ) {
6599       @cust_main_invoice = 
6600         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6601     } else {
6602       @cust_main_invoice = ();
6603     }
6604     my %seen = map { $_->address => 1 } @cust_main_invoice;
6605     foreach my $address ( @{$arrayref} ) {
6606       next if exists $seen{$address} && $seen{$address};
6607       $seen{$address} = 1;
6608       my $cust_main_invoice = new FS::cust_main_invoice ( {
6609         'custnum' => $self->custnum,
6610         'dest'    => $address,
6611       } );
6612       my $error = $cust_main_invoice->insert;
6613       warn $error if $error;
6614     }
6615   }
6616   
6617   if ( $self->custnum ) {
6618     map { $_->address }
6619       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
6620   } else {
6621     ();
6622   }
6623
6624 }
6625
6626 =item check_invoicing_list ARRAYREF
6627
6628 Checks these arguements as valid input for the invoicing_list method.  If there
6629 is an error, returns the error, otherwise returns false.
6630
6631 =cut
6632
6633 sub check_invoicing_list {
6634   my( $self, $arrayref ) = @_;
6635
6636   foreach my $address ( @$arrayref ) {
6637
6638     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
6639       return 'Can\'t add FAX invoice destination with a blank FAX number.';
6640     }
6641
6642     my $cust_main_invoice = new FS::cust_main_invoice ( {
6643       'custnum' => $self->custnum,
6644       'dest'    => $address,
6645     } );
6646     my $error = $self->custnum
6647                 ? $cust_main_invoice->check
6648                 : $cust_main_invoice->checkdest
6649     ;
6650     return $error if $error;
6651
6652   }
6653
6654   return "Email address required"
6655     if $conf->exists('cust_main-require_invoicing_list_email')
6656     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
6657
6658   '';
6659 }
6660
6661 =item set_default_invoicing_list
6662
6663 Sets the invoicing list to all accounts associated with this customer,
6664 overwriting any previous invoicing list.
6665
6666 =cut
6667
6668 sub set_default_invoicing_list {
6669   my $self = shift;
6670   $self->invoicing_list($self->all_emails);
6671 }
6672
6673 =item all_emails
6674
6675 Returns the email addresses of all accounts provisioned for this customer.
6676
6677 =cut
6678
6679 sub all_emails {
6680   my $self = shift;
6681   my %list;
6682   foreach my $cust_pkg ( $self->all_pkgs ) {
6683     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
6684     my @svc_acct =
6685       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6686         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
6687           @cust_svc;
6688     $list{$_}=1 foreach map { $_->email } @svc_acct;
6689   }
6690   keys %list;
6691 }
6692
6693 =item invoicing_list_addpost
6694
6695 Adds postal invoicing to this customer.  If this customer is already configured
6696 to receive postal invoices, does nothing.
6697
6698 =cut
6699
6700 sub invoicing_list_addpost {
6701   my $self = shift;
6702   return if grep { $_ eq 'POST' } $self->invoicing_list;
6703   my @invoicing_list = $self->invoicing_list;
6704   push @invoicing_list, 'POST';
6705   $self->invoicing_list(\@invoicing_list);
6706 }
6707
6708 =item invoicing_list_emailonly
6709
6710 Returns the list of email invoice recipients (invoicing_list without non-email
6711 destinations such as POST and FAX).
6712
6713 =cut
6714
6715 sub invoicing_list_emailonly {
6716   my $self = shift;
6717   warn "$me invoicing_list_emailonly called"
6718     if $DEBUG;
6719   grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
6720 }
6721
6722 =item invoicing_list_emailonly_scalar
6723
6724 Returns the list of email invoice recipients (invoicing_list without non-email
6725 destinations such as POST and FAX) as a comma-separated scalar.
6726
6727 =cut
6728
6729 sub invoicing_list_emailonly_scalar {
6730   my $self = shift;
6731   warn "$me invoicing_list_emailonly_scalar called"
6732     if $DEBUG;
6733   join(', ', $self->invoicing_list_emailonly);
6734 }
6735
6736 =item referral_custnum_cust_main
6737
6738 Returns the customer who referred this customer (or the empty string, if
6739 this customer was not referred).
6740
6741 Note the difference with referral_cust_main method: This method,
6742 referral_custnum_cust_main returns the single customer (if any) who referred
6743 this customer, while referral_cust_main returns an array of customers referred
6744 BY this customer.
6745
6746 =cut
6747
6748 sub referral_custnum_cust_main {
6749   my $self = shift;
6750   return '' unless $self->referral_custnum;
6751   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6752 }
6753
6754 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
6755
6756 Returns an array of customers referred by this customer (referral_custnum set
6757 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
6758 customers referred by customers referred by this customer and so on, inclusive.
6759 The default behavior is DEPTH 1 (no recursion).
6760
6761 Note the difference with referral_custnum_cust_main method: This method,
6762 referral_cust_main, returns an array of customers referred BY this customer,
6763 while referral_custnum_cust_main returns the single customer (if any) who
6764 referred this customer.
6765
6766 =cut
6767
6768 sub referral_cust_main {
6769   my $self = shift;
6770   my $depth = @_ ? shift : 1;
6771   my $exclude = @_ ? shift : {};
6772
6773   my @cust_main =
6774     map { $exclude->{$_->custnum}++; $_; }
6775       grep { ! $exclude->{ $_->custnum } }
6776         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
6777
6778   if ( $depth > 1 ) {
6779     push @cust_main,
6780       map { $_->referral_cust_main($depth-1, $exclude) }
6781         @cust_main;
6782   }
6783
6784   @cust_main;
6785 }
6786
6787 =item referral_cust_main_ncancelled
6788
6789 Same as referral_cust_main, except only returns customers with uncancelled
6790 packages.
6791
6792 =cut
6793
6794 sub referral_cust_main_ncancelled {
6795   my $self = shift;
6796   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
6797 }
6798
6799 =item referral_cust_pkg [ DEPTH ]
6800
6801 Like referral_cust_main, except returns a flat list of all unsuspended (and
6802 uncancelled) packages for each customer.  The number of items in this list may
6803 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
6804
6805 =cut
6806
6807 sub referral_cust_pkg {
6808   my $self = shift;
6809   my $depth = @_ ? shift : 1;
6810
6811   map { $_->unsuspended_pkgs }
6812     grep { $_->unsuspended_pkgs }
6813       $self->referral_cust_main($depth);
6814 }
6815
6816 =item referring_cust_main
6817
6818 Returns the single cust_main record for the customer who referred this customer
6819 (referral_custnum), or false.
6820
6821 =cut
6822
6823 sub referring_cust_main {
6824   my $self = shift;
6825   return '' unless $self->referral_custnum;
6826   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
6827 }
6828
6829 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
6830
6831 Applies a credit to this customer.  If there is an error, returns the error,
6832 otherwise returns false.
6833
6834 REASON can be a text string, an FS::reason object, or a scalar reference to
6835 a reasonnum.  If a text string, it will be automatically inserted as a new
6836 reason, and a 'reason_type' option must be passed to indicate the
6837 FS::reason_type for the new reason.
6838
6839 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
6840
6841 Any other options are passed to FS::cust_credit::insert.
6842
6843 =cut
6844
6845 sub credit {
6846   my( $self, $amount, $reason, %options ) = @_;
6847
6848   my $cust_credit = new FS::cust_credit {
6849     'custnum' => $self->custnum,
6850     'amount'  => $amount,
6851   };
6852
6853   if ( ref($reason) ) {
6854
6855     if ( ref($reason) eq 'SCALAR' ) {
6856       $cust_credit->reasonnum( $$reason );
6857     } else {
6858       $cust_credit->reasonnum( $reason->reasonnum );
6859     }
6860
6861   } else {
6862     $cust_credit->set('reason', $reason)
6863   }
6864
6865   for (qw( addlinfo eventnum )) {
6866     $cust_credit->$_( delete $options{$_} )
6867       if exists($options{$_});
6868   }
6869
6870   $cust_credit->insert(%options);
6871
6872 }
6873
6874 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
6875
6876 Creates a one-time charge for this customer.  If there is an error, returns
6877 the error, otherwise returns false.
6878
6879 New-style, with a hashref of options:
6880
6881   my $error = $cust_main->charge(
6882                                   {
6883                                     'amount'     => 54.32,
6884                                     'quantity'   => 1,
6885                                     'start_date' => str2time('7/4/2009'),
6886                                     'pkg'        => 'Description',
6887                                     'comment'    => 'Comment',
6888                                     'additional' => [], #extra invoice detail
6889                                     'classnum'   => 1,  #pkg_class
6890
6891                                     'setuptax'   => '', # or 'Y' for tax exempt
6892
6893                                     #internal taxation
6894                                     'taxclass'   => 'Tax class',
6895
6896                                     #vendor taxation
6897                                     'taxproduct' => 2,  #part_pkg_taxproduct
6898                                     'override'   => {}, #XXX describe
6899
6900                                     #will be filled in with the new object
6901                                     'cust_pkg_ref' => \$cust_pkg,
6902
6903                                     #generate an invoice immediately
6904                                     'bill_now' => 0,
6905                                     'invoice_terms' => '', #with these terms
6906                                   }
6907                                 );
6908
6909 Old-style:
6910
6911   my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
6912
6913 =cut
6914
6915 sub charge {
6916   my $self = shift;
6917   my ( $amount, $quantity, $start_date, $classnum );
6918   my ( $pkg, $comment, $additional );
6919   my ( $setuptax, $taxclass );   #internal taxes
6920   my ( $taxproduct, $override ); #vendor (CCH) taxes
6921   my $no_auto = '';
6922   my $cust_pkg_ref = '';
6923   my ( $bill_now, $invoice_terms ) = ( 0, '' );
6924   if ( ref( $_[0] ) ) {
6925     $amount     = $_[0]->{amount};
6926     $quantity   = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
6927     $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
6928     $no_auto    = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
6929     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
6930     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
6931                                            : '$'. sprintf("%.2f",$amount);
6932     $setuptax   = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
6933     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
6934     $classnum   = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
6935     $additional = $_[0]->{additional} || [];
6936     $taxproduct = $_[0]->{taxproductnum};
6937     $override   = { '' => $_[0]->{tax_override} };
6938     $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
6939     $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
6940     $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
6941   } else {
6942     $amount     = shift;
6943     $quantity   = 1;
6944     $start_date = '';
6945     $pkg        = @_ ? shift : 'One-time charge';
6946     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
6947     $setuptax   = '';
6948     $taxclass   = @_ ? shift : '';
6949     $additional = [];
6950   }
6951
6952   local $SIG{HUP} = 'IGNORE';
6953   local $SIG{INT} = 'IGNORE';
6954   local $SIG{QUIT} = 'IGNORE';
6955   local $SIG{TERM} = 'IGNORE';
6956   local $SIG{TSTP} = 'IGNORE';
6957   local $SIG{PIPE} = 'IGNORE';
6958
6959   my $oldAutoCommit = $FS::UID::AutoCommit;
6960   local $FS::UID::AutoCommit = 0;
6961   my $dbh = dbh;
6962
6963   my $part_pkg = new FS::part_pkg ( {
6964     'pkg'           => $pkg,
6965     'comment'       => $comment,
6966     'plan'          => 'flat',
6967     'freq'          => 0,
6968     'disabled'      => 'Y',
6969     'classnum'      => ( $classnum ? $classnum : '' ),
6970     'setuptax'      => $setuptax,
6971     'taxclass'      => $taxclass,
6972     'taxproductnum' => $taxproduct,
6973   } );
6974
6975   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
6976                         ( 0 .. @$additional - 1 )
6977                   ),
6978                   'additional_count' => scalar(@$additional),
6979                   'setup_fee' => $amount,
6980                 );
6981
6982   my $error = $part_pkg->insert( options       => \%options,
6983                                  tax_overrides => $override,
6984                                );
6985   if ( $error ) {
6986     $dbh->rollback if $oldAutoCommit;
6987     return $error;
6988   }
6989
6990   my $pkgpart = $part_pkg->pkgpart;
6991   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
6992   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
6993     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
6994     $error = $type_pkgs->insert;
6995     if ( $error ) {
6996       $dbh->rollback if $oldAutoCommit;
6997       return $error;
6998     }
6999   }
7000
7001   my $cust_pkg = new FS::cust_pkg ( {
7002     'custnum'    => $self->custnum,
7003     'pkgpart'    => $pkgpart,
7004     'quantity'   => $quantity,
7005     'start_date' => $start_date,
7006     'no_auto'    => $no_auto,
7007   } );
7008
7009   $error = $cust_pkg->insert;
7010   if ( $error ) {
7011     $dbh->rollback if $oldAutoCommit;
7012     return $error;
7013   } elsif ( $cust_pkg_ref ) {
7014     ${$cust_pkg_ref} = $cust_pkg;
7015   }
7016
7017   if ( $bill_now ) {
7018     my $error = $self->bill( 'invoice_terms' => $invoice_terms,
7019                              'pkg_list'      => [ $cust_pkg ],
7020                            );
7021     if ( $error ) {
7022       $dbh->rollback if $oldAutoCommit;
7023       return $error;
7024     }   
7025   }
7026
7027   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
7028   return '';
7029
7030 }
7031
7032 #=item charge_postal_fee
7033 #
7034 #Applies a one time charge this customer.  If there is an error,
7035 #returns the error, returns the cust_pkg charge object or false
7036 #if there was no charge.
7037 #
7038 #=cut
7039 #
7040 # This should be a customer event.  For that to work requires that bill
7041 # also be a customer event.
7042
7043 sub charge_postal_fee {
7044   my $self = shift;
7045
7046   my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
7047   return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
7048
7049   my $cust_pkg = new FS::cust_pkg ( {
7050     'custnum'  => $self->custnum,
7051     'pkgpart'  => $pkgpart,
7052     'quantity' => 1,
7053   } );
7054
7055   my $error = $cust_pkg->insert;
7056   $error ? $error : $cust_pkg;
7057 }
7058
7059 =item cust_bill
7060
7061 Returns all the invoices (see L<FS::cust_bill>) for this customer.
7062
7063 =cut
7064
7065 sub cust_bill {
7066   my $self = shift;
7067   map { $_ } #return $self->num_cust_bill unless wantarray;
7068   sort { $a->_date <=> $b->_date }
7069     qsearch('cust_bill', { 'custnum' => $self->custnum, } )
7070 }
7071
7072 =item open_cust_bill
7073
7074 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
7075 customer.
7076
7077 =cut
7078
7079 sub open_cust_bill {
7080   my $self = shift;
7081
7082   qsearch({
7083     'table'     => 'cust_bill',
7084     'hashref'   => { 'custnum' => $self->custnum, },
7085     'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
7086     'order_by'  => 'ORDER BY _date ASC',
7087   });
7088
7089 }
7090
7091 =item cust_statements
7092
7093 Returns all the statements (see L<FS::cust_statement>) for this customer.
7094
7095 =cut
7096
7097 sub cust_statement {
7098   my $self = shift;
7099   map { $_ } #return $self->num_cust_statement unless wantarray;
7100   sort { $a->_date <=> $b->_date }
7101     qsearch('cust_statement', { 'custnum' => $self->custnum, } )
7102 }
7103
7104 =item cust_credit
7105
7106 Returns all the credits (see L<FS::cust_credit>) for this customer.
7107
7108 =cut
7109
7110 sub cust_credit {
7111   my $self = shift;
7112   map { $_ } #return $self->num_cust_credit unless wantarray;
7113   sort { $a->_date <=> $b->_date }
7114     qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
7115 }
7116
7117 =item cust_credit_pkgnum
7118
7119 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
7120 package when using experimental package balances.
7121
7122 =cut
7123
7124 sub cust_credit_pkgnum {
7125   my( $self, $pkgnum ) = @_;
7126   map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
7127   sort { $a->_date <=> $b->_date }
7128     qsearch( 'cust_credit', { 'custnum' => $self->custnum,
7129                               'pkgnum'  => $pkgnum,
7130                             }
7131     );
7132 }
7133
7134 =item cust_pay
7135
7136 Returns all the payments (see L<FS::cust_pay>) for this customer.
7137
7138 =cut
7139
7140 sub cust_pay {
7141   my $self = shift;
7142   return $self->num_cust_pay unless wantarray;
7143   sort { $a->_date <=> $b->_date }
7144     qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
7145 }
7146
7147 =item num_cust_pay
7148
7149 Returns the number of payments (see L<FS::cust_pay>) for this customer.  Also
7150 called automatically when the cust_pay method is used in a scalar context.
7151
7152 =cut
7153
7154 sub num_cust_pay {
7155   my $self = shift;
7156   my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
7157   my $sth = dbh->prepare($sql) or die dbh->errstr;
7158   $sth->execute($self->custnum) or die $sth->errstr;
7159   $sth->fetchrow_arrayref->[0];
7160 }
7161
7162 =item cust_pay_pkgnum
7163
7164 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
7165 package when using experimental package balances.
7166
7167 =cut
7168
7169 sub cust_pay_pkgnum {
7170   my( $self, $pkgnum ) = @_;
7171   map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
7172   sort { $a->_date <=> $b->_date }
7173     qsearch( 'cust_pay', { 'custnum' => $self->custnum,
7174                            'pkgnum'  => $pkgnum,
7175                          }
7176     );
7177 }
7178
7179 =item cust_pay_void
7180
7181 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
7182
7183 =cut
7184
7185 sub cust_pay_void {
7186   my $self = shift;
7187   map { $_ } #return $self->num_cust_pay_void unless wantarray;
7188   sort { $a->_date <=> $b->_date }
7189     qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
7190 }
7191
7192 =item cust_pay_batch
7193
7194 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
7195
7196 =cut
7197
7198 sub cust_pay_batch {
7199   my $self = shift;
7200   map { $_ } #return $self->num_cust_pay_batch unless wantarray;
7201   sort { $a->paybatchnum <=> $b->paybatchnum }
7202     qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
7203 }
7204
7205 =item cust_pay_pending
7206
7207 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
7208 (without status "done").
7209
7210 =cut
7211
7212 sub cust_pay_pending {
7213   my $self = shift;
7214   return $self->num_cust_pay_pending unless wantarray;
7215   sort { $a->_date <=> $b->_date }
7216     qsearch( 'cust_pay_pending', {
7217                                    'custnum' => $self->custnum,
7218                                    'status'  => { op=>'!=', value=>'done' },
7219                                  },
7220            );
7221 }
7222
7223 =item cust_pay_pending_attempt
7224
7225 Returns all payment attempts / declined payments for this customer, as pending
7226 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
7227 a corresponding payment (see L<FS::cust_pay>).
7228
7229 =cut
7230
7231 sub cust_pay_pending_attempt {
7232   my $self = shift;
7233   return $self->num_cust_pay_pending_attempt unless wantarray;
7234   sort { $a->_date <=> $b->_date }
7235     qsearch( 'cust_pay_pending', {
7236                                    'custnum' => $self->custnum,
7237                                    'status'  => 'done',
7238                                    'paynum'  => '',
7239                                  },
7240            );
7241 }
7242
7243 =item num_cust_pay_pending
7244
7245 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7246 customer (without status "done").  Also called automatically when the
7247 cust_pay_pending method is used in a scalar context.
7248
7249 =cut
7250
7251 sub num_cust_pay_pending {
7252   my $self = shift;
7253   $self->scalar_sql(
7254     " SELECT COUNT(*) FROM cust_pay_pending ".
7255       " WHERE custnum = ? AND status != 'done' ",
7256     $self->custnum
7257   );
7258 }
7259
7260 =item num_cust_pay_pending_attempt
7261
7262 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
7263 customer, with status "done" but without a corresp.  Also called automatically when the
7264 cust_pay_pending method is used in a scalar context.
7265
7266 =cut
7267
7268 sub num_cust_pay_pending_attempt {
7269   my $self = shift;
7270   $self->scalar_sql(
7271     " SELECT COUNT(*) FROM cust_pay_pending ".
7272       " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
7273     $self->custnum
7274   );
7275 }
7276
7277 =item cust_refund
7278
7279 Returns all the refunds (see L<FS::cust_refund>) for this customer.
7280
7281 =cut
7282
7283 sub cust_refund {
7284   my $self = shift;
7285   map { $_ } #return $self->num_cust_refund unless wantarray;
7286   sort { $a->_date <=> $b->_date }
7287     qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
7288 }
7289
7290 =item display_custnum
7291
7292 Returns the displayed customer number for this customer: agent_custid if
7293 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
7294
7295 =cut
7296
7297 sub display_custnum {
7298   my $self = shift;
7299   if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
7300     return $self->agent_custid;
7301   } else {
7302     return $self->custnum;
7303   }
7304 }
7305
7306 =item name
7307
7308 Returns a name string for this customer, either "Company (Last, First)" or
7309 "Last, First".
7310
7311 =cut
7312
7313 sub name {
7314   my $self = shift;
7315   my $name = $self->contact;
7316   $name = $self->company. " ($name)" if $self->company;
7317   $name;
7318 }
7319
7320 =item ship_name
7321
7322 Returns a name string for this (service/shipping) contact, either
7323 "Company (Last, First)" or "Last, First".
7324
7325 =cut
7326
7327 sub ship_name {
7328   my $self = shift;
7329   if ( $self->get('ship_last') ) { 
7330     my $name = $self->ship_contact;
7331     $name = $self->ship_company. " ($name)" if $self->ship_company;
7332     $name;
7333   } else {
7334     $self->name;
7335   }
7336 }
7337
7338 =item name_short
7339
7340 Returns a name string for this customer, either "Company" or "First Last".
7341
7342 =cut
7343
7344 sub name_short {
7345   my $self = shift;
7346   $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
7347 }
7348
7349 =item ship_name_short
7350
7351 Returns a name string for this (service/shipping) contact, either "Company"
7352 or "First Last".
7353
7354 =cut
7355
7356 sub ship_name_short {
7357   my $self = shift;
7358   if ( $self->get('ship_last') ) { 
7359     $self->ship_company !~ /^\s*$/
7360       ? $self->ship_company
7361       : $self->ship_contact_firstlast;
7362   } else {
7363     $self->name_company_or_firstlast;
7364   }
7365 }
7366
7367 =item contact
7368
7369 Returns this customer's full (billing) contact name only, "Last, First"
7370
7371 =cut
7372
7373 sub contact {
7374   my $self = shift;
7375   $self->get('last'). ', '. $self->first;
7376 }
7377
7378 =item ship_contact
7379
7380 Returns this customer's full (shipping) contact name only, "Last, First"
7381
7382 =cut
7383
7384 sub ship_contact {
7385   my $self = shift;
7386   $self->get('ship_last')
7387     ? $self->get('ship_last'). ', '. $self->ship_first
7388     : $self->contact;
7389 }
7390
7391 =item contact_firstlast
7392
7393 Returns this customers full (billing) contact name only, "First Last".
7394
7395 =cut
7396
7397 sub contact_firstlast {
7398   my $self = shift;
7399   $self->first. ' '. $self->get('last');
7400 }
7401
7402 =item ship_contact_firstlast
7403
7404 Returns this customer's full (shipping) contact name only, "First Last".
7405
7406 =cut
7407
7408 sub ship_contact_firstlast {
7409   my $self = shift;
7410   $self->get('ship_last')
7411     ? $self->first. ' '. $self->get('ship_last')
7412     : $self->contact_firstlast;
7413 }
7414
7415 =item country_full
7416
7417 Returns this customer's full country name
7418
7419 =cut
7420
7421 sub country_full {
7422   my $self = shift;
7423   code2country($self->country);
7424 }
7425
7426 =item geocode DATA_VENDOR
7427
7428 Returns a value for the customer location as encoded by DATA_VENDOR.
7429 Currently this only makes sense for "CCH" as DATA_VENDOR.
7430
7431 =cut
7432
7433 sub geocode {
7434   my ($self, $data_vendor) = (shift, shift);  #always cch for now
7435
7436   my $geocode = $self->get('geocode');  #XXX only one data_vendor for geocode
7437   return $geocode if $geocode;
7438
7439   my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
7440                ? 'ship_'
7441                : '';
7442
7443   my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
7444     if $self->country eq 'US';
7445
7446   $zip ||= '';
7447   $plus4 ||= '';
7448   #CCH specific location stuff
7449   my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
7450
7451   my @cust_tax_location =
7452     qsearch( {
7453                'table'     => 'cust_tax_location', 
7454                'hashref'   => { 'zip' => $zip, 'data_vendor' => $data_vendor },
7455                'extra_sql' => $extra_sql,
7456                'order_by'  => 'ORDER BY plus4hi',#overlapping with distinct ends
7457              }
7458            );
7459   $geocode = $cust_tax_location[0]->geocode
7460     if scalar(@cust_tax_location);
7461
7462   $geocode;
7463 }
7464
7465 =item cust_status
7466
7467 =item status
7468
7469 Returns a status string for this customer, currently:
7470
7471 =over 4
7472
7473 =item prospect - No packages have ever been ordered
7474
7475 =item ordered - Recurring packages all are new (not yet billed).
7476
7477 =item active - One or more recurring packages is active
7478
7479 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
7480
7481 =item suspended - All non-cancelled recurring packages are suspended
7482
7483 =item cancelled - All recurring packages are cancelled
7484
7485 =back
7486
7487 =cut
7488
7489 sub status { shift->cust_status(@_); }
7490
7491 sub cust_status {
7492   my $self = shift;
7493   # prospect ordered active inactive suspended cancelled
7494   for my $status ( FS::cust_main->statuses() ) {
7495     my $method = $status.'_sql';
7496     my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
7497     my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
7498     $sth->execute( ($self->custnum) x $numnum )
7499       or die "Error executing 'SELECT $sql': ". $sth->errstr;
7500     return $status if $sth->fetchrow_arrayref->[0];
7501   }
7502 }
7503
7504 =item ucfirst_cust_status
7505
7506 =item ucfirst_status
7507
7508 Returns the status with the first character capitalized.
7509
7510 =cut
7511
7512 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
7513
7514 sub ucfirst_cust_status {
7515   my $self = shift;
7516   ucfirst($self->cust_status);
7517 }
7518
7519 =item statuscolor
7520
7521 Returns a hex triplet color string for this customer's status.
7522
7523 =cut
7524
7525 use vars qw(%statuscolor);
7526 tie %statuscolor, 'Tie::IxHash',
7527   'prospect'  => '7e0079', #'000000', #black?  naw, purple
7528   'active'    => '00CC00', #green
7529   'ordered'   => '009999', #teal? cyan?
7530   'inactive'  => '0000CC', #blue
7531   'suspended' => 'FF9900', #yellow
7532   'cancelled' => 'FF0000', #red
7533 ;
7534
7535 sub statuscolor { shift->cust_statuscolor(@_); }
7536
7537 sub cust_statuscolor {
7538   my $self = shift;
7539   $statuscolor{$self->cust_status};
7540 }
7541
7542 =item tickets
7543
7544 Returns an array of hashes representing the customer's RT tickets.
7545
7546 =cut
7547
7548 sub tickets {
7549   my $self = shift;
7550
7551   my $num = $conf->config('cust_main-max_tickets') || 10;
7552   my @tickets = ();
7553
7554   if ( $conf->config('ticket_system') ) {
7555     unless ( $conf->config('ticket_system-custom_priority_field') ) {
7556
7557       @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
7558
7559     } else {
7560
7561       foreach my $priority (
7562         $conf->config('ticket_system-custom_priority_field-values'), ''
7563       ) {
7564         last if scalar(@tickets) >= $num;
7565         push @tickets, 
7566           @{ FS::TicketSystem->customer_tickets( $self->custnum,
7567                                                  $num - scalar(@tickets),
7568                                                  $priority,
7569                                                )
7570            };
7571       }
7572     }
7573   }
7574   (@tickets);
7575 }
7576
7577 # Return services representing svc_accts in customer support packages
7578 sub support_services {
7579   my $self = shift;
7580   my %packages = map { $_ => 1 } $conf->config('support_packages');
7581
7582   grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
7583     grep { $_->part_svc->svcdb eq 'svc_acct' }
7584     map { $_->cust_svc }
7585     grep { exists $packages{ $_->pkgpart } }
7586     $self->ncancelled_pkgs;
7587
7588 }
7589
7590 # Return a list of latitude/longitude for one of the services (if any)
7591 sub service_coordinates {
7592   my $self = shift;
7593
7594   my @svc_X = 
7595     grep { $_->latitude && $_->longitude }
7596     map { $_->svc_x }
7597     map { $_->cust_svc }
7598     $self->ncancelled_pkgs;
7599
7600   scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
7601 }
7602
7603 =back
7604
7605 =head1 CLASS METHODS
7606
7607 =over 4
7608
7609 =item statuses
7610
7611 Class method that returns the list of possible status strings for customers
7612 (see L<the status method|/status>).  For example:
7613
7614   @statuses = FS::cust_main->statuses();
7615
7616 =cut
7617
7618 sub statuses {
7619   #my $self = shift; #could be class...
7620   keys %statuscolor;
7621 }
7622
7623 =item prospect_sql
7624
7625 Returns an SQL expression identifying prospective cust_main records (customers
7626 with no packages ever ordered)
7627
7628 =cut
7629
7630 use vars qw($select_count_pkgs);
7631 $select_count_pkgs =
7632   "SELECT COUNT(*) FROM cust_pkg
7633     WHERE cust_pkg.custnum = cust_main.custnum";
7634
7635 sub select_count_pkgs_sql {
7636   $select_count_pkgs;
7637 }
7638
7639 sub prospect_sql {
7640   " 0 = ( $select_count_pkgs ) ";
7641 }
7642
7643 =item ordered_sql
7644
7645 Returns an SQL expression identifying ordered cust_main records (customers with
7646 recurring packages not yet setup).
7647
7648 =cut
7649
7650 sub ordered_sql {
7651   FS::cust_main->none_active_sql.
7652   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
7653 }
7654
7655 =item active_sql
7656
7657 Returns an SQL expression identifying active cust_main records (customers with
7658 active recurring packages).
7659
7660 =cut
7661
7662 sub active_sql {
7663   " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7664 }
7665
7666 =item none_active_sql
7667
7668 Returns an SQL expression identifying cust_main records with no active
7669 recurring packages.  This includes customers of status prospect, ordered,
7670 inactive, and suspended.
7671
7672 =cut
7673
7674 sub none_active_sql {
7675   " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
7676 }
7677
7678 =item inactive_sql
7679
7680 Returns an SQL expression identifying inactive cust_main records (customers with
7681 no active recurring packages, but otherwise unsuspended/uncancelled).
7682
7683 =cut
7684
7685 sub inactive_sql {
7686   FS::cust_main->none_active_sql.
7687   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
7688 }
7689
7690 =item susp_sql
7691 =item suspended_sql
7692
7693 Returns an SQL expression identifying suspended cust_main records.
7694
7695 =cut
7696
7697
7698 sub suspended_sql { susp_sql(@_); }
7699 sub susp_sql {
7700   FS::cust_main->none_active_sql.
7701   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
7702 }
7703
7704 =item cancel_sql
7705 =item cancelled_sql
7706
7707 Returns an SQL expression identifying cancelled cust_main records.
7708
7709 =cut
7710
7711 sub cancelled_sql { cancel_sql(@_); }
7712 sub cancel_sql {
7713
7714   my $recurring_sql = FS::cust_pkg->recurring_sql;
7715   my $cancelled_sql = FS::cust_pkg->cancelled_sql;
7716
7717   "
7718         0 < ( $select_count_pkgs )
7719     AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql   )
7720     AND 0 = ( $select_count_pkgs AND $recurring_sql
7721                   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
7722             )
7723     AND 0 = (  $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
7724   ";
7725
7726 }
7727
7728 =item uncancel_sql
7729 =item uncancelled_sql
7730
7731 Returns an SQL expression identifying un-cancelled cust_main records.
7732
7733 =cut
7734
7735 sub uncancelled_sql { uncancel_sql(@_); }
7736 sub uncancel_sql { "
7737   ( 0 < ( $select_count_pkgs
7738                    AND ( cust_pkg.cancel IS NULL
7739                          OR cust_pkg.cancel = 0
7740                        )
7741         )
7742     OR 0 = ( $select_count_pkgs )
7743   )
7744 "; }
7745
7746 =item balance_sql
7747
7748 Returns an SQL fragment to retreive the balance.
7749
7750 =cut
7751
7752 sub balance_sql { "
7753     ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
7754         WHERE cust_bill.custnum   = cust_main.custnum     )
7755   - ( SELECT COALESCE( SUM(paid),    0 ) FROM cust_pay
7756         WHERE cust_pay.custnum    = cust_main.custnum     )
7757   - ( SELECT COALESCE( SUM(amount),  0 ) FROM cust_credit
7758         WHERE cust_credit.custnum = cust_main.custnum     )
7759   + ( SELECT COALESCE( SUM(refund),  0 ) FROM cust_refund
7760         WHERE cust_refund.custnum = cust_main.custnum     )
7761 "; }
7762
7763 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
7764
7765 Returns an SQL fragment to retreive the balance for this customer, optionally
7766 considering invoices with date earlier than START_TIME, and not
7767 later than END_TIME (total_owed_date minus total_unapplied_credits minus
7768 total_unapplied_payments).
7769
7770 Times are specified as SQL fragments or numeric
7771 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
7772 L<Date::Parse> for conversion functions.  The empty string can be passed
7773 to disable that time constraint completely.
7774
7775 Available options are:
7776
7777 =over 4
7778
7779 =item unapplied_date
7780
7781 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
7782
7783 =item total
7784
7785 (unused.  obsolete?)
7786 set to true to remove all customer comparison clauses, for totals
7787
7788 =item where
7789
7790 (unused.  obsolete?)
7791 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
7792
7793 =item join
7794
7795 (unused.  obsolete?)
7796 JOIN clause (typically used with the total option)
7797
7798 =item cutoff
7799
7800 An absolute cutoff time.  Payments, credits, and refunds I<applied> after this 
7801 time will be ignored.  Note that START_TIME and END_TIME only limit the date 
7802 range for invoices and I<unapplied> payments, credits, and refunds.
7803
7804 =back
7805
7806 =cut
7807
7808 sub balance_date_sql {
7809   my( $class, $start, $end, %opt ) = @_;
7810
7811   my $cutoff = $opt{'cutoff'};
7812
7813   my $owed         = FS::cust_bill->owed_sql($cutoff);
7814   my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
7815   my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
7816   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
7817
7818   my $j = $opt{'join'} || '';
7819
7820   my $owed_wh   = $class->_money_table_where( 'cust_bill',   $start,$end,%opt );
7821   my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
7822   my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
7823   my $pay_wh    = $class->_money_table_where( 'cust_pay',    $start,$end,%opt );
7824
7825   "   ( SELECT COALESCE(SUM($owed),         0) FROM cust_bill   $j $owed_wh   )
7826     + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
7827     - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
7828     - ( SELECT COALESCE(SUM($unapp_pay),    0) FROM cust_pay    $j $pay_wh    )
7829   ";
7830
7831 }
7832
7833 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
7834
7835 Returns an SQL fragment to retreive the total unapplied payments for this
7836 customer, only considering invoices with date earlier than START_TIME, and
7837 optionally not later than END_TIME.
7838
7839 Times are specified as SQL fragments or numeric
7840 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
7841 L<Date::Parse> for conversion functions.  The empty string can be passed
7842 to disable that time constraint completely.
7843
7844 Available options are:
7845
7846 =cut
7847
7848 sub unapplied_payments_date_sql {
7849   my( $class, $start, $end, %opt ) = @_;
7850
7851   my $cutoff = $opt{'cutoff'};
7852
7853   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
7854
7855   my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
7856                                                           'unapplied_date'=>1 );
7857
7858   " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
7859 }
7860
7861 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
7862
7863 Helper method for balance_date_sql; name (and usage) subject to change
7864 (suggestions welcome).
7865
7866 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
7867 cust_refund, cust_credit or cust_pay).
7868
7869 If TABLE is "cust_bill" or the unapplied_date option is true, only
7870 considers records with date earlier than START_TIME, and optionally not
7871 later than END_TIME .
7872
7873 =cut
7874
7875 sub _money_table_where {
7876   my( $class, $table, $start, $end, %opt ) = @_;
7877
7878   my @where = ();
7879   push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
7880   if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
7881     push @where, "$table._date <= $start" if defined($start) && length($start);
7882     push @where, "$table._date >  $end"   if defined($end)   && length($end);
7883   }
7884   push @where, @{$opt{'where'}} if $opt{'where'};
7885   my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
7886
7887   $where;
7888
7889 }
7890
7891 =item search HASHREF
7892
7893 (Class method)
7894
7895 Returns a qsearch hash expression to search for parameters specified in
7896 HASHREF.  Valid parameters are
7897
7898 =over 4
7899
7900 =item agentnum
7901
7902 =item status
7903
7904 =item cancelled_pkgs
7905
7906 bool
7907
7908 =item signupdate
7909
7910 listref of start date, end date
7911
7912 =item payby
7913
7914 listref
7915
7916 =item paydate_year
7917
7918 =item paydate_month
7919
7920 =item current_balance
7921
7922 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
7923
7924 =item cust_fields
7925
7926 =item flattened_pkgs
7927
7928 bool
7929
7930 =back
7931
7932 =cut
7933
7934 sub search {
7935   my ($class, $params) = @_;
7936
7937   my $dbh = dbh;
7938
7939   my @where = ();
7940   my $orderby;
7941
7942   ##
7943   # parse agent
7944   ##
7945
7946   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
7947     push @where,
7948       "cust_main.agentnum = $1";
7949   }
7950
7951   ##
7952   # do the same for user
7953   ##
7954
7955   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
7956     push @where,
7957       "cust_main.usernum = $1";
7958   }
7959
7960   ##
7961   # parse status
7962   ##
7963
7964   #prospect ordered active inactive suspended cancelled
7965   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
7966     my $method = $params->{'status'}. '_sql';
7967     #push @where, $class->$method();
7968     push @where, FS::cust_main->$method();
7969   }
7970   
7971   ##
7972   # parse cancelled package checkbox
7973   ##
7974
7975   my $pkgwhere = "";
7976
7977   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
7978     unless $params->{'cancelled_pkgs'};
7979
7980   ##
7981   # parse without census tract checkbox
7982   ##
7983
7984   push @where, "(censustract = '' or censustract is null)"
7985     if $params->{'no_censustract'};
7986
7987   ##
7988   # dates
7989   ##
7990
7991   foreach my $field (qw( signupdate )) {
7992
7993     next unless exists($params->{$field});
7994
7995     my($beginning, $ending, $hour) = @{$params->{$field}};
7996
7997     push @where,
7998       "cust_main.$field IS NOT NULL",
7999       "cust_main.$field >= $beginning",
8000       "cust_main.$field <= $ending";
8001
8002     # XXX: do this for mysql and/or pull it out of here
8003     if(defined $hour) {
8004       if ($dbh->{Driver}->{Name} eq 'Pg') {
8005         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
8006       }
8007       else {
8008         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
8009       }
8010     }
8011
8012     $orderby ||= "ORDER BY cust_main.$field";
8013
8014   }
8015
8016   ###
8017   # classnum
8018   ###
8019
8020   if ( $params->{'classnum'} ) {
8021
8022     my @classnum = ref( $params->{'classnum'} )
8023                      ? @{ $params->{'classnum'} }
8024                      :  ( $params->{'classnum'} );
8025
8026     @classnum = grep /^(\d*)$/, @classnum;
8027
8028     if ( @classnum ) {
8029       push @where, '( '. join(' OR ', map {
8030                                             $_ ? "cust_main.classnum = $_"
8031                                                : "cust_main.classnum IS NULL"
8032                                           }
8033                                           @classnum
8034                              ).
8035                    ' )';
8036     }
8037
8038   }
8039
8040   ###
8041   # payby
8042   ###
8043
8044   if ( $params->{'payby'} ) {
8045
8046     my @payby = ref( $params->{'payby'} )
8047                   ? @{ $params->{'payby'} }
8048                   :  ( $params->{'payby'} );
8049
8050     @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
8051
8052     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
8053       if @payby;
8054
8055   }
8056
8057   ###
8058   # paydate_year / paydate_month
8059   ###
8060
8061   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
8062     my $year = $1;
8063     $params->{'paydate_month'} =~ /^(\d\d?)$/
8064       or die "paydate_year without paydate_month?";
8065     my $month = $1;
8066
8067     push @where,
8068       'paydate IS NOT NULL',
8069       "paydate != ''",
8070       "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
8071 ;
8072   }
8073
8074   ###
8075   # invoice terms
8076   ###
8077
8078   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
8079     my $terms = $1;
8080     if ( $1 eq 'NULL' ) {
8081       push @where,
8082         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
8083     } else {
8084       push @where,
8085         "cust_main.invoice_terms IS NOT NULL",
8086         "cust_main.invoice_terms = '$1'";
8087     }
8088   }
8089
8090   ##
8091   # amounts
8092   ##
8093
8094   if ( $params->{'current_balance'} ) {
8095
8096     #my $balance_sql = $class->balance_sql();
8097     my $balance_sql = FS::cust_main->balance_sql();
8098
8099     my @current_balance =
8100       ref( $params->{'current_balance'} )
8101       ? @{ $params->{'current_balance'} }
8102       :  ( $params->{'current_balance'} );
8103
8104     push @where, map { s/current_balance/$balance_sql/; $_ }
8105                      @current_balance;
8106
8107   }
8108
8109   ##
8110   # custbatch
8111   ##
8112
8113   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
8114     push @where,
8115       "cust_main.custbatch = '$1'";
8116   }
8117
8118   ##
8119   # setup queries, subs, etc. for the search
8120   ##
8121
8122   $orderby ||= 'ORDER BY custnum';
8123
8124   # here is the agent virtualization
8125   push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
8126
8127   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
8128
8129   my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum  ) ';
8130
8131   my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
8132
8133   my $select = join(', ', 
8134                  'cust_main.custnum',
8135                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
8136                );
8137
8138   my(@extra_headers) = ();
8139   my(@extra_fields)  = ();
8140
8141   if ($params->{'flattened_pkgs'}) {
8142
8143     if ($dbh->{Driver}->{Name} eq 'Pg') {
8144
8145       $select .= ", array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
8146
8147     }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
8148       $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
8149       $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
8150     }else{
8151       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
8152            "omitting packing information from report.";
8153     }
8154
8155     my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
8156
8157     my $sth = dbh->prepare($header_query) or die dbh->errstr;
8158     $sth->execute() or die $sth->errstr;
8159     my $headerrow = $sth->fetchrow_arrayref;
8160     my $headercount = $headerrow ? $headerrow->[0] : 0;
8161     while($headercount) {
8162       unshift @extra_headers, "Package ". $headercount;
8163       unshift @extra_fields, eval q!sub {my $c = shift;
8164                                          my @a = split '\|', $c->magic;
8165                                          my $p = $a[!.--$headercount. q!];
8166                                          $p;
8167                                         };!;
8168     }
8169
8170   }
8171
8172   my $sql_query = {
8173     'table'         => 'cust_main',
8174     'select'        => $select,
8175     'hashref'       => {},
8176     'extra_sql'     => $extra_sql,
8177     'order_by'      => $orderby,
8178     'count_query'   => $count_query,
8179     'extra_headers' => \@extra_headers,
8180     'extra_fields'  => \@extra_fields,
8181   };
8182
8183 }
8184
8185 =item email_search_result HASHREF
8186
8187 (Class method)
8188
8189 Emails a notice to the specified customers.
8190
8191 Valid parameters are those of the L<search> method, plus the following:
8192
8193 =over 4
8194
8195 =item from
8196
8197 From: address
8198
8199 =item subject
8200
8201 Email Subject:
8202
8203 =item html_body
8204
8205 HTML body
8206
8207 =item text_body
8208
8209 Text body
8210
8211 =item job
8212
8213 Optional job queue job for status updates.
8214
8215 =back
8216
8217 Returns an error message, or false for success.
8218
8219 If an error occurs during any email, stops the enture send and returns that
8220 error.  Presumably if you're getting SMTP errors aborting is better than 
8221 retrying everything.
8222
8223 =cut
8224
8225 sub email_search_result {
8226   my($class, $params) = @_;
8227
8228   my $from = delete $params->{from};
8229   my $subject = delete $params->{subject};
8230   my $html_body = delete $params->{html_body};
8231   my $text_body = delete $params->{text_body};
8232   my $error = '';
8233
8234   my $job = delete $params->{'job'}
8235     or die "email_search_result must run from the job queue.\n";
8236
8237   $params->{'payby'} = [ split(/\0/, $params->{'payby'}) ]
8238     unless ref($params->{'payby'});
8239
8240   my $sql_query = $class->search($params);
8241
8242   my $count_query   = delete($sql_query->{'count_query'});
8243   my $count_sth = dbh->prepare($count_query)
8244     or die "Error preparing $count_query: ". dbh->errstr;
8245   $count_sth->execute
8246     or die "Error executing $count_query: ". $count_sth->errstr;
8247   my $count_arrayref = $count_sth->fetchrow_arrayref;
8248   my $num_cust = $count_arrayref->[0];
8249
8250   #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
8251   #my @extra_fields  = @{ delete($sql_query->{'extra_fields'})  };
8252
8253
8254   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
8255   my @retry_jobs = ();
8256   my $success = 0;
8257
8258   #eventually order+limit magic to reduce memory use?
8259   foreach my $cust_main ( qsearch($sql_query) ) {
8260
8261     #progressbar first, so that the count is right
8262     $num++;
8263     if ( time - $min_sec > $last ) {
8264       my $error = $job->update_statustext(
8265         int( 100 * $num / $num_cust )
8266       );
8267       die $error if $error;
8268       $last = time;
8269     }
8270
8271     my $to = $cust_main->invoicing_list_emailonly_scalar;
8272
8273     if( $to ) {
8274       my @message = (
8275         'from'      => $from,
8276         'to'        => $to,
8277         'subject'   => $subject,
8278         'html_body' => $html_body,
8279         'text_body' => $text_body,
8280       );
8281
8282       $error = send_email( generate_email( @message ) );
8283
8284       if($error) {
8285         # queue the sending of this message so that the user can see what we 
8286         # tried to do, and retry if desired
8287         my $queue = new FS::queue {
8288           'job'        => 'FS::Misc::process_send_email',
8289           'custnum'    => $cust_main->custnum,
8290           'status'     => 'failed',
8291           'statustext' => $error,
8292         };
8293         $queue->insert(@message);
8294         push @retry_jobs, $queue;
8295       }
8296       else {
8297         $success++;
8298       }
8299     }
8300
8301     if($success == 0 and 
8302         (scalar(@retry_jobs) > 10 or $num == $num_cust)
8303       ) {
8304       # 10 is arbitrary, but if we have enough failures, that's 
8305       # probably a configuration or network problem, and we 
8306       # abort the batch and run away screaming.
8307       # We NEVER do this if anything was successfully sent.
8308       $_->delete foreach (@retry_jobs);
8309       return "multiple failures: '$error'\n";
8310     }
8311   }
8312
8313   if(@retry_jobs) {
8314     # fail the job, but with a status message that makes it clear
8315     # something was sent.
8316     return "Sent $success, failed ".scalar(@retry_jobs).". Failed attempts placed in job queue.\n";
8317   }
8318
8319   return '';
8320 }
8321
8322 sub process_email_search_result {
8323   my $job = shift;
8324   #warn "$me process_re_X $method for job $job\n" if $DEBUG;
8325
8326   my $param = thaw(decode_base64(shift));
8327   warn Dumper($param) if $DEBUG;
8328
8329   $param->{'job'} = $job;
8330
8331   $param->{'payby'} = [ split(/\0/, $param->{'payby'}) ]
8332     unless ref($param->{'payby'});
8333
8334   my $error = FS::cust_main->email_search_result( $param );
8335   die $error if $error;
8336
8337 }
8338
8339 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
8340
8341 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
8342 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
8343 specified (the appropriate ship_ field is also searched).
8344
8345 Additional options are the same as FS::Record::qsearch
8346
8347 =cut
8348
8349 sub fuzzy_search {
8350   my( $self, $fuzzy, $hash, @opt) = @_;
8351   #$self
8352   $hash ||= {};
8353   my @cust_main = ();
8354
8355   check_and_rebuild_fuzzyfiles();
8356   foreach my $field ( keys %$fuzzy ) {
8357
8358     my $all = $self->all_X($field);
8359     next unless scalar(@$all);
8360
8361     my %match = ();
8362     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
8363
8364     my @fcust = ();
8365     foreach ( keys %match ) {
8366       push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
8367       push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
8368     }
8369     my %fsaw = ();
8370     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
8371   }
8372
8373   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
8374   my %saw = ();
8375   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
8376
8377   @cust_main;
8378
8379 }
8380
8381 =item masked FIELD
8382
8383 Returns a masked version of the named field
8384
8385 =cut
8386
8387 sub masked {
8388 my ($self,$field) = @_;
8389
8390 # Show last four
8391
8392 'x'x(length($self->getfield($field))-4).
8393   substr($self->getfield($field), (length($self->getfield($field))-4));
8394
8395 }
8396
8397 =back
8398
8399 =head1 SUBROUTINES
8400
8401 =over 4
8402
8403 =item smart_search OPTION => VALUE ...
8404
8405 Accepts the following options: I<search>, the string to search for.  The string
8406 will be searched for as a customer number, phone number, name or company name,
8407 as an exact, or, in some cases, a substring or fuzzy match (see the source code
8408 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
8409 skip fuzzy matching when an exact match is found.
8410
8411 Any additional options are treated as an additional qualifier on the search
8412 (i.e. I<agentnum>).
8413
8414 Returns a (possibly empty) array of FS::cust_main objects.
8415
8416 =cut
8417
8418 sub smart_search {
8419   my %options = @_;
8420
8421   #here is the agent virtualization
8422   my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8423
8424   my @cust_main = ();
8425
8426   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
8427   my $search = delete $options{'search'};
8428   ( my $alphanum_search = $search ) =~ s/\W//g;
8429   
8430   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
8431
8432     #false laziness w/Record::ut_phone
8433     my $phonen = "$1-$2-$3";
8434     $phonen .= " x$4" if $4;
8435
8436     push @cust_main, qsearch( {
8437       'table'   => 'cust_main',
8438       'hashref' => { %options },
8439       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8440                      ' ( '.
8441                          join(' OR ', map "$_ = '$phonen'",
8442                                           qw( daytime night fax
8443                                               ship_daytime ship_night ship_fax )
8444                              ).
8445                      ' ) '.
8446                      " AND $agentnums_sql", #agent virtualization
8447     } );
8448
8449     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
8450       #try looking for matches with extensions unless one was specified
8451
8452       push @cust_main, qsearch( {
8453         'table'   => 'cust_main',
8454         'hashref' => { %options },
8455         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
8456                        ' ( '.
8457                            join(' OR ', map "$_ LIKE '$phonen\%'",
8458                                             qw( daytime night
8459                                                 ship_daytime ship_night )
8460                                ).
8461                        ' ) '.
8462                        " AND $agentnums_sql", #agent virtualization
8463       } );
8464
8465     }
8466
8467   # custnum search (also try agent_custid), with some tweaking options if your
8468   # legacy cust "numbers" have letters
8469   } 
8470
8471   if ( $search =~ /^\s*(\d+)\s*$/
8472          || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
8473               && $search =~ /^\s*(\w\w?\d+)\s*$/
8474             )
8475          || ( $conf->exists('address1-search' )
8476               && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
8477             )
8478      )
8479   {
8480
8481     my $num = $1;
8482
8483     if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
8484       push @cust_main, qsearch( {
8485         'table'     => 'cust_main',
8486         'hashref'   => { 'custnum' => $num, %options },
8487         'extra_sql' => " AND $agentnums_sql", #agent virtualization
8488       } );
8489     }
8490
8491     push @cust_main, qsearch( {
8492       'table'     => 'cust_main',
8493       'hashref'   => { 'agent_custid' => $num, %options },
8494       'extra_sql' => " AND $agentnums_sql", #agent virtualization
8495     } );
8496
8497     if ( $conf->exists('address1-search') ) {
8498       my $len = length($num);
8499       $num = lc($num);
8500       foreach my $prefix ( '', 'ship_' ) {
8501         push @cust_main, qsearch( {
8502           'table'     => 'cust_main',
8503           'hashref'   => { %options, },
8504           'extra_sql' => 
8505             ( keys(%options) ? ' AND ' : ' WHERE ' ).
8506             " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
8507             " AND $agentnums_sql",
8508         } );
8509       }
8510     }
8511
8512   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
8513
8514     my($company, $last, $first) = ( $1, $2, $3 );
8515
8516     # "Company (Last, First)"
8517     #this is probably something a browser remembered,
8518     #so just do an exact search (but case-insensitive, so USPS standardization
8519     #doesn't throw a wrench in the works)
8520
8521     foreach my $prefix ( '', 'ship_' ) {
8522       push @cust_main, qsearch( {
8523         'table'     => 'cust_main',
8524         'hashref'   => { %options },
8525         'extra_sql' => 
8526           ( keys(%options) ? ' AND ' : ' WHERE ' ).
8527           join(' AND ',
8528             " LOWER(${prefix}first)   = ". dbh->quote(lc($first)),
8529             " LOWER(${prefix}last)    = ". dbh->quote(lc($last)),
8530             " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
8531             $agentnums_sql,
8532           ),
8533       } );
8534     }
8535
8536   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
8537                                               # try (ship_){last,company}
8538
8539     my $value = lc($1);
8540
8541     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
8542     # # full strings the browser remembers won't work
8543     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
8544
8545     use Lingua::EN::NameParse;
8546     my $NameParse = new Lingua::EN::NameParse(
8547              auto_clean     => 1,
8548              allow_reversed => 1,
8549     );
8550
8551     my($last, $first) = ( '', '' );
8552     #maybe disable this too and just rely on NameParse?
8553     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
8554     
8555       ($last, $first) = ( $1, $2 );
8556     
8557     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
8558     } elsif ( ! $NameParse->parse($value) ) {
8559
8560       my %name = $NameParse->components;
8561       $first = $name{'given_name_1'};
8562       $last  = $name{'surname_1'};
8563
8564     }
8565
8566     if ( $first && $last ) {
8567
8568       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
8569
8570       #exact
8571       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8572       $sql .= "
8573         (     ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
8574            OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
8575         )";
8576
8577       push @cust_main, qsearch( {
8578         'table'     => 'cust_main',
8579         'hashref'   => \%options,
8580         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8581       } );
8582
8583       # or it just be something that was typed in... (try that in a sec)
8584
8585     }
8586
8587     my $q_value = dbh->quote($value);
8588
8589     #exact
8590     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
8591     $sql .= " (    LOWER(last)          = $q_value
8592                 OR LOWER(company)       = $q_value
8593                 OR LOWER(ship_last)     = $q_value
8594                 OR LOWER(ship_company)  = $q_value
8595             ";
8596     $sql .= "   OR LOWER(address1)      = $q_value
8597                 OR LOWER(ship_address1) = $q_value
8598             "
8599       if $conf->exists('address1-search');
8600     $sql .= " )";
8601
8602     push @cust_main, qsearch( {
8603       'table'     => 'cust_main',
8604       'hashref'   => \%options,
8605       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
8606     } );
8607
8608     #no exact match, trying substring/fuzzy
8609     #always do substring & fuzzy (unless they're explicity config'ed off)
8610     #getting complaints searches are not returning enough
8611     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
8612
8613       #still some false laziness w/search (was search/cust_main.cgi)
8614
8615       #substring
8616
8617       my @hashrefs = (
8618         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
8619         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
8620       );
8621
8622       if ( $first && $last ) {
8623
8624         push @hashrefs,
8625           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
8626             'last'         => { op=>'ILIKE', value=>"%$last%" },
8627           },
8628           { 'ship_first'   => { op=>'ILIKE', value=>"%$first%" },
8629             'ship_last'    => { op=>'ILIKE', value=>"%$last%" },
8630           },
8631         ;
8632
8633       } else {
8634
8635         push @hashrefs,
8636           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
8637           { 'ship_last'    => { op=>'ILIKE', value=>"%$value%" }, },
8638         ;
8639       }
8640
8641       if ( $conf->exists('address1-search') ) {
8642         push @hashrefs,
8643           { 'address1'      => { op=>'ILIKE', value=>"%$value%" }, },
8644           { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
8645         ;
8646       }
8647
8648       foreach my $hashref ( @hashrefs ) {
8649
8650         push @cust_main, qsearch( {
8651           'table'     => 'cust_main',
8652           'hashref'   => { %$hashref,
8653                            %options,
8654                          },
8655           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
8656         } );
8657
8658       }
8659
8660       #fuzzy
8661       my @fuzopts = (
8662         \%options,                #hashref
8663         '',                       #select
8664         " AND $agentnums_sql",    #extra_sql  #agent virtualization
8665       );
8666
8667       if ( $first && $last ) {
8668         push @cust_main, FS::cust_main->fuzzy_search(
8669           { 'last'   => $last,    #fuzzy hashref
8670             'first'  => $first }, #
8671           @fuzopts
8672         );
8673       }
8674       foreach my $field ( 'last', 'company' ) {
8675         push @cust_main,
8676           FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
8677       }
8678       if ( $conf->exists('address1-search') ) {
8679         push @cust_main,
8680           FS::cust_main->fuzzy_search( { 'address1' => $value }, @fuzopts );
8681       }
8682
8683     }
8684
8685   }
8686
8687   #eliminate duplicates
8688   my %saw = ();
8689   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8690
8691   @cust_main;
8692
8693 }
8694
8695 =item email_search
8696
8697 Accepts the following options: I<email>, the email address to search for.  The
8698 email address will be searched for as an email invoice destination and as an
8699 svc_acct account.
8700
8701 #Any additional options are treated as an additional qualifier on the search
8702 #(i.e. I<agentnum>).
8703
8704 Returns a (possibly empty) array of FS::cust_main objects (but usually just
8705 none or one).
8706
8707 =cut
8708
8709 sub email_search {
8710   my %options = @_;
8711
8712   local($DEBUG) = 1;
8713
8714   my $email = delete $options{'email'};
8715
8716   #we're only being used by RT at the moment... no agent virtualization yet
8717   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
8718
8719   my @cust_main = ();
8720
8721   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
8722
8723     my ( $user, $domain ) = ( $1, $2 );
8724
8725     warn "$me smart_search: searching for $user in domain $domain"
8726       if $DEBUG;
8727
8728     push @cust_main,
8729       map $_->cust_main,
8730           qsearch( {
8731                      'table'     => 'cust_main_invoice',
8732                      'hashref'   => { 'dest' => $email },
8733                    }
8734                  );
8735
8736     push @cust_main,
8737       map  $_->cust_main,
8738       grep $_,
8739       map  $_->cust_svc->cust_pkg,
8740           qsearch( {
8741                      'table'     => 'svc_acct',
8742                      'hashref'   => { 'username' => $user, },
8743                      'extra_sql' =>
8744                        'AND ( SELECT domain FROM svc_domain
8745                                 WHERE svc_acct.domsvc = svc_domain.svcnum
8746                             ) = '. dbh->quote($domain),
8747                    }
8748                  );
8749   }
8750
8751   my %saw = ();
8752   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
8753
8754   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
8755     if $DEBUG;
8756
8757   @cust_main;
8758
8759 }
8760
8761 =item check_and_rebuild_fuzzyfiles
8762
8763 =cut
8764
8765 sub check_and_rebuild_fuzzyfiles {
8766   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8767   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
8768 }
8769
8770 =item rebuild_fuzzyfiles
8771
8772 =cut
8773
8774 sub rebuild_fuzzyfiles {
8775
8776   use Fcntl qw(:flock);
8777
8778   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8779   mkdir $dir, 0700 unless -d $dir;
8780
8781   foreach my $fuzzy ( @fuzzyfields ) {
8782
8783     open(LOCK,">>$dir/cust_main.$fuzzy")
8784       or die "can't open $dir/cust_main.$fuzzy: $!";
8785     flock(LOCK,LOCK_EX)
8786       or die "can't lock $dir/cust_main.$fuzzy: $!";
8787
8788     open (CACHE,">$dir/cust_main.$fuzzy.tmp")
8789       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
8790
8791     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
8792       my $sth = dbh->prepare("SELECT $field FROM cust_main".
8793                              " WHERE $field != '' AND $field IS NOT NULL");
8794       $sth->execute or die $sth->errstr;
8795
8796       while ( my $row = $sth->fetchrow_arrayref ) {
8797         print CACHE $row->[0]. "\n";
8798       }
8799
8800     } 
8801
8802     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
8803   
8804     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
8805     close LOCK;
8806   }
8807
8808 }
8809
8810 =item all_X
8811
8812 =cut
8813
8814 sub all_X {
8815   my( $self, $field ) = @_;
8816   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8817   open(CACHE,"<$dir/cust_main.$field")
8818     or die "can't open $dir/cust_main.$field: $!";
8819   my @array = map { chomp; $_; } <CACHE>;
8820   close CACHE;
8821   \@array;
8822 }
8823
8824 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
8825
8826 =cut
8827
8828 sub append_fuzzyfiles {
8829   #my( $first, $last, $company ) = @_;
8830
8831   &check_and_rebuild_fuzzyfiles;
8832
8833   use Fcntl qw(:flock);
8834
8835   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
8836
8837   foreach my $field (@fuzzyfields) {
8838     my $value = shift;
8839
8840     if ( $value ) {
8841
8842       open(CACHE,">>$dir/cust_main.$field")
8843         or die "can't open $dir/cust_main.$field: $!";
8844       flock(CACHE,LOCK_EX)
8845         or die "can't lock $dir/cust_main.$field: $!";
8846
8847       print CACHE "$value\n";
8848
8849       flock(CACHE,LOCK_UN)
8850         or die "can't unlock $dir/cust_main.$field: $!";
8851       close CACHE;
8852     }
8853
8854   }
8855
8856   1;
8857 }
8858
8859 =item batch_charge
8860
8861 =cut
8862
8863 sub batch_charge {
8864   my $param = shift;
8865   #warn join('-',keys %$param);
8866   my $fh = $param->{filehandle};
8867   my $agentnum = $param->{agentnum};
8868   my $format = $param->{format};
8869
8870   my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
8871
8872   my @fields;
8873   if ( $format eq 'simple' ) {
8874     @fields = qw( custnum agent_custid amount pkg );
8875   } else {
8876     die "unknown format $format";
8877   }
8878
8879   eval "use Text::CSV_XS;";
8880   die $@ if $@;
8881
8882   my $csv = new Text::CSV_XS;
8883   #warn $csv;
8884   #warn $fh;
8885
8886   my $imported = 0;
8887   #my $columns;
8888
8889   local $SIG{HUP} = 'IGNORE';
8890   local $SIG{INT} = 'IGNORE';
8891   local $SIG{QUIT} = 'IGNORE';
8892   local $SIG{TERM} = 'IGNORE';
8893   local $SIG{TSTP} = 'IGNORE';
8894   local $SIG{PIPE} = 'IGNORE';
8895
8896   my $oldAutoCommit = $FS::UID::AutoCommit;
8897   local $FS::UID::AutoCommit = 0;
8898   my $dbh = dbh;
8899   
8900   #while ( $columns = $csv->getline($fh) ) {
8901   my $line;
8902   while ( defined($line=<$fh>) ) {
8903
8904     $csv->parse($line) or do {
8905       $dbh->rollback if $oldAutoCommit;
8906       return "can't parse: ". $csv->error_input();
8907     };
8908
8909     my @columns = $csv->fields();
8910     #warn join('-',@columns);
8911
8912     my %row = ();
8913     foreach my $field ( @fields ) {
8914       $row{$field} = shift @columns;
8915     }
8916
8917     if ( $row{custnum} && $row{agent_custid} ) {
8918       dbh->rollback if $oldAutoCommit;
8919       return "can't specify custnum with agent_custid $row{agent_custid}";
8920     }
8921
8922     my %hash = ();
8923     if ( $row{agent_custid} && $agentnum ) {
8924       %hash = ( 'agent_custid' => $row{agent_custid},
8925                 'agentnum'     => $agentnum,
8926               );
8927     }
8928
8929     if ( $row{custnum} ) {
8930       %hash = ( 'custnum' => $row{custnum} );
8931     }
8932
8933     unless ( scalar(keys %hash) ) {
8934       $dbh->rollback if $oldAutoCommit;
8935       return "can't find customer without custnum or agent_custid and agentnum";
8936     }
8937
8938     my $cust_main = qsearchs('cust_main', { %hash } );
8939     unless ( $cust_main ) {
8940       $dbh->rollback if $oldAutoCommit;
8941       my $custnum = $row{custnum} || $row{agent_custid};
8942       return "unknown custnum $custnum";
8943     }
8944
8945     if ( $row{'amount'} > 0 ) {
8946       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
8947       if ( $error ) {
8948         $dbh->rollback if $oldAutoCommit;
8949         return $error;
8950       }
8951       $imported++;
8952     } elsif ( $row{'amount'} < 0 ) {
8953       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
8954                                       $row{'pkg'}                         );
8955       if ( $error ) {
8956         $dbh->rollback if $oldAutoCommit;
8957         return $error;
8958       }
8959       $imported++;
8960     } else {
8961       #hmm?
8962     }
8963
8964   }
8965
8966   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
8967
8968   return "Empty file!" unless $imported;
8969
8970   ''; #no error
8971
8972 }
8973
8974 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
8975
8976 Deprecated.  Use event notification and message templates 
8977 (L<FS::msg_template>) instead.
8978
8979 Sends a templated email notification to the customer (see L<Text::Template>).
8980
8981 OPTIONS is a hash and may include
8982
8983 I<from> - the email sender (default is invoice_from)
8984
8985 I<to> - comma-separated scalar or arrayref of recipients 
8986    (default is invoicing_list)
8987
8988 I<subject> - The subject line of the sent email notification
8989    (default is "Notice from company_name")
8990
8991 I<extra_fields> - a hashref of name/value pairs which will be substituted
8992    into the template
8993
8994 The following variables are vavailable in the template.
8995
8996 I<$first> - the customer first name
8997 I<$last> - the customer last name
8998 I<$company> - the customer company
8999 I<$payby> - a description of the method of payment for the customer
9000             # would be nice to use FS::payby::shortname
9001 I<$payinfo> - the account information used to collect for this customer
9002 I<$expdate> - the expiration of the customer payment in seconds from epoch
9003
9004 =cut
9005
9006 sub notify {
9007   my ($self, $template, %options) = @_;
9008
9009   return unless $conf->exists($template);
9010
9011   my $from = $conf->config('invoice_from', $self->agentnum)
9012     if $conf->exists('invoice_from', $self->agentnum);
9013   $from = $options{from} if exists($options{from});
9014
9015   my $to = join(',', $self->invoicing_list_emailonly);
9016   $to = $options{to} if exists($options{to});
9017   
9018   my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
9019     if $conf->exists('company_name', $self->agentnum);
9020   $subject = $options{subject} if exists($options{subject});
9021
9022   my $notify_template = new Text::Template (TYPE => 'ARRAY',
9023                                             SOURCE => [ map "$_\n",
9024                                               $conf->config($template)]
9025                                            )
9026     or die "can't create new Text::Template object: Text::Template::ERROR";
9027   $notify_template->compile()
9028     or die "can't compile template: Text::Template::ERROR";
9029
9030   $FS::notify_template::_template::company_name =
9031     $conf->config('company_name', $self->agentnum);
9032   $FS::notify_template::_template::company_address =
9033     join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
9034
9035   my $paydate = $self->paydate || '2037-12-31';
9036   $FS::notify_template::_template::first = $self->first;
9037   $FS::notify_template::_template::last = $self->last;
9038   $FS::notify_template::_template::company = $self->company;
9039   $FS::notify_template::_template::payinfo = $self->mask_payinfo;
9040   my $payby = $self->payby;
9041   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
9042   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
9043
9044   #credit cards expire at the end of the month/year of their exp date
9045   if ($payby eq 'CARD' || $payby eq 'DCRD') {
9046     $FS::notify_template::_template::payby = 'credit card';
9047     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
9048     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
9049     $expire_time--;
9050   }elsif ($payby eq 'COMP') {
9051     $FS::notify_template::_template::payby = 'complimentary account';
9052   }else{
9053     $FS::notify_template::_template::payby = 'current method';
9054   }
9055   $FS::notify_template::_template::expdate = $expire_time;
9056
9057   for (keys %{$options{extra_fields}}){
9058     no strict "refs";
9059     ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
9060   }
9061
9062   send_email(from => $from,
9063              to => $to,
9064              subject => $subject,
9065              body => $notify_template->fill_in( PACKAGE =>
9066                                                 'FS::notify_template::_template'                                              ),
9067             );
9068
9069 }
9070
9071 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
9072
9073 Generates a templated notification to the customer (see L<Text::Template>).
9074
9075 OPTIONS is a hash and may include
9076
9077 I<extra_fields> - a hashref of name/value pairs which will be substituted
9078    into the template.  These values may override values mentioned below
9079    and those from the customer record.
9080
9081 The following variables are available in the template instead of or in addition
9082 to the fields of the customer record.
9083
9084 I<$payby> - a description of the method of payment for the customer
9085             # would be nice to use FS::payby::shortname
9086 I<$payinfo> - the masked account information used to collect for this customer
9087 I<$expdate> - the expiration of the customer payment method in seconds from epoch
9088 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
9089
9090 =cut
9091
9092 # a lot like cust_bill::print_latex
9093 sub generate_letter {
9094   my ($self, $template, %options) = @_;
9095
9096   return unless $conf->exists($template);
9097
9098   my $letter_template = new Text::Template
9099                         ( TYPE       => 'ARRAY',
9100                           SOURCE     => [ map "$_\n", $conf->config($template)],
9101                           DELIMITERS => [ '[@--', '--@]' ],
9102                         )
9103     or die "can't create new Text::Template object: Text::Template::ERROR";
9104
9105   $letter_template->compile()
9106     or die "can't compile template: Text::Template::ERROR";
9107
9108   my %letter_data = map { $_ => $self->$_ } $self->fields;
9109   $letter_data{payinfo} = $self->mask_payinfo;
9110
9111   #my $paydate = $self->paydate || '2037-12-31';
9112   my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
9113
9114   my $payby = $self->payby;
9115   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
9116   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
9117
9118   #credit cards expire at the end of the month/year of their exp date
9119   if ($payby eq 'CARD' || $payby eq 'DCRD') {
9120     $letter_data{payby} = 'credit card';
9121     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
9122     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
9123     $expire_time--;
9124   }elsif ($payby eq 'COMP') {
9125     $letter_data{payby} = 'complimentary account';
9126   }else{
9127     $letter_data{payby} = 'current method';
9128   }
9129   $letter_data{expdate} = $expire_time;
9130
9131   for (keys %{$options{extra_fields}}){
9132     $letter_data{$_} = $options{extra_fields}->{$_};
9133   }
9134
9135   unless(exists($letter_data{returnaddress})){
9136     my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
9137                                                   $self->agent_template)
9138                      );
9139     if ( length($retadd) ) {
9140       $letter_data{returnaddress} = $retadd;
9141     } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
9142       $letter_data{returnaddress} =
9143         join( "\n", map { s/( {2,})/'~' x length($1)/eg;
9144                           s/$/\\\\\*/;
9145                           $_;
9146                         }
9147                     ( $conf->config('company_name', $self->agentnum),
9148                       $conf->config('company_address', $self->agentnum),
9149                     )
9150         );
9151     } else {
9152       $letter_data{returnaddress} = '~';
9153     }
9154   }
9155
9156   $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
9157
9158   $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
9159
9160   my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
9161
9162   my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
9163                            DIR      => $dir,
9164                            SUFFIX   => '.eps',
9165                            UNLINK   => 0,
9166                          ) or die "can't open temp file: $!\n";
9167   print $lh $conf->config_binary('logo.eps', $self->agentnum)
9168     or die "can't write temp file: $!\n";
9169   close $lh;
9170   $letter_data{'logo_file'} = $lh->filename;
9171
9172   my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
9173                            DIR      => $dir,
9174                            SUFFIX   => '.tex',
9175                            UNLINK   => 0,
9176                          ) or die "can't open temp file: $!\n";
9177
9178   $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
9179   close $fh;
9180   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
9181   return ($1, $letter_data{'logo_file'});
9182
9183 }
9184
9185 =item print_ps TEMPLATE 
9186
9187 Returns an postscript letter filled in from TEMPLATE, as a scalar.
9188
9189 =cut
9190
9191 sub print_ps {
9192   my $self = shift;
9193   my($file, $lfile) = $self->generate_letter(@_);
9194   my $ps = FS::Misc::generate_ps($file);
9195   unlink($file.'.tex');
9196   unlink($lfile);
9197
9198   $ps;
9199 }
9200
9201 =item print TEMPLATE
9202
9203 Prints the filled in template.
9204
9205 TEMPLATE is the name of a L<Text::Template> to fill in and print.
9206
9207 =cut
9208
9209 sub queueable_print {
9210   my %opt = @_;
9211
9212   my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
9213     or die "invalid customer number: " . $opt{custvnum};
9214
9215   my $error = $self->print( $opt{template} );
9216   die $error if $error;
9217 }
9218
9219 sub print {
9220   my ($self, $template) = (shift, shift);
9221   do_print [ $self->print_ps($template) ];
9222 }
9223
9224 #these three subs should just go away once agent stuff is all config overrides
9225
9226 sub agent_template {
9227   my $self = shift;
9228   $self->_agent_plandata('agent_templatename');
9229 }
9230
9231 sub agent_invoice_from {
9232   my $self = shift;
9233   $self->_agent_plandata('agent_invoice_from');
9234 }
9235
9236 sub _agent_plandata {
9237   my( $self, $option ) = @_;
9238
9239   #yuck.  this whole thing needs to be reconciled better with 1.9's idea of
9240   #agent-specific Conf
9241
9242   use FS::part_event::Condition;
9243   
9244   my $agentnum = $self->agentnum;
9245
9246   my $regexp = regexp_sql();
9247
9248   my $part_event_option =
9249     qsearchs({
9250       'select'    => 'part_event_option.*',
9251       'table'     => 'part_event_option',
9252       'addl_from' => q{
9253         LEFT JOIN part_event USING ( eventpart )
9254         LEFT JOIN part_event_option AS peo_agentnum
9255           ON ( part_event.eventpart = peo_agentnum.eventpart
9256                AND peo_agentnum.optionname = 'agentnum'
9257                AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
9258              )
9259         LEFT JOIN part_event_condition
9260           ON ( part_event.eventpart = part_event_condition.eventpart
9261                AND part_event_condition.conditionname = 'cust_bill_age'
9262              )
9263         LEFT JOIN part_event_condition_option
9264           ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
9265                AND part_event_condition_option.optionname = 'age'
9266              )
9267       },
9268       #'hashref'   => { 'optionname' => $option },
9269       #'hashref'   => { 'part_event_option.optionname' => $option },
9270       'extra_sql' =>
9271         " WHERE part_event_option.optionname = ". dbh->quote($option).
9272         " AND action = 'cust_bill_send_agent' ".
9273         " AND ( disabled IS NULL OR disabled != 'Y' ) ".
9274         " AND peo_agentnum.optionname = 'agentnum' ".
9275         " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
9276         " ORDER BY
9277            CASE WHEN part_event_condition_option.optionname IS NULL
9278            THEN -1
9279            ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
9280         " END
9281           , part_event.weight".
9282         " LIMIT 1"
9283     });
9284     
9285   unless ( $part_event_option ) {
9286     return $self->agent->invoice_template || ''
9287       if $option eq 'agent_templatename';
9288     return '';
9289   }
9290
9291   $part_event_option->optionvalue;
9292
9293 }
9294
9295 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
9296
9297 Subroutine (not a method), designed to be called from the queue.
9298
9299 Takes a list of options and values.
9300
9301 Pulls up the customer record via the custnum option and calls bill_and_collect.
9302
9303 =cut
9304
9305 sub queued_bill {
9306   my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
9307
9308   my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
9309   warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
9310
9311   $cust_main->bill_and_collect( %args );
9312 }
9313
9314 sub process_bill_and_collect {
9315   my $job = shift;
9316   my $param = thaw(decode_base64(shift));
9317   my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
9318       or die "custnum '$param->{custnum}' not found!\n";
9319   $param->{'job'}   = $job;
9320   $param->{'fatal'} = 1; # runs from job queue, will be caught
9321   $param->{'retry'} = 1;
9322
9323   $cust_main->bill_and_collect( %$param );
9324 }
9325
9326 sub _upgrade_data { #class method
9327   my ($class, %opts) = @_;
9328
9329   my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
9330   my $sth = dbh->prepare($sql) or die dbh->errstr;
9331   $sth->execute or die $sth->errstr;
9332
9333   local($ignore_expired_card) = 1;
9334   local($skip_fuzzyfiles) = 1;
9335   $class->_upgrade_otaker(%opts);
9336
9337 }
9338
9339 =back
9340
9341 =head1 BUGS
9342
9343 The delete method.
9344
9345 The delete method should possibly take an FS::cust_main object reference
9346 instead of a scalar customer number.
9347
9348 Bill and collect options should probably be passed as references instead of a
9349 list.
9350
9351 There should probably be a configuration file with a list of allowed credit
9352 card types.
9353
9354 No multiple currency support (probably a larger project than just this module).
9355
9356 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
9357
9358 Birthdates rely on negative epoch values.
9359
9360 The payby for card/check batches is broken.  With mixed batching, bad
9361 things will happen.
9362
9363 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
9364
9365 =head1 SEE ALSO
9366
9367 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
9368 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
9369 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
9370
9371 =cut
9372
9373 1;
9374