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