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