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