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