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