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