when expiring multiple packages, remove services in cancel weight order, #37177
[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::cust_main::Packages FS::cust_main::Status
6              FS::cust_main::NationalID
7              FS::cust_main::Billing FS::cust_main::Billing_Realtime
8              FS::cust_main::Billing_Discount
9              FS::cust_main::Billing_ThirdParty
10              FS::cust_main::Location
11              FS::cust_main::Credit_Limit
12              FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13              FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
14              FS::o2m_Common
15              FS::Record
16            );
17 use vars qw( $DEBUG $me $conf $default_agent_custid $custnum_display_length
18              @encrypted_fields
19              $import
20              $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
21              $skip_fuzzyfiles
22              @paytypes
23            );
24 use Carp;
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
28 use MIME::Base64;
29 use Data::Dumper;
30 use Tie::IxHash;
31 use Digest::MD5 qw(md5_base64);
32 use Date::Format;
33 #use Date::Manip;
34 use File::Temp; #qw( tempfile );
35 use Business::CreditCard 0.28;
36 use FS::UID qw( getotaker dbh driver_name );
37 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
38 use FS::Misc qw( generate_email send_email generate_ps do_print money_pretty card_types );
39 use FS::Msgcat qw(gettext);
40 use FS::CurrentUser;
41 use FS::TicketSystem;
42 use FS::payby;
43 use FS::cust_pkg;
44 use FS::cust_svc;
45 use FS::cust_bill;
46 use FS::cust_bill_void;
47 use FS::legacy_cust_bill;
48 use FS::cust_pay;
49 use FS::cust_pay_pending;
50 use FS::cust_pay_void;
51 use FS::cust_pay_batch;
52 use FS::cust_credit;
53 use FS::cust_refund;
54 use FS::part_referral;
55 use FS::cust_main_county;
56 use FS::cust_location;
57 use FS::cust_class;
58 use FS::cust_main_exemption;
59 use FS::cust_tax_adjustment;
60 use FS::cust_tax_location;
61 use FS::agent;
62 use FS::cust_main_invoice;
63 use FS::cust_tag;
64 use FS::prepay_credit;
65 use FS::queue;
66 use FS::part_pkg;
67 use FS::part_export;
68 #use FS::cust_event;
69 use FS::type_pkgs;
70 use FS::payment_gateway;
71 use FS::agent_payment_gateway;
72 use FS::banned_pay;
73 use FS::cust_main_note;
74 use FS::cust_attachment;
75 use FS::contact;
76 use FS::Locales;
77 use FS::upgrade_journal;
78
79 # 1 is mostly method/subroutine entry and options
80 # 2 traces progress of some operations
81 # 3 is even more information including possibly sensitive data
82 $DEBUG = 0;
83 $me = '[FS::cust_main]';
84
85 $import = 0;
86 $ignore_expired_card = 0;
87 $ignore_banned_card = 0;
88
89 $skip_fuzzyfiles = 0;
90
91 @encrypted_fields = ('payinfo', 'paycvv');
92 sub nohistory_fields { ('payinfo', 'paycvv'); }
93
94 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
95
96 #ask FS::UID to run this stuff for us later
97 #$FS::UID::callback{'FS::cust_main'} = sub { 
98 install_callback FS::UID sub { 
99   $conf = new FS::Conf;
100   $default_agent_custid   = $conf->exists('cust_main-default_agent_custid');
101   $custnum_display_length = $conf->config('cust_main-custnum-display_length');
102 };
103
104 sub _cache {
105   my $self = shift;
106   my ( $hashref, $cache ) = @_;
107   if ( exists $hashref->{'pkgnum'} ) {
108     #@{ $self->{'_pkgnum'} } = ();
109     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110     $self->{'_pkgnum'} = $subcache;
111     #push @{ $self->{'_pkgnum'} },
112     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
113   }
114 }
115
116 =head1 NAME
117
118 FS::cust_main - Object methods for cust_main records
119
120 =head1 SYNOPSIS
121
122   use FS::cust_main;
123
124   $record = new FS::cust_main \%hash;
125   $record = new FS::cust_main { 'column' => 'value' };
126
127   $error = $record->insert;
128
129   $error = $new_record->replace($old_record);
130
131   $error = $record->delete;
132
133   $error = $record->check;
134
135   @cust_pkg = $record->all_pkgs;
136
137   @cust_pkg = $record->ncancelled_pkgs;
138
139   @cust_pkg = $record->suspended_pkgs;
140
141   $error = $record->bill;
142   $error = $record->bill %options;
143   $error = $record->bill 'time' => $time;
144
145   $error = $record->collect;
146   $error = $record->collect %options;
147   $error = $record->collect 'invoice_time'   => $time,
148                           ;
149
150 =head1 DESCRIPTION
151
152 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
153 FS::Record.  The following fields are currently supported:
154
155 =over 4
156
157 =item custnum
158
159 Primary key (assigned automatically for new customers)
160
161 =item agentnum
162
163 Agent (see L<FS::agent>)
164
165 =item refnum
166
167 Advertising source (see L<FS::part_referral>)
168
169 =item first
170
171 First name
172
173 =item last
174
175 Last name
176
177 =item ss
178
179 Cocial security number (optional)
180
181 =item company
182
183 (optional)
184
185 =item daytime
186
187 phone (optional)
188
189 =item night
190
191 phone (optional)
192
193 =item fax
194
195 phone (optional)
196
197 =item mobile
198
199 phone (optional)
200
201 =item payby
202
203 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
204
205 =item payinfo
206
207 Payment Information (See L<FS::payinfo_Mixin> for data format)
208
209 =item paymask
210
211 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
212
213 =item paycvv
214
215 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
216
217 =item paydate
218
219 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
220
221 =item paystart_month
222
223 Start date month (maestro/solo cards only)
224
225 =item paystart_year
226
227 Start date year (maestro/solo cards only)
228
229 =item payissue
230
231 Issue number (maestro/solo cards only)
232
233 =item payname
234
235 Name on card or billing name
236
237 =item payip
238
239 IP address from which payment information was received
240
241 =item tax
242
243 Tax exempt, empty or `Y'
244
245 =item usernum
246
247 Order taker (see L<FS::access_user>)
248
249 =item comments
250
251 Comments (optional)
252
253 =item referral_custnum
254
255 Referring customer number
256
257 =item spool_cdr
258
259 Enable individual CDR spooling, empty or `Y'
260
261 =item dundate
262
263 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
264
265 =item squelch_cdr
266
267 Discourage individual CDR printing, empty or `Y'
268
269 =item edit_subject
270
271 Allow self-service editing of ticket subjects, empty or 'Y'
272
273 =item calling_list_exempt
274
275 Do not call, empty or 'Y'
276
277 =item invoice_ship_address
278
279 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
280
281 =back
282
283 =head1 METHODS
284
285 =over 4
286
287 =item new HASHREF
288
289 Creates a new customer.  To add the customer to the database, see L<"insert">.
290
291 Note that this stores the hash reference, not a distinct copy of the hash it
292 points to.  You can ask the object for a copy with the I<hash> method.
293
294 =cut
295
296 sub table { 'cust_main'; }
297
298 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
299
300 Adds this customer to the database.  If there is an error, returns the error,
301 otherwise returns false.
302
303 Usually the customer's location will not yet exist in the database, and
304 the C<bill_location> and C<ship_location> pseudo-fields must be set to 
305 uninserted L<FS::cust_location> objects.  These will be inserted and linked
306 (in both directions) to the new customer record.  If they're references 
307 to the same object, they will become the same location.
308
309 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
310 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
311 are inserted atomicly, or the transaction is rolled back.  Passing an empty
312 hash reference is equivalent to not supplying this parameter.  There should be
313 a better explanation of this, but until then, here's an example:
314
315   use Tie::RefHash;
316   tie %hash, 'Tie::RefHash'; #this part is important
317   %hash = (
318     $cust_pkg => [ $svc_acct ],
319     ...
320   );
321   $cust_main->insert( \%hash );
322
323 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
324 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
325 expected and rollback the entire transaction; it is not necessary to call 
326 check_invoicing_list first.  The invoicing_list is set after the records in the
327 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
328 invoicing_list destination to the newly-created svc_acct.  Here's an example:
329
330   $cust_main->insert( {}, [ $email, 'POST' ] );
331
332 Currently available options are: I<depend_jobnum>, I<noexport>,
333 I<tax_exemption> and I<prospectnum>.
334
335 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
336 on the supplied jobnum (they will not run until the specific job completes).
337 This can be used to defer provisioning until some action completes (such
338 as running the customer's credit card successfully).
339
340 The I<noexport> option is deprecated.  If I<noexport> is set true, no
341 provisioning jobs (exports) are scheduled.  (You can schedule them later with
342 the B<reexport> method.)
343
344 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
345 of tax names and exemption numbers.  FS::cust_main_exemption records will be
346 created and inserted.
347
348 If I<prospectnum> is set, moves contacts and locations from that prospect.
349
350 =cut
351
352 sub insert {
353   my $self = shift;
354   my $cust_pkgs = @_ ? shift : {};
355   my $invoicing_list = @_ ? shift : '';
356   my %options = @_;
357   warn "$me insert called with options ".
358        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
359     if $DEBUG;
360
361   local $SIG{HUP} = 'IGNORE';
362   local $SIG{INT} = 'IGNORE';
363   local $SIG{QUIT} = 'IGNORE';
364   local $SIG{TERM} = 'IGNORE';
365   local $SIG{TSTP} = 'IGNORE';
366   local $SIG{PIPE} = 'IGNORE';
367
368   my $oldAutoCommit = $FS::UID::AutoCommit;
369   local $FS::UID::AutoCommit = 0;
370   my $dbh = dbh;
371
372   my $prepay_identifier = '';
373   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
374   my $payby = '';
375   if ( $self->payby eq 'PREPAY' ) {
376
377     $self->payby('BILL');
378     $prepay_identifier = $self->payinfo;
379     $self->payinfo('');
380
381     warn "  looking up prepaid card $prepay_identifier\n"
382       if $DEBUG > 1;
383
384     my $error = $self->get_prepay( $prepay_identifier,
385                                    'amount_ref'     => \$amount,
386                                    'seconds_ref'    => \$seconds,
387                                    'upbytes_ref'    => \$upbytes,
388                                    'downbytes_ref'  => \$downbytes,
389                                    'totalbytes_ref' => \$totalbytes,
390                                  );
391     if ( $error ) {
392       $dbh->rollback if $oldAutoCommit;
393       #return "error applying prepaid card (transaction rolled back): $error";
394       return $error;
395     }
396
397     $payby = 'PREP' if $amount;
398
399   } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
400
401     $payby = $1;
402     $self->payby('BILL');
403     $amount = $self->paid;
404
405   }
406
407   # insert locations
408   foreach my $l (qw(bill_location ship_location)) {
409
410     my $loc = delete $self->hashref->{$l} or return "$l not set";
411     
412     if ( !$loc->locationnum ) {
413       # warn the location that we're going to insert it with no custnum
414       $loc->set(custnum_pending => 1);
415       warn "  inserting $l\n"
416         if $DEBUG > 1;
417       my $error = $loc->insert;
418       if ( $error ) {
419         $dbh->rollback if $oldAutoCommit;
420         my $label = $l eq 'ship_location' ? 'service' : 'billing';
421         return "$error (in $label location)";
422       }
423
424     } elsif ( $loc->prospectnum ) {
425
426       $loc->prospectnum('');
427       $loc->set(custnum_pending => 1);
428       my $error = $loc->replace;
429       if ( $error ) {
430         $dbh->rollback if $oldAutoCommit;
431         my $label = $l eq 'ship_location' ? 'service' : 'billing';
432         return "$error (moving $label location)";
433       }
434
435     } elsif ( ($loc->custnum || 0) > 0 ) {
436       # then it somehow belongs to another customer--shouldn't happen
437       $dbh->rollback if $oldAutoCommit;
438       return "$l belongs to customer ".$loc->custnum;
439     }
440     # else it already belongs to this customer 
441     # (happens when ship_location is identical to bill_location)
442
443     $self->set($l.'num', $loc->locationnum);
444
445     if ( $self->get($l.'num') eq '' ) {
446       $dbh->rollback if $oldAutoCommit;
447       return "$l not set";
448     }
449   }
450
451   warn "  inserting $self\n"
452     if $DEBUG > 1;
453
454   $self->signupdate(time) unless $self->signupdate;
455
456   $self->auto_agent_custid()
457     if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
458
459   my $error =  $self->check_payinfo_cardtype
460             || $self->SUPER::insert;
461   if ( $error ) {
462     $dbh->rollback if $oldAutoCommit;
463     #return "inserting cust_main record (transaction rolled back): $error";
464     return $error;
465   }
466
467   # now set cust_location.custnum
468   foreach my $l (qw(bill_location ship_location)) {
469     warn "  setting $l.custnum\n"
470       if $DEBUG > 1;
471     my $loc = $self->$l;
472     unless ( $loc->custnum ) {
473       $loc->set(custnum => $self->custnum);
474       $error ||= $loc->replace;
475     }
476
477     if ( $error ) {
478       $dbh->rollback if $oldAutoCommit;
479       return "error setting $l custnum: $error";
480     }
481   }
482
483   warn "  setting invoicing list\n"
484     if $DEBUG > 1;
485
486   if ( $invoicing_list ) {
487     $error = $self->check_invoicing_list( $invoicing_list );
488     if ( $error ) {
489       $dbh->rollback if $oldAutoCommit;
490       #return "checking invoicing_list (transaction rolled back): $error";
491       return $error;
492     }
493     $self->invoicing_list( $invoicing_list );
494   }
495
496   warn "  setting customer tags\n"
497     if $DEBUG > 1;
498
499   foreach my $tagnum ( @{ $self->tagnum || [] } ) {
500     my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
501                                       'custnum' => $self->custnum };
502     my $error = $cust_tag->insert;
503     if ( $error ) {
504       $dbh->rollback if $oldAutoCommit;
505       return $error;
506     }
507   }
508
509   my $prospectnum = delete $options{'prospectnum'};
510   if ( $prospectnum ) {
511
512     warn "  moving contacts and locations from prospect $prospectnum\n"
513       if $DEBUG > 1;
514
515     my $prospect_main =
516       qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
517     unless ( $prospect_main ) {
518       $dbh->rollback if $oldAutoCommit;
519       return "Unknown prospectnum $prospectnum";
520     }
521     $prospect_main->custnum($self->custnum);
522     $prospect_main->disabled('Y');
523     my $error = $prospect_main->replace;
524     if ( $error ) {
525       $dbh->rollback if $oldAutoCommit;
526       return $error;
527     }
528
529     my @contact = $prospect_main->contact;
530     my @cust_location = $prospect_main->cust_location;
531     my @qual = $prospect_main->qual;
532
533     foreach my $r ( @contact, @cust_location, @qual ) {
534       $r->prospectnum('');
535       $r->custnum($self->custnum);
536       my $error = $r->replace;
537       if ( $error ) {
538         $dbh->rollback if $oldAutoCommit;
539         return $error;
540       }
541     }
542
543   }
544
545   # validate card (needs custnum already set)
546   if ( $self->payby =~ /^(CARD|DCRD)$/
547        && $conf->exists('business-onlinepayment-verification') ) {
548     $error = $self->realtime_verify_bop({ 'method'=>'CC' });
549     if ( $error ) {
550       $dbh->rollback if $oldAutoCommit;
551       return $error;
552     }
553   }
554
555   warn "  setting contacts\n"
556     if $DEBUG > 1;
557
558   if ( my $contact = delete $options{'contact'} ) {
559
560     foreach my $c ( @$contact ) {
561       $c->custnum($self->custnum);
562       my $error = $c->insert;
563       if ( $error ) {
564         $dbh->rollback if $oldAutoCommit;
565         return $error;
566       }
567
568     }
569
570   } elsif ( my $contact_params = delete $options{'contact_params'} ) {
571
572     my $error = $self->process_o2m( 'table'  => 'contact',
573                                     'fields' => FS::contact->cgi_contact_fields,
574                                     'params' => $contact_params,
575                                   );
576     if ( $error ) {
577       $dbh->rollback if $oldAutoCommit;
578       return $error;
579     }
580   }
581
582   warn "  setting cust_main_exemption\n"
583     if $DEBUG > 1;
584
585   my $tax_exemption = delete $options{'tax_exemption'};
586   if ( $tax_exemption ) {
587
588     $tax_exemption = { map { $_ => '' } @$tax_exemption }
589       if ref($tax_exemption) eq 'ARRAY';
590
591     foreach my $taxname ( keys %$tax_exemption ) {
592       my $cust_main_exemption = new FS::cust_main_exemption {
593         'custnum'       => $self->custnum,
594         'taxname'       => $taxname,
595         'exempt_number' => $tax_exemption->{$taxname},
596       };
597       my $error = $cust_main_exemption->insert;
598       if ( $error ) {
599         $dbh->rollback if $oldAutoCommit;
600         return "inserting cust_main_exemption (transaction rolled back): $error";
601       }
602     }
603   }
604
605   warn "  ordering packages\n"
606     if $DEBUG > 1;
607
608   $error = $self->order_pkgs( $cust_pkgs,
609                               %options,
610                               'seconds_ref'    => \$seconds,
611                               'upbytes_ref'    => \$upbytes,
612                               'downbytes_ref'  => \$downbytes,
613                               'totalbytes_ref' => \$totalbytes,
614                             );
615   if ( $error ) {
616     $dbh->rollback if $oldAutoCommit;
617     return $error;
618   }
619
620   if ( $seconds ) {
621     $dbh->rollback if $oldAutoCommit;
622     return "No svc_acct record to apply pre-paid time";
623   }
624   if ( $upbytes || $downbytes || $totalbytes ) {
625     $dbh->rollback if $oldAutoCommit;
626     return "No svc_acct record to apply pre-paid data";
627   }
628
629   if ( $amount ) {
630     warn "  inserting initial $payby payment of $amount\n"
631       if $DEBUG > 1;
632     $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
633     if ( $error ) {
634       $dbh->rollback if $oldAutoCommit;
635       return "inserting payment (transaction rolled back): $error";
636     }
637   }
638
639   unless ( $import || $skip_fuzzyfiles ) {
640     warn "  queueing fuzzyfiles update\n"
641       if $DEBUG > 1;
642     $error = $self->queue_fuzzyfiles_update;
643     if ( $error ) {
644       $dbh->rollback if $oldAutoCommit;
645       return "updating fuzzy search cache: $error";
646     }
647   }
648
649   # FS::geocode_Mixin::after_insert or something?
650   if ( $conf->config('tax_district_method') and !$import ) {
651     # if anything non-empty, try to look it up
652     my $queue = new FS::queue {
653       'job'     => 'FS::geocode_Mixin::process_district_update',
654       'custnum' => $self->custnum,
655     };
656     my $error = $queue->insert( ref($self), $self->custnum );
657     if ( $error ) {
658       $dbh->rollback if $oldAutoCommit;
659       return "queueing tax district update: $error";
660     }
661   }
662
663   # cust_main exports!
664   warn "  exporting\n" if $DEBUG > 1;
665
666   my $export_args = $options{'export_args'} || [];
667
668   my @part_export =
669     map qsearch( 'part_export', {exportnum=>$_} ),
670       $conf->config('cust_main-exports'); #, $agentnum
671
672   foreach my $part_export ( @part_export ) {
673     my $error = $part_export->export_insert($self, @$export_args);
674     if ( $error ) {
675       $dbh->rollback if $oldAutoCommit;
676       return "exporting to ". $part_export->exporttype.
677              " (transaction rolled back): $error";
678     }
679   }
680
681   #foreach my $depend_jobnum ( @$depend_jobnums ) {
682   #    warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
683   #      if $DEBUG;
684   #    foreach my $jobnum ( @jobnums ) {
685   #      my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
686   #      warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
687   #        if $DEBUG;
688   #      my $error = $queue->depend_insert($depend_jobnum);
689   #      if ( $error ) {
690   #        $dbh->rollback if $oldAutoCommit;
691   #        return "error queuing job dependancy: $error";
692   #      }
693   #    }
694   #  }
695   #
696   #}
697   #
698   #if ( exists $options{'jobnums'} ) {
699   #  push @{ $options{'jobnums'} }, @jobnums;
700   #}
701
702   warn "  insert complete; committing transaction\n"
703     if $DEBUG > 1;
704
705   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
706   '';
707
708 }
709
710 use File::CounterFile;
711 sub auto_agent_custid {
712   my $self = shift;
713
714   my $format = $conf->config('cust_main-auto_agent_custid');
715   my $agent_custid;
716   if ( $format eq '1YMMXXXXXXXX' ) {
717
718     my $counter = new File::CounterFile 'cust_main.agent_custid';
719     $counter->lock;
720
721     my $ym = 100000000000 + time2str('%y%m00000000', time);
722     if ( $ym > $counter->value ) {
723       $counter->{'value'} = $agent_custid = $ym;
724       $counter->{'updated'} = 1;
725     } else {
726       $agent_custid = $counter->inc;
727     }
728
729     $counter->unlock;
730
731   } else {
732     die "Unknown cust_main-auto_agent_custid format: $format";
733   }
734
735   $self->agent_custid($agent_custid);
736
737 }
738
739 =item PACKAGE METHODS
740
741 Documentation on customer package methods has been moved to
742 L<FS::cust_main::Packages>.
743
744 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
745
746 Recharges this (existing) customer with the specified prepaid card (see
747 L<FS::prepay_credit>), specified either by I<identifier> or as an
748 FS::prepay_credit object.  If there is an error, returns the error, otherwise
749 returns false.
750
751 Optionally, five scalar references can be passed as well.  They will have their
752 values filled in with the amount, number of seconds, and number of upload,
753 download, and total bytes applied by this prepaid card.
754
755 =cut
756
757 #the ref bullshit here should be refactored like get_prepay.  MyAccount.pm is
758 #the only place that uses these args
759 sub recharge_prepay { 
760   my( $self, $prepay_credit, $amountref, $secondsref, 
761       $upbytesref, $downbytesref, $totalbytesref ) = @_;
762
763   local $SIG{HUP} = 'IGNORE';
764   local $SIG{INT} = 'IGNORE';
765   local $SIG{QUIT} = 'IGNORE';
766   local $SIG{TERM} = 'IGNORE';
767   local $SIG{TSTP} = 'IGNORE';
768   local $SIG{PIPE} = 'IGNORE';
769
770   my $oldAutoCommit = $FS::UID::AutoCommit;
771   local $FS::UID::AutoCommit = 0;
772   my $dbh = dbh;
773
774   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
775
776   my $error = $self->get_prepay( $prepay_credit,
777                                  'amount_ref'     => \$amount,
778                                  'seconds_ref'    => \$seconds,
779                                  'upbytes_ref'    => \$upbytes,
780                                  'downbytes_ref'  => \$downbytes,
781                                  'totalbytes_ref' => \$totalbytes,
782                                )
783            || $self->increment_seconds($seconds)
784            || $self->increment_upbytes($upbytes)
785            || $self->increment_downbytes($downbytes)
786            || $self->increment_totalbytes($totalbytes)
787            || $self->insert_cust_pay_prepay( $amount,
788                                              ref($prepay_credit)
789                                                ? $prepay_credit->identifier
790                                                : $prepay_credit
791                                            );
792
793   if ( $error ) {
794     $dbh->rollback if $oldAutoCommit;
795     return $error;
796   }
797
798   if ( defined($amountref)  ) { $$amountref  = $amount;  }
799   if ( defined($secondsref) ) { $$secondsref = $seconds; }
800   if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
801   if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
802   if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
803
804   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
805   '';
806
807 }
808
809 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
810
811 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
812 specified either by I<identifier> or as an FS::prepay_credit object.
813
814 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
815 incremented by the values of the prepaid card.
816
817 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
818 check or set this customer's I<agentnum>.
819
820 If there is an error, returns the error, otherwise returns false.
821
822 =cut
823
824
825 sub get_prepay {
826   my( $self, $prepay_credit, %opt ) = @_;
827
828   local $SIG{HUP} = 'IGNORE';
829   local $SIG{INT} = 'IGNORE';
830   local $SIG{QUIT} = 'IGNORE';
831   local $SIG{TERM} = 'IGNORE';
832   local $SIG{TSTP} = 'IGNORE';
833   local $SIG{PIPE} = 'IGNORE';
834
835   my $oldAutoCommit = $FS::UID::AutoCommit;
836   local $FS::UID::AutoCommit = 0;
837   my $dbh = dbh;
838
839   unless ( ref($prepay_credit) ) {
840
841     my $identifier = $prepay_credit;
842
843     $prepay_credit = qsearchs(
844       'prepay_credit',
845       { 'identifier' => $identifier },
846       '',
847       'FOR UPDATE'
848     );
849
850     unless ( $prepay_credit ) {
851       $dbh->rollback if $oldAutoCommit;
852       return "Invalid prepaid card: ". $identifier;
853     }
854
855   }
856
857   if ( $prepay_credit->agentnum ) {
858     if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
859       $dbh->rollback if $oldAutoCommit;
860       return "prepaid card not valid for agent ". $self->agentnum;
861     }
862     $self->agentnum($prepay_credit->agentnum);
863   }
864
865   my $error = $prepay_credit->delete;
866   if ( $error ) {
867     $dbh->rollback if $oldAutoCommit;
868     return "removing prepay_credit (transaction rolled back): $error";
869   }
870
871   ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
872     for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
873
874   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
875   '';
876
877 }
878
879 =item increment_upbytes SECONDS
880
881 Updates this customer's single or primary account (see L<FS::svc_acct>) by
882 the specified number of upbytes.  If there is an error, returns the error,
883 otherwise returns false.
884
885 =cut
886
887 sub increment_upbytes {
888   _increment_column( shift, 'upbytes', @_);
889 }
890
891 =item increment_downbytes SECONDS
892
893 Updates this customer's single or primary account (see L<FS::svc_acct>) by
894 the specified number of downbytes.  If there is an error, returns the error,
895 otherwise returns false.
896
897 =cut
898
899 sub increment_downbytes {
900   _increment_column( shift, 'downbytes', @_);
901 }
902
903 =item increment_totalbytes SECONDS
904
905 Updates this customer's single or primary account (see L<FS::svc_acct>) by
906 the specified number of totalbytes.  If there is an error, returns the error,
907 otherwise returns false.
908
909 =cut
910
911 sub increment_totalbytes {
912   _increment_column( shift, 'totalbytes', @_);
913 }
914
915 =item increment_seconds SECONDS
916
917 Updates this customer's single or primary account (see L<FS::svc_acct>) by
918 the specified number of seconds.  If there is an error, returns the error,
919 otherwise returns false.
920
921 =cut
922
923 sub increment_seconds {
924   _increment_column( shift, 'seconds', @_);
925 }
926
927 =item _increment_column AMOUNT
928
929 Updates this customer's single or primary account (see L<FS::svc_acct>) by
930 the specified number of seconds or bytes.  If there is an error, returns
931 the error, otherwise returns false.
932
933 =cut
934
935 sub _increment_column {
936   my( $self, $column, $amount ) = @_;
937   warn "$me increment_column called: $column, $amount\n"
938     if $DEBUG;
939
940   return '' unless $amount;
941
942   my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
943                       $self->ncancelled_pkgs;
944
945   if ( ! @cust_pkg ) {
946     return 'No packages with primary or single services found'.
947            ' to apply pre-paid time';
948   } elsif ( scalar(@cust_pkg) > 1 ) {
949     #maybe have a way to specify the package/account?
950     return 'Multiple packages found to apply pre-paid time';
951   }
952
953   my $cust_pkg = $cust_pkg[0];
954   warn "  found package pkgnum ". $cust_pkg->pkgnum. "\n"
955     if $DEBUG > 1;
956
957   my @cust_svc =
958     $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
959
960   if ( ! @cust_svc ) {
961     return 'No account found to apply pre-paid time';
962   } elsif ( scalar(@cust_svc) > 1 ) {
963     return 'Multiple accounts found to apply pre-paid time';
964   }
965   
966   my $svc_acct = $cust_svc[0]->svc_x;
967   warn "  found service svcnum ". $svc_acct->pkgnum.
968        ' ('. $svc_acct->email. ")\n"
969     if $DEBUG > 1;
970
971   $column = "increment_$column";
972   $svc_acct->$column($amount);
973
974 }
975
976 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
977
978 Inserts a prepayment in the specified amount for this customer.  An optional
979 second argument can specify the prepayment identifier for tracking purposes.
980 If there is an error, returns the error, otherwise returns false.
981
982 =cut
983
984 sub insert_cust_pay_prepay {
985   shift->insert_cust_pay('PREP', @_);
986 }
987
988 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
989
990 Inserts a cash payment in the specified amount for this customer.  An optional
991 second argument can specify the payment identifier for tracking purposes.
992 If there is an error, returns the error, otherwise returns false.
993
994 =cut
995
996 sub insert_cust_pay_cash {
997   shift->insert_cust_pay('CASH', @_);
998 }
999
1000 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1001
1002 Inserts a Western Union payment in the specified amount for this customer.  An
1003 optional second argument can specify the prepayment identifier for tracking
1004 purposes.  If there is an error, returns the error, otherwise returns false.
1005
1006 =cut
1007
1008 sub insert_cust_pay_west {
1009   shift->insert_cust_pay('WEST', @_);
1010 }
1011
1012 sub insert_cust_pay {
1013   my( $self, $payby, $amount ) = splice(@_, 0, 3);
1014   my $payinfo = scalar(@_) ? shift : '';
1015
1016   my $cust_pay = new FS::cust_pay {
1017     'custnum' => $self->custnum,
1018     'paid'    => sprintf('%.2f', $amount),
1019     #'_date'   => #date the prepaid card was purchased???
1020     'payby'   => $payby,
1021     'payinfo' => $payinfo,
1022   };
1023   $cust_pay->insert;
1024
1025 }
1026
1027 =item reexport
1028
1029 This method is deprecated.  See the I<depend_jobnum> option to the insert and
1030 order_pkgs methods for a better way to defer provisioning.
1031
1032 Re-schedules all exports by calling the B<reexport> method of all associated
1033 packages (see L<FS::cust_pkg>).  If there is an error, returns the error;
1034 otherwise returns false.
1035
1036 =cut
1037
1038 sub reexport {
1039   my $self = shift;
1040
1041   carp "WARNING: FS::cust_main::reexport is deprectated; ".
1042        "use the depend_jobnum option to insert or order_pkgs to delay export";
1043
1044   local $SIG{HUP} = 'IGNORE';
1045   local $SIG{INT} = 'IGNORE';
1046   local $SIG{QUIT} = 'IGNORE';
1047   local $SIG{TERM} = 'IGNORE';
1048   local $SIG{TSTP} = 'IGNORE';
1049   local $SIG{PIPE} = 'IGNORE';
1050
1051   my $oldAutoCommit = $FS::UID::AutoCommit;
1052   local $FS::UID::AutoCommit = 0;
1053   my $dbh = dbh;
1054
1055   foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1056     my $error = $cust_pkg->reexport;
1057     if ( $error ) {
1058       $dbh->rollback if $oldAutoCommit;
1059       return $error;
1060     }
1061   }
1062
1063   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1064   '';
1065
1066 }
1067
1068 =item delete [ OPTION => VALUE ... ]
1069
1070 This deletes the customer.  If there is an error, returns the error, otherwise
1071 returns false.
1072
1073 This will completely remove all traces of the customer record.  This is not
1074 what you want when a customer cancels service; for that, cancel all of the
1075 customer's packages (see L</cancel>).
1076
1077 If the customer has any uncancelled packages, you need to pass a new (valid)
1078 customer number for those packages to be transferred to, as the "new_customer"
1079 option.  Cancelled packages will be deleted.  Did I mention that this is NOT
1080 what you want when a customer cancels service and that you really should be
1081 looking at L<FS::cust_pkg/cancel>?  
1082
1083 You can't delete a customer with invoices (see L<FS::cust_bill>),
1084 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1085 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1086 set the "delete_financials" option to a true value.
1087
1088 =cut
1089
1090 sub delete {
1091   my( $self, %opt ) = @_;
1092
1093   local $SIG{HUP} = 'IGNORE';
1094   local $SIG{INT} = 'IGNORE';
1095   local $SIG{QUIT} = 'IGNORE';
1096   local $SIG{TERM} = 'IGNORE';
1097   local $SIG{TSTP} = 'IGNORE';
1098   local $SIG{PIPE} = 'IGNORE';
1099
1100   my $oldAutoCommit = $FS::UID::AutoCommit;
1101   local $FS::UID::AutoCommit = 0;
1102   my $dbh = dbh;
1103
1104   if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1105      $dbh->rollback if $oldAutoCommit;
1106      return "Can't delete a master agent customer";
1107   }
1108
1109   #use FS::access_user
1110   if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1111      $dbh->rollback if $oldAutoCommit;
1112      return "Can't delete a master employee customer";
1113   }
1114
1115   tie my %financial_tables, 'Tie::IxHash',
1116     'cust_bill'      => 'invoices',
1117     'cust_statement' => 'statements',
1118     'cust_credit'    => 'credits',
1119     'cust_pay'       => 'payments',
1120     'cust_refund'    => 'refunds',
1121   ;
1122    
1123   foreach my $table ( keys %financial_tables ) {
1124
1125     my @records = $self->$table();
1126
1127     if ( @records && ! $opt{'delete_financials'} ) {
1128       $dbh->rollback if $oldAutoCommit;
1129       return "Can't delete a customer with ". $financial_tables{$table};
1130     }
1131
1132     foreach my $record ( @records ) {
1133       my $error = $record->delete;
1134       if ( $error ) {
1135         $dbh->rollback if $oldAutoCommit;
1136         return "Error deleting ". $financial_tables{$table}. ": $error\n";
1137       }
1138     }
1139
1140   }
1141
1142   my @cust_pkg = $self->ncancelled_pkgs;
1143   if ( @cust_pkg ) {
1144     my $new_custnum = $opt{'new_custnum'};
1145     unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1146       $dbh->rollback if $oldAutoCommit;
1147       return "Invalid new customer number: $new_custnum";
1148     }
1149     foreach my $cust_pkg ( @cust_pkg ) {
1150       my %hash = $cust_pkg->hash;
1151       $hash{'custnum'} = $new_custnum;
1152       my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1153       my $error = $new_cust_pkg->replace($cust_pkg,
1154                                          options => { $cust_pkg->options },
1155                                         );
1156       if ( $error ) {
1157         $dbh->rollback if $oldAutoCommit;
1158         return $error;
1159       }
1160     }
1161   }
1162   my @cancelled_cust_pkg = $self->all_pkgs;
1163   foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1164     my $error = $cust_pkg->delete;
1165     if ( $error ) {
1166       $dbh->rollback if $oldAutoCommit;
1167       return $error;
1168     }
1169   }
1170
1171   #cust_tax_adjustment in financials?
1172   #cust_pay_pending?  ouch
1173   #cust_recon?
1174   foreach my $table (qw(
1175     cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1176     cust_location cust_main_note cust_tax_adjustment
1177     cust_pay_void cust_pay_batch queue cust_tax_exempt
1178   )) {
1179     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1180       my $error = $record->delete;
1181       if ( $error ) {
1182         $dbh->rollback if $oldAutoCommit;
1183         return $error;
1184       }
1185     }
1186   }
1187
1188   my $sth = $dbh->prepare(
1189     'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1190   ) or do {
1191     my $errstr = $dbh->errstr;
1192     $dbh->rollback if $oldAutoCommit;
1193     return $errstr;
1194   };
1195   $sth->execute($self->custnum) or do {
1196     my $errstr = $sth->errstr;
1197     $dbh->rollback if $oldAutoCommit;
1198     return $errstr;
1199   };
1200
1201   #tickets
1202
1203   my $ticket_dbh = '';
1204   if ($conf->config('ticket_system') eq 'RT_Internal') {
1205     $ticket_dbh = $dbh;
1206   } elsif ($conf->config('ticket_system') eq 'RT_External') {
1207     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1208     $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1209       #or die "RT_External DBI->connect error: $DBI::errstr\n";
1210   }
1211
1212   if ( $ticket_dbh ) {
1213
1214     my $ticket_sth = $ticket_dbh->prepare(
1215       'DELETE FROM Links WHERE Target = ?'
1216     ) or do {
1217       my $errstr = $ticket_dbh->errstr;
1218       $dbh->rollback if $oldAutoCommit;
1219       return $errstr;
1220     };
1221     $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1222       or do {
1223         my $errstr = $ticket_sth->errstr;
1224         $dbh->rollback if $oldAutoCommit;
1225         return $errstr;
1226       };
1227
1228     #check and see if the customer is the only link on the ticket, and
1229     #if so, set the ticket to deleted status in RT?
1230     #maybe someday, for now this will at least fix tickets not displaying
1231
1232   }
1233
1234   #delete the customer record
1235
1236   my $error = $self->SUPER::delete;
1237   if ( $error ) {
1238     $dbh->rollback if $oldAutoCommit;
1239     return $error;
1240   }
1241
1242   # cust_main exports!
1243
1244   #my $export_args = $options{'export_args'} || [];
1245
1246   my @part_export =
1247     map qsearch( 'part_export', {exportnum=>$_} ),
1248       $conf->config('cust_main-exports'); #, $agentnum
1249
1250   foreach my $part_export ( @part_export ) {
1251     my $error = $part_export->export_delete( $self ); #, @$export_args);
1252     if ( $error ) {
1253       $dbh->rollback if $oldAutoCommit;
1254       return "exporting to ". $part_export->exporttype.
1255              " (transaction rolled back): $error";
1256     }
1257   }
1258
1259   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1260   '';
1261
1262 }
1263
1264 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1265
1266 This merges this customer into the provided new custnum, and then deletes the
1267 customer.  If there is an error, returns the error, otherwise returns false.
1268
1269 The source customer's name, company name, phone numbers, agent,
1270 referring customer, customer class, advertising source, order taker, and
1271 billing information (except balance) are discarded.
1272
1273 All packages are moved to the target customer.  Packages with package locations
1274 are preserved.  Packages without package locations are moved to a new package
1275 location with the source customer's service/shipping address.
1276
1277 All invoices, statements, payments, credits and refunds are moved to the target
1278 customer.  The source customer's balance is added to the target customer.
1279
1280 All notes, attachments, tickets and customer tags are moved to the target
1281 customer.
1282
1283 Change history is not currently moved.
1284
1285 =cut
1286
1287 sub merge {
1288   my( $self, $new_custnum, %opt ) = @_;
1289
1290   return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1291
1292   my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1293     or return "Invalid new customer number: $new_custnum";
1294
1295   return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1296     if $self->agentnum != $new_cust_main->agentnum 
1297     && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1298
1299   local $SIG{HUP} = 'IGNORE';
1300   local $SIG{INT} = 'IGNORE';
1301   local $SIG{QUIT} = 'IGNORE';
1302   local $SIG{TERM} = 'IGNORE';
1303   local $SIG{TSTP} = 'IGNORE';
1304   local $SIG{PIPE} = 'IGNORE';
1305
1306   my $oldAutoCommit = $FS::UID::AutoCommit;
1307   local $FS::UID::AutoCommit = 0;
1308   my $dbh = dbh;
1309
1310   if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1311      $dbh->rollback if $oldAutoCommit;
1312      return "Can't merge a master agent customer";
1313   }
1314
1315   #use FS::access_user
1316   if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1317      $dbh->rollback if $oldAutoCommit;
1318      return "Can't merge a master employee customer";
1319   }
1320
1321   if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1322                                      'status'  => { op=>'!=', value=>'done' },
1323                                    }
1324               )
1325   ) {
1326      $dbh->rollback if $oldAutoCommit;
1327      return "Can't merge a customer with pending payments";
1328   }
1329
1330   tie my %financial_tables, 'Tie::IxHash',
1331     'cust_bill'         => 'invoices',
1332     'cust_bill_void'    => 'voided invoices',
1333     'cust_statement'    => 'statements',
1334     'cust_credit'       => 'credits',
1335     'cust_credit_void'  => 'voided credits',
1336     'cust_pay'          => 'payments',
1337     'cust_pay_void'     => 'voided payments',
1338     'cust_refund'       => 'refunds',
1339   ;
1340    
1341   foreach my $table ( keys %financial_tables ) {
1342
1343     my @records = $self->$table();
1344
1345     foreach my $record ( @records ) {
1346       $record->custnum($new_custnum);
1347       my $error = $record->replace;
1348       if ( $error ) {
1349         $dbh->rollback if $oldAutoCommit;
1350         return "Error merging ". $financial_tables{$table}. ": $error\n";
1351       }
1352     }
1353
1354   }
1355
1356   my $name = $self->ship_name; #?
1357
1358   my $locationnum = '';
1359   foreach my $cust_pkg ( $self->all_pkgs ) {
1360     $cust_pkg->custnum($new_custnum);
1361
1362     unless ( $cust_pkg->locationnum ) {
1363       unless ( $locationnum ) {
1364         my $cust_location = new FS::cust_location {
1365           $self->location_hash,
1366           'custnum' => $new_custnum,
1367         };
1368         my $error = $cust_location->insert;
1369         if ( $error ) {
1370           $dbh->rollback if $oldAutoCommit;
1371           return $error;
1372         }
1373         $locationnum = $cust_location->locationnum;
1374       }
1375       $cust_pkg->locationnum($locationnum);
1376     }
1377
1378     my $error = $cust_pkg->replace;
1379     if ( $error ) {
1380       $dbh->rollback if $oldAutoCommit;
1381       return $error;
1382     }
1383
1384     # add customer (ship) name to svc_phone.phone_name if blank
1385     my @cust_svc = $cust_pkg->cust_svc;
1386     foreach my $cust_svc (@cust_svc) {
1387       my($label, $value, $svcdb) = $cust_svc->label;
1388       next unless $svcdb eq 'svc_phone';
1389       my $svc_phone = $cust_svc->svc_x;
1390       next if $svc_phone->phone_name;
1391       $svc_phone->phone_name($name);
1392       my $error = $svc_phone->replace;
1393       if ( $error ) {
1394         $dbh->rollback if $oldAutoCommit;
1395         return $error;
1396       }
1397     }
1398
1399   }
1400
1401   #not considered:
1402   # cust_tax_exempt (texas tax exemptions)
1403   # cust_recon (some sort of not-well understood thing for OnPac)
1404
1405   #these are moved over
1406   foreach my $table (qw(
1407     cust_tag cust_location contact cust_attachment cust_main_note
1408     cust_tax_adjustment cust_pay_batch queue
1409   )) {
1410     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1411       $record->custnum($new_custnum);
1412       my $error = $record->replace;
1413       if ( $error ) {
1414         $dbh->rollback if $oldAutoCommit;
1415         return $error;
1416       }
1417     }
1418   }
1419
1420   #these aren't preserved
1421   foreach my $table (qw(
1422     cust_main_exemption cust_main_invoice
1423   )) {
1424     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1425       my $error = $record->delete;
1426       if ( $error ) {
1427         $dbh->rollback if $oldAutoCommit;
1428         return $error;
1429       }
1430     }
1431   }
1432
1433
1434   my $sth = $dbh->prepare(
1435     'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1436   ) or do {
1437     my $errstr = $dbh->errstr;
1438     $dbh->rollback if $oldAutoCommit;
1439     return $errstr;
1440   };
1441   $sth->execute($new_custnum, $self->custnum) or do {
1442     my $errstr = $sth->errstr;
1443     $dbh->rollback if $oldAutoCommit;
1444     return $errstr;
1445   };
1446
1447   #tickets
1448
1449   my $ticket_dbh = '';
1450   if ($conf->config('ticket_system') eq 'RT_Internal') {
1451     $ticket_dbh = $dbh;
1452   } elsif ($conf->config('ticket_system') eq 'RT_External') {
1453     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1454     $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1455       #or die "RT_External DBI->connect error: $DBI::errstr\n";
1456   }
1457
1458   if ( $ticket_dbh ) {
1459
1460     my $ticket_sth = $ticket_dbh->prepare(
1461       'UPDATE Links SET Target = ? WHERE Target = ?'
1462     ) or do {
1463       my $errstr = $ticket_dbh->errstr;
1464       $dbh->rollback if $oldAutoCommit;
1465       return $errstr;
1466     };
1467     $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1468                          'freeside://freeside/cust_main/'.$self->custnum)
1469       or do {
1470         my $errstr = $ticket_sth->errstr;
1471         $dbh->rollback if $oldAutoCommit;
1472         return $errstr;
1473       };
1474
1475   }
1476
1477   #delete the customer record
1478
1479   my $error = $self->delete;
1480   if ( $error ) {
1481     $dbh->rollback if $oldAutoCommit;
1482     return $error;
1483   }
1484
1485   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1486   '';
1487
1488 }
1489
1490 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1491
1492 Replaces the OLD_RECORD with this one in the database.  If there is an error,
1493 returns the error, otherwise returns false.
1494
1495 To change the customer's address, set the pseudo-fields C<bill_location> and
1496 C<ship_location>.  The address will still only change if at least one of the
1497 address fields differs from the existing values.
1498
1499 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1500 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
1501 expected and rollback the entire transaction; it is not necessary to call 
1502 check_invoicing_list first.  Here's an example:
1503
1504   $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1505
1506 Currently available options are: I<tax_exemption>.
1507
1508 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1509 of tax names and exemption numbers.  FS::cust_main_exemption records will be
1510 deleted and inserted as appropriate.
1511
1512 =cut
1513
1514 sub replace {
1515   my $self = shift;
1516
1517   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1518               ? shift
1519               : $self->replace_old;
1520
1521   my @param = @_;
1522
1523   warn "$me replace called\n"
1524     if $DEBUG;
1525
1526   my $curuser = $FS::CurrentUser::CurrentUser;
1527   if (    $self->payby eq 'COMP'
1528        && $self->payby ne $old->payby
1529        && ! $curuser->access_right('Complimentary customer')
1530      )
1531   {
1532     return "You are not permitted to create complimentary accounts.";
1533   }
1534
1535   local($ignore_expired_card) = 1
1536     if $old->payby  =~ /^(CARD|DCRD)$/
1537     && $self->payby =~ /^(CARD|DCRD)$/
1538     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1539
1540   local($ignore_banned_card) = 1
1541     if (    $old->payby  =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1542          || $old->payby  =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1543     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1544
1545   if (    $self->payby =~ /^(CARD|DCRD)$/
1546        && $old->payinfo ne $self->payinfo
1547        && $old->paymask ne $self->paymask )
1548   {
1549     my $error = $self->check_payinfo_cardtype;
1550     return $error if $error;
1551
1552     if ( $conf->exists('business-onlinepayment-verification') ) {
1553       #need to standardize paydate for this, false laziness with check
1554       my( $m, $y );
1555       if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1556         ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1557       } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1558         ( $m, $y ) = ( $2, "19$1" );
1559       } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1560         ( $m, $y ) = ( $3, "20$2" );
1561       } else {
1562         return "Illegal expiration date: ". $self->paydate;
1563       }
1564       $m = sprintf('%02d',$m);
1565       $self->paydate("$y-$m-01");
1566
1567       $error = $self->realtime_verify_bop({ 'method'=>'CC' });
1568       return $error if $error;
1569     }
1570   }
1571
1572   return "Invoicing locale is required"
1573     if $old->locale
1574     && ! $self->locale
1575     && $conf->exists('cust_main-require_locale');
1576
1577   local $SIG{HUP} = 'IGNORE';
1578   local $SIG{INT} = 'IGNORE';
1579   local $SIG{QUIT} = 'IGNORE';
1580   local $SIG{TERM} = 'IGNORE';
1581   local $SIG{TSTP} = 'IGNORE';
1582   local $SIG{PIPE} = 'IGNORE';
1583
1584   my $oldAutoCommit = $FS::UID::AutoCommit;
1585   local $FS::UID::AutoCommit = 0;
1586   my $dbh = dbh;
1587
1588   for my $l (qw(bill_location ship_location)) {
1589     my $old_loc = $old->$l;
1590     my $new_loc = $self->$l;
1591
1592     # find the existing location if there is one
1593     $new_loc->set('custnum' => $self->custnum);
1594     my $error = $new_loc->find_or_insert;
1595     if ( $error ) {
1596       $dbh->rollback if $oldAutoCommit;
1597       return $error;
1598     }
1599     $self->set($l.'num', $new_loc->locationnum);
1600   } #for $l
1601
1602   # replace the customer record
1603   my $error = $self->SUPER::replace($old);
1604
1605   if ( $error ) {
1606     $dbh->rollback if $oldAutoCommit;
1607     return $error;
1608   }
1609
1610   # now move packages to the new service location
1611   $self->set('ship_location', ''); #flush cache
1612   if ( $old->ship_locationnum and # should only be null during upgrade...
1613        $old->ship_locationnum != $self->ship_locationnum ) {
1614     $error = $old->ship_location->move_to($self->ship_location);
1615     if ( $error ) {
1616       $dbh->rollback if $oldAutoCommit;
1617       return $error;
1618     }
1619   }
1620   # don't move packages based on the billing location, but 
1621   # disable it if it's no longer in use
1622   if ( $old->bill_locationnum and
1623        $old->bill_locationnum != $self->bill_locationnum ) {
1624     $error = $old->bill_location->disable_if_unused;
1625     if ( $error ) {
1626       $dbh->rollback if $oldAutoCommit;
1627       return $error;
1628     }
1629   }
1630
1631   if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1632     my $invoicing_list = shift @param;
1633     $error = $self->check_invoicing_list( $invoicing_list );
1634     if ( $error ) {
1635       $dbh->rollback if $oldAutoCommit;
1636       return $error;
1637     }
1638     $self->invoicing_list( $invoicing_list );
1639   }
1640
1641   if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1642
1643     #this could be more efficient than deleting and re-inserting, if it matters
1644     foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1645       my $error = $cust_tag->delete;
1646       if ( $error ) {
1647         $dbh->rollback if $oldAutoCommit;
1648         return $error;
1649       }
1650     }
1651     foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1652       my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
1653                                         'custnum' => $self->custnum };
1654       my $error = $cust_tag->insert;
1655       if ( $error ) {
1656         $dbh->rollback if $oldAutoCommit;
1657         return $error;
1658       }
1659     }
1660
1661   }
1662
1663   my %options = @param;
1664
1665   my $tax_exemption = delete $options{'tax_exemption'};
1666   if ( $tax_exemption ) {
1667
1668     $tax_exemption = { map { $_ => '' } @$tax_exemption }
1669       if ref($tax_exemption) eq 'ARRAY';
1670
1671     my %cust_main_exemption =
1672       map { $_->taxname => $_ }
1673           qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1674
1675     foreach my $taxname ( keys %$tax_exemption ) {
1676
1677       if ( $cust_main_exemption{$taxname} && 
1678            $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1679          )
1680       {
1681         delete $cust_main_exemption{$taxname};
1682         next;
1683       }
1684
1685       my $cust_main_exemption = new FS::cust_main_exemption {
1686         'custnum'       => $self->custnum,
1687         'taxname'       => $taxname,
1688         'exempt_number' => $tax_exemption->{$taxname},
1689       };
1690       my $error = $cust_main_exemption->insert;
1691       if ( $error ) {
1692         $dbh->rollback if $oldAutoCommit;
1693         return "inserting cust_main_exemption (transaction rolled back): $error";
1694       }
1695     }
1696
1697     foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1698       my $error = $cust_main_exemption->delete;
1699       if ( $error ) {
1700         $dbh->rollback if $oldAutoCommit;
1701         return "deleting cust_main_exemption (transaction rolled back): $error";
1702       }
1703     }
1704
1705   }
1706
1707   if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1708        && ( ( $self->get('payinfo') ne $old->get('payinfo')
1709               && $self->get('payinfo') !~ /^99\d{14}$/ 
1710             )
1711             || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1712           )
1713      )
1714   {
1715
1716     # card/check/lec info has changed, want to retry realtime_ invoice events
1717     my $error = $self->retry_realtime;
1718     if ( $error ) {
1719       $dbh->rollback if $oldAutoCommit;
1720       return $error;
1721     }
1722   }
1723
1724   unless ( $import || $skip_fuzzyfiles ) {
1725     $error = $self->queue_fuzzyfiles_update;
1726     if ( $error ) {
1727       $dbh->rollback if $oldAutoCommit;
1728       return "updating fuzzy search cache: $error";
1729     }
1730   }
1731
1732   # tax district update in cust_location
1733
1734   # cust_main exports!
1735
1736   my $export_args = $options{'export_args'} || [];
1737
1738   my @part_export =
1739     map qsearch( 'part_export', {exportnum=>$_} ),
1740       $conf->config('cust_main-exports'); #, $agentnum
1741
1742   foreach my $part_export ( @part_export ) {
1743     my $error = $part_export->export_replace( $self, $old, @$export_args);
1744     if ( $error ) {
1745       $dbh->rollback if $oldAutoCommit;
1746       return "exporting to ". $part_export->exporttype.
1747              " (transaction rolled back): $error";
1748     }
1749   }
1750
1751   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1752   '';
1753
1754 }
1755
1756 =item queue_fuzzyfiles_update
1757
1758 Used by insert & replace to update the fuzzy search cache
1759
1760 =cut
1761
1762 use FS::cust_main::Search;
1763 sub queue_fuzzyfiles_update {
1764   my $self = shift;
1765
1766   local $SIG{HUP} = 'IGNORE';
1767   local $SIG{INT} = 'IGNORE';
1768   local $SIG{QUIT} = 'IGNORE';
1769   local $SIG{TERM} = 'IGNORE';
1770   local $SIG{TSTP} = 'IGNORE';
1771   local $SIG{PIPE} = 'IGNORE';
1772
1773   my $oldAutoCommit = $FS::UID::AutoCommit;
1774   local $FS::UID::AutoCommit = 0;
1775   my $dbh = dbh;
1776
1777   foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1778     my $queue = new FS::queue { 
1779       'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1780     };
1781     my @args = "cust_main.$field", $self->get($field);
1782     my $error = $queue->insert( @args );
1783     if ( $error ) {
1784       $dbh->rollback if $oldAutoCommit;
1785       return "queueing job (transaction rolled back): $error";
1786     }
1787   }
1788
1789   my @locations = $self->bill_location;
1790   push @locations, $self->ship_location if $self->has_ship_address;
1791   foreach my $location (@locations) {
1792     my $queue = new FS::queue { 
1793       'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1794     };
1795     my @args = 'cust_location.address1', $location->address1;
1796     my $error = $queue->insert( @args );
1797     if ( $error ) {
1798       $dbh->rollback if $oldAutoCommit;
1799       return "queueing job (transaction rolled back): $error";
1800     }
1801   }
1802
1803   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1804   '';
1805
1806 }
1807
1808 =item check
1809
1810 Checks all fields to make sure this is a valid customer record.  If there is
1811 an error, returns the error, otherwise returns false.  Called by the insert
1812 and replace methods.
1813
1814 =cut
1815
1816 sub check {
1817   my $self = shift;
1818
1819   warn "$me check BEFORE: \n". $self->_dump
1820     if $DEBUG > 2;
1821
1822   my $error =
1823     $self->ut_numbern('custnum')
1824     || $self->ut_number('agentnum')
1825     || $self->ut_textn('agent_custid')
1826     || $self->ut_number('refnum')
1827     || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1828     || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1829     || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1830     || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1831     || $self->ut_textn('custbatch')
1832     || $self->ut_name('last')
1833     || $self->ut_name('first')
1834     || $self->ut_snumbern('signupdate')
1835     || $self->ut_snumbern('birthdate')
1836     || $self->ut_namen('spouse_last')
1837     || $self->ut_namen('spouse_first')
1838     || $self->ut_snumbern('spouse_birthdate')
1839     || $self->ut_snumbern('anniversary_date')
1840     || $self->ut_textn('company')
1841     || $self->ut_textn('ship_company')
1842     || $self->ut_anything('comments')
1843     || $self->ut_numbern('referral_custnum')
1844     || $self->ut_textn('stateid')
1845     || $self->ut_textn('stateid_state')
1846     || $self->ut_textn('invoice_terms')
1847     || $self->ut_floatn('cdr_termination_percentage')
1848     || $self->ut_floatn('credit_limit')
1849     || $self->ut_numbern('billday')
1850     || $self->ut_numbern('prorate_day')
1851     || $self->ut_flag('edit_subject')
1852     || $self->ut_flag('calling_list_exempt')
1853     || $self->ut_flag('invoice_noemail')
1854     || $self->ut_flag('message_noemail')
1855     || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1856     || $self->ut_flag('invoice_ship_address')
1857   ;
1858
1859   foreach (qw(company ship_company)) {
1860     my $company = $self->get($_);
1861     $company =~ s/^\s+//; 
1862     $company =~ s/\s+$//; 
1863     $company =~ s/\s+/ /g;
1864     $self->set($_, $company);
1865   }
1866
1867   #barf.  need message catalogs.  i18n.  etc.
1868   $error .= "Please select an advertising source."
1869     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1870   return $error if $error;
1871
1872   return "Unknown agent"
1873     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1874
1875   return "Unknown refnum"
1876     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1877
1878   return "Unknown referring custnum: ". $self->referral_custnum
1879     unless ! $self->referral_custnum 
1880            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1881
1882   if ( $self->ss eq '' ) {
1883     $self->ss('');
1884   } else {
1885     my $ss = $self->ss;
1886     $ss =~ s/\D//g;
1887     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1888       or return "Illegal social security number: ". $self->ss;
1889     $self->ss("$1-$2-$3");
1890   }
1891
1892   #turn off invoice_ship_address if ship & bill are the same
1893   if ($self->bill_locationnum eq $self->ship_locationnum) {
1894     $self->invoice_ship_address('');
1895   }
1896
1897   # cust_main_county verification now handled by cust_location check
1898
1899   $error =
1900        $self->ut_phonen('daytime', $self->country)
1901     || $self->ut_phonen('night',   $self->country)
1902     || $self->ut_phonen('fax',     $self->country)
1903     || $self->ut_phonen('mobile',  $self->country)
1904   ;
1905   return $error if $error;
1906
1907   if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1908        && ! $import
1909        && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1910      ) {
1911
1912     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1913                           ? 'Day Phone'
1914                           : FS::Msgcat::_gettext('daytime');
1915     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1916                         ? 'Night Phone'
1917                         : FS::Msgcat::_gettext('night');
1918
1919     my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1920                         ? 'Mobile Phone'
1921                         : FS::Msgcat::_gettext('mobile');
1922
1923     return "$daytime_label, $night_label or $mobile_label is required"
1924   
1925   }
1926
1927   #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1928   #  or return "Illegal payby: ". $self->payby;
1929   #$self->payby($1);
1930   FS::payby->can_payby($self->table, $self->payby)
1931     or return "Illegal payby: ". $self->payby;
1932
1933   $error =    $self->ut_numbern('paystart_month')
1934            || $self->ut_numbern('paystart_year')
1935            || $self->ut_numbern('payissue')
1936            || $self->ut_textn('paytype')
1937   ;
1938   return $error if $error;
1939
1940   if ( $self->payip eq '' ) {
1941     $self->payip('');
1942   } else {
1943     $error = $self->ut_ip('payip');
1944     return $error if $error;
1945   }
1946
1947   # If it is encrypted and the private key is not availaible then we can't
1948   # check the credit card.
1949   my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1950
1951   # Need some kind of global flag to accept invalid cards, for testing
1952   # on scrubbed data.
1953   if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1954
1955     my $payinfo = $self->payinfo;
1956     $payinfo =~ s/\D//g;
1957     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1958       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1959     $payinfo = $1;
1960     $self->payinfo($payinfo);
1961     validate($payinfo)
1962       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1963
1964     return gettext('unknown_card_type')
1965       if $self->payinfo !~ /^99\d{14}$/ #token
1966       && cardtype($self->payinfo) eq "Unknown";
1967
1968     unless ( $ignore_banned_card ) {
1969       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1970       if ( $ban ) {
1971         if ( $ban->bantype eq 'warn' ) {
1972           #or others depending on value of $ban->reason ?
1973           return '_duplicate_card'.
1974                  ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1975                  ' until '.         time2str('%a %h %o at %r', $ban->_end_date).
1976                  ' (ban# '. $ban->bannum. ')'
1977             unless $self->override_ban_warn;
1978         } else {
1979           return 'Banned credit card: banned on '.
1980                  time2str('%a %h %o at %r', $ban->_date).
1981                  ' by '. $ban->otaker.
1982                  ' (ban# '. $ban->bannum. ')';
1983         }
1984       }
1985     }
1986
1987     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1988       if ( cardtype($self->payinfo) eq 'American Express card' ) {
1989         $self->paycvv =~ /^(\d{4})$/
1990           or return "CVV2 (CID) for American Express cards is four digits.";
1991         $self->paycvv($1);
1992       } else {
1993         $self->paycvv =~ /^(\d{3})$/
1994           or return "CVV2 (CVC2/CID) is three digits.";
1995         $self->paycvv($1);
1996       }
1997     } else {
1998       $self->paycvv('');
1999     }
2000
2001     my $cardtype = cardtype($payinfo);
2002     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
2003
2004       return "Start date or issue number is required for $cardtype cards"
2005         unless $self->paystart_month && $self->paystart_year or $self->payissue;
2006
2007       return "Start month must be between 1 and 12"
2008         if $self->paystart_month
2009            and $self->paystart_month < 1 || $self->paystart_month > 12;
2010
2011       return "Start year must be 1990 or later"
2012         if $self->paystart_year
2013            and $self->paystart_year < 1990;
2014
2015       return "Issue number must be beween 1 and 99"
2016         if $self->payissue
2017           and $self->payissue < 1 || $self->payissue > 99;
2018
2019     } else {
2020       $self->paystart_month('');
2021       $self->paystart_year('');
2022       $self->payissue('');
2023     }
2024
2025   } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
2026
2027     my $payinfo = $self->payinfo;
2028     $payinfo =~ s/[^\d\@\.]//g;
2029     if ( $conf->config('echeck-country') eq 'CA' ) {
2030       $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
2031         or return 'invalid echeck account@branch.bank';
2032       $payinfo = "$1\@$2.$3";
2033     } elsif ( $conf->config('echeck-country') eq 'US' ) {
2034       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
2035       $payinfo = "$1\@$2";
2036     } else {
2037       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2038       $payinfo = "$1\@$2";
2039     }
2040     $self->payinfo($payinfo);
2041     $self->paycvv('');
2042
2043     unless ( $ignore_banned_card ) {
2044       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2045       if ( $ban ) {
2046         if ( $ban->bantype eq 'warn' ) {
2047           #or others depending on value of $ban->reason ?
2048           return '_duplicate_ach' unless $self->override_ban_warn;
2049         } else {
2050           return 'Banned ACH account: banned on '.
2051                  time2str('%a %h %o at %r', $ban->_date).
2052                  ' by '. $ban->otaker.
2053                  ' (ban# '. $ban->bannum. ')';
2054         }
2055       }
2056     }
2057
2058   } elsif ( $self->payby eq 'LECB' ) {
2059
2060     my $payinfo = $self->payinfo;
2061     $payinfo =~ s/\D//g;
2062     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2063     $payinfo = $1;
2064     $self->payinfo($payinfo);
2065     $self->paycvv('');
2066
2067   } elsif ( $self->payby eq 'BILL' ) {
2068
2069     $error = $self->ut_textn('payinfo');
2070     return "Illegal P.O. number: ". $self->payinfo if $error;
2071     $self->paycvv('');
2072
2073   } elsif ( $self->payby eq 'COMP' ) {
2074
2075     my $curuser = $FS::CurrentUser::CurrentUser;
2076     if (    ! $self->custnum
2077          && ! $curuser->access_right('Complimentary customer')
2078        )
2079     {
2080       return "You are not permitted to create complimentary accounts."
2081     }
2082
2083     $error = $self->ut_textn('payinfo');
2084     return "Illegal comp account issuer: ". $self->payinfo if $error;
2085     $self->paycvv('');
2086
2087   } elsif ( $self->payby eq 'PREPAY' ) {
2088
2089     my $payinfo = $self->payinfo;
2090     $payinfo =~ s/\W//g; #anything else would just confuse things
2091     $self->payinfo($payinfo);
2092     $error = $self->ut_alpha('payinfo');
2093     return "Illegal prepayment identifier: ". $self->payinfo if $error;
2094     return "Unknown prepayment identifier"
2095       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2096     $self->paycvv('');
2097
2098   }
2099
2100   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2101     return "Expiration date required"
2102       # shouldn't payinfo_check do this?
2103       unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2104     $self->paydate('');
2105   } else {
2106     my( $m, $y );
2107     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2108       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2109     } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2110       ( $m, $y ) = ( $2, "19$1" );
2111     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2112       ( $m, $y ) = ( $3, "20$2" );
2113     } else {
2114       return "Illegal expiration date: ". $self->paydate;
2115     }
2116     $m = sprintf('%02d',$m);
2117     $self->paydate("$y-$m-01");
2118     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2119     return gettext('expired_card')
2120       if !$import
2121       && !$ignore_expired_card 
2122       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2123   }
2124
2125   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2126        ( ! $conf->exists('require_cardname')
2127          || $self->payby !~ /^(CARD|DCRD)$/  ) 
2128   ) {
2129     $self->payname( $self->first. " ". $self->getfield('last') );
2130   } else {
2131
2132     if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2133       $self->payname =~ /^([\w \,\.\-\']*)$/
2134         or return gettext('illegal_name'). " payname: ". $self->payname;
2135       $self->payname($1);
2136     } else {
2137       $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2138         or return gettext('illegal_name'). " payname: ". $self->payname;
2139       $self->payname($1);
2140     }
2141
2142   }
2143
2144   return "Please select an invoicing locale"
2145     if ! $self->locale
2146     && ! $self->custnum
2147     && $conf->exists('cust_main-require_locale');
2148
2149   foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2150     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2151     $self->$flag($1);
2152   }
2153
2154   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2155
2156   warn "$me check AFTER: \n". $self->_dump
2157     if $DEBUG > 2;
2158
2159   $self->SUPER::check;
2160 }
2161
2162 sub check_payinfo_cardtype {
2163   my $self = shift;
2164
2165   return '' unless $self->payby =~ /^(CARD|DCRD)$/;
2166
2167   my $payinfo = $self->payinfo;
2168   $payinfo =~ s/\D//g;
2169
2170   return '' if $payinfo =~ /^99\d{14}$/; #token
2171
2172   my %bop_card_types = map { $_=>1 } values %{ card_types() };
2173   my $cardtype = cardtype($payinfo);
2174
2175   return "$cardtype not accepted" unless $bop_card_types{$cardtype};
2176
2177   '';
2178
2179 }
2180
2181 =item replace_check
2182
2183 Additional checks for replace only.
2184
2185 =cut
2186
2187 sub replace_check {
2188   my ($new,$old) = @_;
2189   #preserve old value if global config is set
2190   if ($old && $conf->exists('invoice-ship_address')) {
2191     $new->invoice_ship_address($old->invoice_ship_address);
2192   }
2193   return '';
2194 }
2195
2196 =item addr_fields 
2197
2198 Returns a list of fields which have ship_ duplicates.
2199
2200 =cut
2201
2202 sub addr_fields {
2203   qw( last first company
2204       locationname
2205       address1 address2 city county state zip country
2206       latitude longitude
2207       daytime night fax mobile
2208     );
2209 }
2210
2211 =item has_ship_address
2212
2213 Returns true if this customer record has a separate shipping address.
2214
2215 =cut
2216
2217 sub has_ship_address {
2218   my $self = shift;
2219   $self->bill_locationnum != $self->ship_locationnum;
2220 }
2221
2222 =item location_hash
2223
2224 Returns a list of key/value pairs, with the following keys: address1, 
2225 adddress2, city, county, state, zip, country, district, and geocode.  The 
2226 shipping address is used if present.
2227
2228 =cut
2229
2230 sub location_hash {
2231   my $self = shift;
2232   $self->ship_location->location_hash;
2233 }
2234
2235 =item cust_location
2236
2237 Returns all locations (see L<FS::cust_location>) for this customer.
2238
2239 =cut
2240
2241 sub cust_location {
2242   my $self = shift;
2243   qsearch('cust_location', { 'custnum' => $self->custnum,
2244                              'prospectnum' => '' } );
2245 }
2246
2247 =item cust_contact
2248
2249 Returns all contacts (see L<FS::contact>) for this customer.
2250
2251 =cut
2252
2253 #already used :/ sub contact {
2254 sub cust_contact {
2255   my $self = shift;
2256   qsearch('contact', { 'custnum' => $self->custnum } );
2257 }
2258
2259 =item unsuspend
2260
2261 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2262 and L<FS::cust_pkg>) for this customer, except those on hold.
2263
2264 Returns a list: an empty list on success or a list of errors.
2265
2266 =cut
2267
2268 sub unsuspend {
2269   my $self = shift;
2270   grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2271 }
2272
2273 =item release_hold
2274
2275 Unsuspends all suspended packages in the on-hold state (those without setup 
2276 dates) for this customer. 
2277
2278 =cut
2279
2280 sub release_hold {
2281   my $self = shift;
2282   grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2283 }
2284
2285 =item suspend
2286
2287 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2288
2289 Returns a list: an empty list on success or a list of errors.
2290
2291 =cut
2292
2293 sub suspend {
2294   my $self = shift;
2295   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2296 }
2297
2298 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2299
2300 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2301 PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref instead
2302 of a list of pkgparts; the hashref has the following keys:
2303
2304 =over 4
2305
2306 =item pkgparts - listref of pkgparts
2307
2308 =item (other options are passed to the suspend method)
2309
2310 =back
2311
2312
2313 Returns a list: an empty list on success or a list of errors.
2314
2315 =cut
2316
2317 sub suspend_if_pkgpart {
2318   my $self = shift;
2319   my (@pkgparts, %opt);
2320   if (ref($_[0]) eq 'HASH'){
2321     @pkgparts = @{$_[0]{pkgparts}};
2322     %opt      = %{$_[0]};
2323   }else{
2324     @pkgparts = @_;
2325   }
2326   grep { $_->suspend(%opt) }
2327     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2328       $self->unsuspended_pkgs;
2329 }
2330
2331 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2332
2333 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2334 given PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref
2335 instead of a list of pkgparts; the hashref has the following keys:
2336
2337 =over 4
2338
2339 =item pkgparts - listref of pkgparts
2340
2341 =item (other options are passed to the suspend method)
2342
2343 =back
2344
2345 Returns a list: an empty list on success or a list of errors.
2346
2347 =cut
2348
2349 sub suspend_unless_pkgpart {
2350   my $self = shift;
2351   my (@pkgparts, %opt);
2352   if (ref($_[0]) eq 'HASH'){
2353     @pkgparts = @{$_[0]{pkgparts}};
2354     %opt      = %{$_[0]};
2355   }else{
2356     @pkgparts = @_;
2357   }
2358   grep { $_->suspend(%opt) }
2359     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2360       $self->unsuspended_pkgs;
2361 }
2362
2363 =item cancel [ OPTION => VALUE ... ]
2364
2365 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2366 The cancellation time will be now.
2367
2368 =back
2369
2370 Always returns a list: an empty list on success or a list of errors.
2371
2372 =cut
2373
2374 sub cancel {
2375   my $self = shift;
2376   my %opt = @_;
2377   warn "$me cancel called on customer ". $self->custnum. " with options ".
2378        join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2379     if $DEBUG;
2380   my @pkgs = $self->ncancelled_pkgs;
2381
2382   $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2383 }
2384
2385 =item cancel_pkgs OPTIONS
2386
2387 Cancels a specified list of packages. OPTIONS can include:
2388
2389 =over 4
2390
2391 =item cust_pkg - an arrayref of the packages. Required.
2392
2393 =item time - the cancellation time, used to calculate final bills and
2394 unused-time credits if any. Will be passed through to the bill() and
2395 FS::cust_pkg::cancel() methods.
2396
2397 =item quiet - can be set true to supress email cancellation notices.
2398
2399 =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.
2400
2401 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2402 for the individual packages, parallel to the C<cust_pkg> argument. The
2403 reason and reason_otaker arguments will be taken from those objects.
2404
2405 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2406
2407 =item nobill - can be set true to skip billing if it might otherwise be done.
2408
2409 =cut
2410
2411 sub cancel_pkgs {
2412   my( $self, %opt ) = @_;
2413
2414   my $oldAutoCommit = $FS::UID::AutoCommit;
2415   local $FS::UID::AutoCommit = 0;
2416
2417   return ( 'access denied' )
2418     unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2419
2420   if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2421
2422     #should try decryption (we might have the private key)
2423     # and if not maybe queue a job for the server that does?
2424     return ( "Can't (yet) ban encrypted credit cards" )
2425       if $self->is_encrypted($self->payinfo);
2426
2427     my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2428     my $error = $ban->insert;
2429     if ($error) {
2430       dbh->rollback if $oldAutoCommit;
2431       return ( $error );
2432     }
2433
2434   }
2435
2436   my @pkgs = @{ delete $opt{'cust_pkg'} };
2437   my $cancel_time = $opt{'time'} || time;
2438
2439   # bill all packages first, so we don't lose usage, service counts for
2440   # bulk billing, etc.
2441   if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2442     $opt{nobill} = 1;
2443     my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2444                              'cancel'   => 1,
2445                              'time'     => $cancel_time );
2446     if ($error) {
2447       warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2448       dbh->rollback if $oldAutoCommit;
2449       return ( "Error billing during cancellation: $error" );
2450     }
2451   }
2452
2453   my @errors;
2454   # now cancel all services, the same way we would for individual packages
2455   my @cust_svc = map { $_->cust_svc } @pkgs;
2456   my @sorted_cust_svc =
2457     map  { $_->[0] }
2458     sort { $a->[1] <=> $b->[1] }
2459     map  { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2460   ;
2461   warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2462     $self->custnum."\n"
2463     if $DEBUG;
2464   foreach my $cust_svc (@sorted_cust_svc) {
2465     my $part_svc = $cust_svc->part_svc;
2466     next if ( defined($part_svc) and $part_svc->preserve );
2467     my $error = $cust_svc->cancel; # immediate cancel, no date option
2468     push @errors, $error if $error;
2469   }
2470   if (@errors) {
2471     dbh->rollback if $oldAutoCommit;
2472     return @errors;
2473   }
2474
2475   warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2476     $self->custnum. "\n"
2477     if $DEBUG;
2478
2479   my @cprs;
2480   if ($opt{'cust_pkg_reason'}) {
2481     @cprs = @{ delete $opt{'cust_pkg_reason'} };
2482   }
2483   foreach (@pkgs) {
2484     my %lopt = %opt;
2485     if (@cprs) {
2486       my $cpr = shift @cprs;
2487       $lopt{'reason'}        = $cpr->reasonnum;
2488       $lopt{'reason_otaker'} = $cpr->otaker;
2489     }
2490     my $error = $_->cancel(%lopt);
2491     push @errors, 'pkgnum '.$_->pkgnum.': '.$error if $error;
2492   }
2493
2494   if (@errors) {
2495     dbh->rollback if $oldAutoCommit;
2496     return @errors;
2497   }
2498
2499   return;
2500 }
2501
2502 sub _banned_pay_hashref {
2503   my $self = shift;
2504
2505   my %payby2ban = (
2506     'CARD' => 'CARD',
2507     'DCRD' => 'CARD',
2508     'CHEK' => 'CHEK',
2509     'DCHK' => 'CHEK'
2510   );
2511
2512   {
2513     'payby'   => $payby2ban{$self->payby},
2514     'payinfo' => $self->payinfo,
2515     #don't ever *search* on reason! #'reason'  =>
2516   };
2517 }
2518
2519 sub _new_banned_pay_hashref {
2520   my $self = shift;
2521   my $hr = $self->_banned_pay_hashref;
2522   $hr->{payinfo} = md5_base64($hr->{payinfo});
2523   $hr;
2524 }
2525
2526 =item notes
2527
2528 Returns all notes (see L<FS::cust_main_note>) for this customer.
2529
2530 =cut
2531
2532 sub notes {
2533   my($self,$orderby_classnum) = (shift,shift);
2534   my $orderby = "sticky DESC, _date DESC";
2535   $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2536   qsearch( 'cust_main_note',
2537            { 'custnum' => $self->custnum },
2538            '',
2539            "ORDER BY $orderby",
2540          );
2541 }
2542
2543 =item agent
2544
2545 Returns the agent (see L<FS::agent>) for this customer.
2546
2547 =cut
2548
2549 sub agent {
2550   my $self = shift;
2551   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2552 }
2553
2554 =item agent_name
2555
2556 Returns the agent name (see L<FS::agent>) for this customer.
2557
2558 =cut
2559
2560 sub agent_name {
2561   my $self = shift;
2562   $self->agent->agent;
2563 }
2564
2565 =item cust_tag
2566
2567 Returns any tags associated with this customer, as FS::cust_tag objects,
2568 or an empty list if there are no tags.
2569
2570 =cut
2571
2572 sub cust_tag {
2573   my $self = shift;
2574   qsearch('cust_tag', { 'custnum' => $self->custnum } );
2575 }
2576
2577 =item part_tag
2578
2579 Returns any tags associated with this customer, as FS::part_tag objects,
2580 or an empty list if there are no tags.
2581
2582 =cut
2583
2584 sub part_tag {
2585   my $self = shift;
2586   map $_->part_tag, $self->cust_tag; 
2587 }
2588
2589
2590 =item cust_class
2591
2592 Returns the customer class, as an FS::cust_class object, or the empty string
2593 if there is no customer class.
2594
2595 =cut
2596
2597 sub cust_class {
2598   my $self = shift;
2599   if ( $self->classnum ) {
2600     qsearchs('cust_class', { 'classnum' => $self->classnum } );
2601   } else {
2602     return '';
2603   } 
2604 }
2605
2606 =item categoryname 
2607
2608 Returns the customer category name, or the empty string if there is no customer
2609 category.
2610
2611 =cut
2612
2613 sub categoryname {
2614   my $self = shift;
2615   my $cust_class = $self->cust_class;
2616   $cust_class
2617     ? $cust_class->categoryname
2618     : '';
2619 }
2620
2621 =item classname 
2622
2623 Returns the customer class name, or the empty string if there is no customer
2624 class.
2625
2626 =cut
2627
2628 sub classname {
2629   my $self = shift;
2630   my $cust_class = $self->cust_class;
2631   $cust_class
2632     ? $cust_class->classname
2633     : '';
2634 }
2635
2636 =item BILLING METHODS
2637
2638 Documentation on billing methods has been moved to
2639 L<FS::cust_main::Billing>.
2640
2641 =item REALTIME BILLING METHODS
2642
2643 Documentation on realtime billing methods has been moved to
2644 L<FS::cust_main::Billing_Realtime>.
2645
2646 =item remove_cvv
2647
2648 Removes the I<paycvv> field from the database directly.
2649
2650 If there is an error, returns the error, otherwise returns false.
2651
2652 =cut
2653
2654 sub remove_cvv {
2655   my $self = shift;
2656   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2657     or return dbh->errstr;
2658   $sth->execute($self->custnum)
2659     or return $sth->errstr;
2660   $self->paycvv('');
2661   '';
2662 }
2663
2664 =item batch_card OPTION => VALUE...
2665
2666 Adds a payment for this invoice to the pending credit card batch (see
2667 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2668 runs the payment using a realtime gateway.
2669
2670 Options may include:
2671
2672 B<amount>: the amount to be paid; defaults to the customer's balance minus
2673 any payments in transit.
2674
2675 B<payby>: the payment method; defaults to cust_main.payby
2676
2677 B<realtime>: runs this as a realtime payment instead of adding it to a 
2678 batch.  Deprecated.
2679
2680 B<invnum>: sets cust_pay_batch.invnum.
2681
2682 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets 
2683 the billing address for the payment; defaults to the customer's billing
2684 location.
2685
2686 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2687 date, and name; defaults to those fields in cust_main.
2688
2689 =cut
2690
2691 sub batch_card {
2692   my ($self, %options) = @_;
2693
2694   my $amount;
2695   if (exists($options{amount})) {
2696     $amount = $options{amount};
2697   }else{
2698     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2699   }
2700   if ($amount <= 0) {
2701     warn(sprintf("Customer balance %.2f - in transit amount %.2f is <= 0.\n",
2702         $self->balance,
2703         $self->in_transit_payments
2704     ));
2705     return;
2706   }
2707   
2708   my $invnum = delete $options{invnum};
2709   my $payby = $options{payby} || $self->payby;  #still dubious
2710
2711   if ($options{'realtime'}) {
2712     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2713                                 $amount,
2714                                 %options,
2715                               );
2716   }
2717
2718   my $oldAutoCommit = $FS::UID::AutoCommit;
2719   local $FS::UID::AutoCommit = 0;
2720   my $dbh = dbh;
2721
2722   #this needs to handle mysql as well as Pg, like svc_acct.pm
2723   #(make it into a common function if folks need to do batching with mysql)
2724   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2725     or return "Cannot lock pay_batch: " . $dbh->errstr;
2726
2727   my %pay_batch = (
2728     'status' => 'O',
2729     'payby'  => FS::payby->payby2payment($payby),
2730   );
2731   $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2732
2733   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2734
2735   unless ( $pay_batch ) {
2736     $pay_batch = new FS::pay_batch \%pay_batch;
2737     my $error = $pay_batch->insert;
2738     if ( $error ) {
2739       $dbh->rollback if $oldAutoCommit;
2740       die "error creating new batch: $error\n";
2741     }
2742   }
2743
2744   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2745       'batchnum' => $pay_batch->batchnum,
2746       'custnum'  => $self->custnum,
2747   } );
2748
2749   foreach (qw( address1 address2 city state zip country latitude longitude
2750                payby payinfo paydate payname ))
2751   {
2752     $options{$_} = '' unless exists($options{$_});
2753   }
2754
2755   my $loc = $self->bill_location;
2756
2757   my $cust_pay_batch = new FS::cust_pay_batch ( {
2758     'batchnum' => $pay_batch->batchnum,
2759     'invnum'   => $invnum || 0,                    # is there a better value?
2760                                                    # this field should be
2761                                                    # removed...
2762                                                    # cust_bill_pay_batch now
2763     'custnum'  => $self->custnum,
2764     'last'     => $self->getfield('last'),
2765     'first'    => $self->getfield('first'),
2766     'address1' => $options{address1} || $loc->address1,
2767     'address2' => $options{address2} || $loc->address2,
2768     'city'     => $options{city}     || $loc->city,
2769     'state'    => $options{state}    || $loc->state,
2770     'zip'      => $options{zip}      || $loc->zip,
2771     'country'  => $options{country}  || $loc->country,
2772     'payby'    => $options{payby}    || $self->payby,
2773     'payinfo'  => $options{payinfo}  || $self->payinfo,
2774     'exp'      => $options{paydate}  || $self->paydate,
2775     'payname'  => $options{payname}  || $self->payname,
2776     'amount'   => $amount,                         # consolidating
2777   } );
2778   
2779   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2780     if $old_cust_pay_batch;
2781
2782   my $error;
2783   if ($old_cust_pay_batch) {
2784     $error = $cust_pay_batch->replace($old_cust_pay_batch)
2785   } else {
2786     $error = $cust_pay_batch->insert;
2787   }
2788
2789   if ( $error ) {
2790     $dbh->rollback if $oldAutoCommit;
2791     die $error;
2792   }
2793
2794   my $unapplied =   $self->total_unapplied_credits
2795                   + $self->total_unapplied_payments
2796                   + $self->in_transit_payments;
2797   foreach my $cust_bill ($self->open_cust_bill) {
2798     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2799     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2800       'invnum' => $cust_bill->invnum,
2801       'paybatchnum' => $cust_pay_batch->paybatchnum,
2802       'amount' => $cust_bill->owed,
2803       '_date' => time,
2804     };
2805     if ($unapplied >= $cust_bill_pay_batch->amount){
2806       $unapplied -= $cust_bill_pay_batch->amount;
2807       next;
2808     }else{
2809       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
2810                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
2811     }
2812     $error = $cust_bill_pay_batch->insert;
2813     if ( $error ) {
2814       $dbh->rollback if $oldAutoCommit;
2815       die $error;
2816     }
2817   }
2818
2819   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2820   '';
2821 }
2822
2823 =item total_owed
2824
2825 Returns the total owed for this customer on all invoices
2826 (see L<FS::cust_bill/owed>).
2827
2828 =cut
2829
2830 sub total_owed {
2831   my $self = shift;
2832   $self->total_owed_date(2145859200); #12/31/2037
2833 }
2834
2835 =item total_owed_date TIME
2836
2837 Returns the total owed for this customer on all invoices with date earlier than
2838 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2839 see L<Time::Local> and L<Date::Parse> for conversion functions.
2840
2841 =cut
2842
2843 sub total_owed_date {
2844   my $self = shift;
2845   my $time = shift;
2846
2847   my $custnum = $self->custnum;
2848
2849   my $owed_sql = FS::cust_bill->owed_sql;
2850
2851   my $sql = "
2852     SELECT SUM($owed_sql) FROM cust_bill
2853       WHERE custnum = $custnum
2854         AND _date <= $time
2855   ";
2856
2857   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2858
2859 }
2860
2861 =item total_owed_pkgnum PKGNUM
2862
2863 Returns the total owed on all invoices for this customer's specific package
2864 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2865
2866 =cut
2867
2868 sub total_owed_pkgnum {
2869   my( $self, $pkgnum ) = @_;
2870   $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2871 }
2872
2873 =item total_owed_date_pkgnum TIME PKGNUM
2874
2875 Returns the total owed for this customer's specific package when using
2876 experimental package balances on all invoices with date earlier than
2877 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2878 see L<Time::Local> and L<Date::Parse> for conversion functions.
2879
2880 =cut
2881
2882 sub total_owed_date_pkgnum {
2883   my( $self, $time, $pkgnum ) = @_;
2884
2885   my $total_bill = 0;
2886   foreach my $cust_bill (
2887     grep { $_->_date <= $time }
2888       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2889   ) {
2890     $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2891   }
2892   sprintf( "%.2f", $total_bill );
2893
2894 }
2895
2896 =item total_paid
2897
2898 Returns the total amount of all payments.
2899
2900 =cut
2901
2902 sub total_paid {
2903   my $self = shift;
2904   my $total = 0;
2905   $total += $_->paid foreach $self->cust_pay;
2906   sprintf( "%.2f", $total );
2907 }
2908
2909 =item total_unapplied_credits
2910
2911 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2912 customer.  See L<FS::cust_credit/credited>.
2913
2914 =item total_credited
2915
2916 Old name for total_unapplied_credits.  Don't use.
2917
2918 =cut
2919
2920 sub total_credited {
2921   #carp "total_credited deprecated, use total_unapplied_credits";
2922   shift->total_unapplied_credits(@_);
2923 }
2924
2925 sub total_unapplied_credits {
2926   my $self = shift;
2927
2928   my $custnum = $self->custnum;
2929
2930   my $unapplied_sql = FS::cust_credit->unapplied_sql;
2931
2932   my $sql = "
2933     SELECT SUM($unapplied_sql) FROM cust_credit
2934       WHERE custnum = $custnum
2935   ";
2936
2937   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2938
2939 }
2940
2941 =item total_unapplied_credits_pkgnum PKGNUM
2942
2943 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2944 customer.  See L<FS::cust_credit/credited>.
2945
2946 =cut
2947
2948 sub total_unapplied_credits_pkgnum {
2949   my( $self, $pkgnum ) = @_;
2950   my $total_credit = 0;
2951   $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2952   sprintf( "%.2f", $total_credit );
2953 }
2954
2955
2956 =item total_unapplied_payments
2957
2958 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2959 See L<FS::cust_pay/unapplied>.
2960
2961 =cut
2962
2963 sub total_unapplied_payments {
2964   my $self = shift;
2965
2966   my $custnum = $self->custnum;
2967
2968   my $unapplied_sql = FS::cust_pay->unapplied_sql;
2969
2970   my $sql = "
2971     SELECT SUM($unapplied_sql) FROM cust_pay
2972       WHERE custnum = $custnum
2973   ";
2974
2975   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2976
2977 }
2978
2979 =item total_unapplied_payments_pkgnum PKGNUM
2980
2981 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2982 specific package when using experimental package balances.  See
2983 L<FS::cust_pay/unapplied>.
2984
2985 =cut
2986
2987 sub total_unapplied_payments_pkgnum {
2988   my( $self, $pkgnum ) = @_;
2989   my $total_unapplied = 0;
2990   $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2991   sprintf( "%.2f", $total_unapplied );
2992 }
2993
2994
2995 =item total_unapplied_refunds
2996
2997 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2998 customer.  See L<FS::cust_refund/unapplied>.
2999
3000 =cut
3001
3002 sub total_unapplied_refunds {
3003   my $self = shift;
3004   my $custnum = $self->custnum;
3005
3006   my $unapplied_sql = FS::cust_refund->unapplied_sql;
3007
3008   my $sql = "
3009     SELECT SUM($unapplied_sql) FROM cust_refund
3010       WHERE custnum = $custnum
3011   ";
3012
3013   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
3014
3015 }
3016
3017 =item balance
3018
3019 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3020 total_unapplied_credits minus total_unapplied_payments).
3021
3022 =cut
3023
3024 sub balance {
3025   my $self = shift;
3026   $self->balance_date_range;
3027 }
3028
3029 =item balance_date TIME
3030
3031 Returns the balance for this customer, only considering invoices with date
3032 earlier than TIME (total_owed_date minus total_credited minus
3033 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
3034 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
3035 functions.
3036
3037 =cut
3038
3039 sub balance_date {
3040   my $self = shift;
3041   $self->balance_date_range(shift);
3042 }
3043
3044 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
3045
3046 Returns the balance for this customer, optionally considering invoices with
3047 date earlier than START_TIME, and not later than END_TIME
3048 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
3049
3050 Times are specified as SQL fragments or numeric
3051 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
3052 L<Date::Parse> for conversion functions.  The empty string can be passed
3053 to disable that time constraint completely.
3054
3055 Accepts the same options as L<balance_date_sql>:
3056
3057 =over 4
3058
3059 =item unapplied_date
3060
3061 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)
3062
3063 =item cutoff
3064
3065 An absolute cutoff time.  Payments, credits, and refunds I<applied> after this 
3066 time will be ignored.  Note that START_TIME and END_TIME only limit the date 
3067 range for invoices and I<unapplied> payments, credits, and refunds.
3068
3069 =back
3070
3071 =cut
3072
3073 sub balance_date_range {
3074   my $self = shift;
3075   my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
3076             ') FROM cust_main WHERE custnum='. $self->custnum;
3077   sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
3078 }
3079
3080 =item balance_pkgnum PKGNUM
3081
3082 Returns the balance for this customer's specific package when using
3083 experimental package balances (total_owed plus total_unrefunded, minus
3084 total_unapplied_credits minus total_unapplied_payments)
3085
3086 =cut
3087
3088 sub balance_pkgnum {
3089   my( $self, $pkgnum ) = @_;
3090
3091   sprintf( "%.2f",
3092       $self->total_owed_pkgnum($pkgnum)
3093 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
3094 #    + $self->total_unapplied_refunds_pkgnum($pkgnum)
3095     - $self->total_unapplied_credits_pkgnum($pkgnum)
3096     - $self->total_unapplied_payments_pkgnum($pkgnum)
3097   );
3098 }
3099
3100 =item in_transit_payments
3101
3102 Returns the total of requests for payments for this customer pending in 
3103 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
3104
3105 =cut
3106
3107 sub in_transit_payments {
3108   my $self = shift;
3109   my $in_transit_payments = 0;
3110   foreach my $pay_batch ( qsearch('pay_batch', {
3111     'status' => 'I',
3112   } ) ) {
3113     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3114       'batchnum' => $pay_batch->batchnum,
3115       'custnum' => $self->custnum,
3116       'status'  => '',
3117     } ) ) {
3118       $in_transit_payments += $cust_pay_batch->amount;
3119     }
3120   }
3121   sprintf( "%.2f", $in_transit_payments );
3122 }
3123
3124 =item payment_info
3125
3126 Returns a hash of useful information for making a payment.
3127
3128 =over 4
3129
3130 =item balance
3131
3132 Current balance.
3133
3134 =item payby
3135
3136 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3137 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3138 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3139
3140 =back
3141
3142 For credit card transactions:
3143
3144 =over 4
3145
3146 =item card_type 1
3147
3148 =item payname
3149
3150 Exact name on card
3151
3152 =back
3153
3154 For electronic check transactions:
3155
3156 =over 4
3157
3158 =item stateid_state
3159
3160 =back
3161
3162 =cut
3163
3164 sub payment_info {
3165   my $self = shift;
3166
3167   my %return = ();
3168
3169   $return{balance} = $self->balance;
3170
3171   $return{payname} = $self->payname
3172                      || ( $self->first. ' '. $self->get('last') );
3173
3174   $return{$_} = $self->bill_location->$_
3175     for qw(address1 address2 city state zip);
3176
3177   $return{payby} = $self->payby;
3178   $return{stateid_state} = $self->stateid_state;
3179
3180   if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3181     $return{card_type} = cardtype($self->payinfo);
3182     $return{payinfo} = $self->paymask;
3183
3184     @return{'month', 'year'} = $self->paydate_monthyear;
3185
3186   }
3187
3188   if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3189     my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3190     $return{payinfo1} = $payinfo1;
3191     $return{payinfo2} = $payinfo2;
3192     $return{paytype}  = $self->paytype;
3193     $return{paystate} = $self->paystate;
3194
3195   }
3196
3197   #doubleclick protection
3198   my $_date = time;
3199   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3200
3201   %return;
3202
3203 }
3204
3205 =item paydate_monthyear
3206
3207 Returns a two-element list consisting of the month and year of this customer's
3208 paydate (credit card expiration date for CARD customers)
3209
3210 =cut
3211
3212 sub paydate_monthyear {
3213   my $self = shift;
3214   if ( $self->paydate  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3215     ( $2, $1 );
3216   } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3217     ( $1, $3 );
3218   } else {
3219     ('', '');
3220   }
3221 }
3222
3223 =item paydate_epoch
3224
3225 Returns the exact time in seconds corresponding to the payment method 
3226 expiration date.  For CARD/DCRD customers this is the end of the month;
3227 for others (COMP is the only other payby that uses paydate) it's the start.
3228 Returns 0 if the paydate is empty or set to the far future.
3229
3230 =cut
3231
3232 sub paydate_epoch {
3233   my $self = shift;
3234   my ($month, $year) = $self->paydate_monthyear;
3235   return 0 if !$year or $year >= 2037;
3236   if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3237     $month++;
3238     if ( $month == 13 ) {
3239       $month = 1;
3240       $year++;
3241     }
3242     return timelocal(0,0,0,1,$month-1,$year) - 1;
3243   }
3244   else {
3245     return timelocal(0,0,0,1,$month-1,$year);
3246   }
3247 }
3248
3249 =item paydate_epoch_sql
3250
3251 Class method.  Returns an SQL expression to obtain the payment expiration date
3252 as a number of seconds.
3253
3254 =cut
3255
3256 # Special expiration date behavior for non-CARD/DCRD customers has been 
3257 # carefully preserved.  Do we really use that?
3258 sub paydate_epoch_sql {
3259   my $class = shift;
3260   my $table = shift || 'cust_main';
3261   my ($case1, $case2);
3262   if ( driver_name eq 'Pg' ) {
3263     $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3264     $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3265   }
3266   elsif ( lc(driver_name) eq 'mysql' ) {
3267     $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3268     $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3269   }
3270   else { return '' }
3271   return "CASE WHEN $table.payby IN('CARD','DCRD') 
3272   THEN ($case1)
3273   ELSE ($case2)
3274   END"
3275 }
3276
3277 =item tax_exemption TAXNAME
3278
3279 =cut
3280
3281 sub tax_exemption {
3282   my( $self, $taxname ) = @_;
3283
3284   qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3285                                      'taxname' => $taxname,
3286                                    },
3287           );
3288 }
3289
3290 =item cust_main_exemption
3291
3292 =cut
3293
3294 sub cust_main_exemption {
3295   my $self = shift;
3296   qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3297 }
3298
3299 =item invoicing_list [ ARRAYREF ]
3300
3301 If an arguement is given, sets these email addresses as invoice recipients
3302 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
3303 (except as warnings), so use check_invoicing_list first.
3304
3305 Returns a list of email addresses (with svcnum entries expanded).
3306
3307 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
3308 check it without disturbing anything by passing nothing.
3309
3310 This interface may change in the future.
3311
3312 =cut
3313
3314 sub invoicing_list {
3315   my( $self, $arrayref ) = @_;
3316
3317   if ( $arrayref ) {
3318     my @cust_main_invoice;
3319     if ( $self->custnum ) {
3320       @cust_main_invoice = 
3321         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3322     } else {
3323       @cust_main_invoice = ();
3324     }
3325     foreach my $cust_main_invoice ( @cust_main_invoice ) {
3326       #warn $cust_main_invoice->destnum;
3327       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3328         #warn $cust_main_invoice->destnum;
3329         my $error = $cust_main_invoice->delete;
3330         warn $error if $error;
3331       }
3332     }
3333     if ( $self->custnum ) {
3334       @cust_main_invoice = 
3335         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3336     } else {
3337       @cust_main_invoice = ();
3338     }
3339     my %seen = map { $_->address => 1 } @cust_main_invoice;
3340     foreach my $address ( @{$arrayref} ) {
3341       next if exists $seen{$address} && $seen{$address};
3342       $seen{$address} = 1;
3343       my $cust_main_invoice = new FS::cust_main_invoice ( {
3344         'custnum' => $self->custnum,
3345         'dest'    => $address,
3346       } );
3347       my $error = $cust_main_invoice->insert;
3348       warn $error if $error;
3349     }
3350   }
3351   
3352   if ( $self->custnum ) {
3353     map { $_->address }
3354       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3355   } else {
3356     ();
3357   }
3358
3359 }
3360
3361 =item check_invoicing_list ARRAYREF
3362
3363 Checks these arguements as valid input for the invoicing_list method.  If there
3364 is an error, returns the error, otherwise returns false.
3365
3366 =cut
3367
3368 sub check_invoicing_list {
3369   my( $self, $arrayref ) = @_;
3370
3371   foreach my $address ( @$arrayref ) {
3372
3373     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3374       return 'Can\'t add FAX invoice destination with a blank FAX number.';
3375     }
3376
3377     my $cust_main_invoice = new FS::cust_main_invoice ( {
3378       'custnum' => $self->custnum,
3379       'dest'    => $address,
3380     } );
3381     my $error = $self->custnum
3382                 ? $cust_main_invoice->check
3383                 : $cust_main_invoice->checkdest
3384     ;
3385     return $error if $error;
3386
3387   }
3388
3389   return "Email address required"
3390     if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3391     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3392
3393   '';
3394 }
3395
3396 =item set_default_invoicing_list
3397
3398 Sets the invoicing list to all accounts associated with this customer,
3399 overwriting any previous invoicing list.
3400
3401 =cut
3402
3403 sub set_default_invoicing_list {
3404   my $self = shift;
3405   $self->invoicing_list($self->all_emails);
3406 }
3407
3408 =item all_emails
3409
3410 Returns the email addresses of all accounts provisioned for this customer.
3411
3412 =cut
3413
3414 sub all_emails {
3415   my $self = shift;
3416   my %list;
3417   foreach my $cust_pkg ( $self->all_pkgs ) {
3418     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3419     my @svc_acct =
3420       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3421         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3422           @cust_svc;
3423     $list{$_}=1 foreach map { $_->email } @svc_acct;
3424   }
3425   keys %list;
3426 }
3427
3428 =item invoicing_list_addpost
3429
3430 Adds postal invoicing to this customer.  If this customer is already configured
3431 to receive postal invoices, does nothing.
3432
3433 =cut
3434
3435 sub invoicing_list_addpost {
3436   my $self = shift;
3437   return if grep { $_ eq 'POST' } $self->invoicing_list;
3438   my @invoicing_list = $self->invoicing_list;
3439   push @invoicing_list, 'POST';
3440   $self->invoicing_list(\@invoicing_list);
3441 }
3442
3443 =item invoicing_list_emailonly
3444
3445 Returns the list of email invoice recipients (invoicing_list without non-email
3446 destinations such as POST and FAX).
3447
3448 =cut
3449
3450 sub invoicing_list_emailonly {
3451   my $self = shift;
3452   warn "$me invoicing_list_emailonly called"
3453     if $DEBUG;
3454   grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3455 }
3456
3457 =item invoicing_list_emailonly_scalar
3458
3459 Returns the list of email invoice recipients (invoicing_list without non-email
3460 destinations such as POST and FAX) as a comma-separated scalar.
3461
3462 =cut
3463
3464 sub invoicing_list_emailonly_scalar {
3465   my $self = shift;
3466   warn "$me invoicing_list_emailonly_scalar called"
3467     if $DEBUG;
3468   join(', ', $self->invoicing_list_emailonly);
3469 }
3470
3471 =item contact_list [ CLASSNUM, ... ]
3472
3473 Returns a list of contacts (L<FS::contact> objects) for the customer. If
3474 a list of contact classnums is given, returns only contacts in those
3475 classes. If '0' is given, also returns contacts with no class.
3476
3477 If no arguments are given, returns all contacts for the customer.
3478
3479 =cut
3480
3481 sub contact_list {
3482   my $self = shift;
3483   my $search = {
3484     table       => 'contact',
3485     select      => 'contact.*',
3486     extra_sql   => ' WHERE contact.custnum = '.$self->custnum,
3487   };
3488
3489   my @orwhere;
3490   my @classnums;
3491   foreach (@_) {
3492     if ( $_ eq '0' ) {
3493       push @orwhere, 'contact.classnum is null';
3494     } elsif ( /^\d+$/ ) {
3495       push @classnums, $_;
3496     } else {
3497       die "bad classnum argument '$_'";
3498     }
3499   }
3500
3501   if (@classnums) {
3502     push @orwhere, 'contact.classnum IN ('.join(',', @classnums).')';
3503   }
3504   if (@orwhere) {
3505     $search->{extra_sql} .= ' AND (' .
3506                             join(' OR ', map "( $_ )", @orwhere) .
3507                             ')';
3508   }
3509
3510   qsearch($search);
3511 }
3512
3513 =item contact_list_email [ CLASSNUM, ... ]
3514
3515 Same as L</contact_list>, but returns email destinations instead of contact
3516 objects. Also accepts 'invoice' as an argument, in which case this will also
3517 return the invoice email address if any.
3518
3519 =cut
3520
3521 sub contact_list_email {
3522   my $self = shift;
3523   my @classnums;
3524   my $and_invoice;
3525   foreach (@_) {
3526     if (/^invoice$/) {
3527       $and_invoice = 1;
3528     } else {
3529       push @classnums, $_;
3530     }
3531   }
3532   my %emails;
3533   # if the only argument passed was 'invoice' then no classnums are
3534   # intended, so skip this.
3535   if ( @classnums ) {
3536     my @contacts = $self->contact_list(@classnums);
3537     foreach my $contact (@contacts) {
3538       foreach my $contact_email ($contact->contact_email) {
3539         # unlike on 4.x, we have a separate list of invoice email
3540         # destinations.
3541         # make sure they're not redundant with contact emails
3542         my $dest = $contact->firstlast . ' <' . $contact_email->emailaddress . '>';
3543         $emails{ $contact_email->emailaddress } = $dest;
3544       }
3545     }
3546   }
3547   if ( $and_invoice ) {
3548     foreach my $email ($self->invoicing_list_emailonly) {
3549       my $dest = $self->name_short . ' <' . $email . '>';
3550       $emails{ $email } ||= $dest;
3551     }
3552   }
3553   values %emails;
3554 }
3555
3556 =item referral_custnum_cust_main
3557
3558 Returns the customer who referred this customer (or the empty string, if
3559 this customer was not referred).
3560
3561 Note the difference with referral_cust_main method: This method,
3562 referral_custnum_cust_main returns the single customer (if any) who referred
3563 this customer, while referral_cust_main returns an array of customers referred
3564 BY this customer.
3565
3566 =cut
3567
3568 sub referral_custnum_cust_main {
3569   my $self = shift;
3570   return '' unless $self->referral_custnum;
3571   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3572 }
3573
3574 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3575
3576 Returns an array of customers referred by this customer (referral_custnum set
3577 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
3578 customers referred by customers referred by this customer and so on, inclusive.
3579 The default behavior is DEPTH 1 (no recursion).
3580
3581 Note the difference with referral_custnum_cust_main method: This method,
3582 referral_cust_main, returns an array of customers referred BY this customer,
3583 while referral_custnum_cust_main returns the single customer (if any) who
3584 referred this customer.
3585
3586 =cut
3587
3588 sub referral_cust_main {
3589   my $self = shift;
3590   my $depth = @_ ? shift : 1;
3591   my $exclude = @_ ? shift : {};
3592
3593   my @cust_main =
3594     map { $exclude->{$_->custnum}++; $_; }
3595       grep { ! $exclude->{ $_->custnum } }
3596         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3597
3598   if ( $depth > 1 ) {
3599     push @cust_main,
3600       map { $_->referral_cust_main($depth-1, $exclude) }
3601         @cust_main;
3602   }
3603
3604   @cust_main;
3605 }
3606
3607 =item referral_cust_main_ncancelled
3608
3609 Same as referral_cust_main, except only returns customers with uncancelled
3610 packages.
3611
3612 =cut
3613
3614 sub referral_cust_main_ncancelled {
3615   my $self = shift;
3616   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3617 }
3618
3619 =item referral_cust_pkg [ DEPTH ]
3620
3621 Like referral_cust_main, except returns a flat list of all unsuspended (and
3622 uncancelled) packages for each customer.  The number of items in this list may
3623 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3624
3625 =cut
3626
3627 sub referral_cust_pkg {
3628   my $self = shift;
3629   my $depth = @_ ? shift : 1;
3630
3631   map { $_->unsuspended_pkgs }
3632     grep { $_->unsuspended_pkgs }
3633       $self->referral_cust_main($depth);
3634 }
3635
3636 =item referring_cust_main
3637
3638 Returns the single cust_main record for the customer who referred this customer
3639 (referral_custnum), or false.
3640
3641 =cut
3642
3643 sub referring_cust_main {
3644   my $self = shift;
3645   return '' unless $self->referral_custnum;
3646   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3647 }
3648
3649 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3650
3651 Applies a credit to this customer.  If there is an error, returns the error,
3652 otherwise returns false.
3653
3654 REASON can be a text string, an FS::reason object, or a scalar reference to
3655 a reasonnum.  If a text string, it will be automatically inserted as a new
3656 reason, and a 'reason_type' option must be passed to indicate the
3657 FS::reason_type for the new reason.
3658
3659 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3660 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3661 I<commission_pkgnum>.
3662
3663 Any other options are passed to FS::cust_credit::insert.
3664
3665 =cut
3666
3667 sub credit {
3668   my( $self, $amount, $reason, %options ) = @_;
3669
3670   my $cust_credit = new FS::cust_credit {
3671     'custnum' => $self->custnum,
3672     'amount'  => $amount,
3673   };
3674
3675   if ( ref($reason) ) {
3676
3677     if ( ref($reason) eq 'SCALAR' ) {
3678       $cust_credit->reasonnum( $$reason );
3679     } else {
3680       $cust_credit->reasonnum( $reason->reasonnum );
3681     }
3682
3683   } else {
3684     $cust_credit->set('reason', $reason)
3685   }
3686
3687   $cust_credit->$_( delete $options{$_} )
3688     foreach grep exists($options{$_}),
3689               qw( addlinfo eventnum ),
3690               map "commission_$_", qw( agentnum salesnum pkgnum );
3691
3692   $cust_credit->insert(%options);
3693
3694 }
3695
3696 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3697
3698 Creates a one-time charge for this customer.  If there is an error, returns
3699 the error, otherwise returns false.
3700
3701 New-style, with a hashref of options:
3702
3703   my $error = $cust_main->charge(
3704                                   {
3705                                     'amount'     => 54.32,
3706                                     'quantity'   => 1,
3707                                     'start_date' => str2time('7/4/2009'),
3708                                     'pkg'        => 'Description',
3709                                     'comment'    => 'Comment',
3710                                     'additional' => [], #extra invoice detail
3711                                     'classnum'   => 1,  #pkg_class
3712
3713                                     'setuptax'   => '', # or 'Y' for tax exempt
3714
3715                                     'locationnum'=> 1234, # optional
3716
3717                                     #internal taxation
3718                                     'taxclass'   => 'Tax class',
3719
3720                                     #vendor taxation
3721                                     'taxproduct' => 2,  #part_pkg_taxproduct
3722                                     'override'   => {}, #XXX describe
3723
3724                                     #will be filled in with the new object
3725                                     'cust_pkg_ref' => \$cust_pkg,
3726
3727                                     #generate an invoice immediately
3728                                     'bill_now' => 0,
3729                                     'invoice_terms' => '', #with these terms
3730                                   }
3731                                 );
3732
3733 Old-style:
3734
3735   my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3736
3737 =cut
3738
3739 #super false laziness w/quotation::charge
3740 sub charge {
3741   my $self = shift;
3742   my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3743   my ( $pkg, $comment, $additional );
3744   my ( $setuptax, $taxclass );   #internal taxes
3745   my ( $taxproduct, $override ); #vendor (CCH) taxes
3746   my $no_auto = '';
3747   my $separate_bill = '';
3748   my $cust_pkg_ref = '';
3749   my ( $bill_now, $invoice_terms ) = ( 0, '' );
3750   my $locationnum;
3751   if ( ref( $_[0] ) ) {
3752     $amount     = $_[0]->{amount};
3753     $setup_cost = $_[0]->{setup_cost};
3754     $quantity   = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3755     $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3756     $no_auto    = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3757     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3758     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
3759                                            : '$'. sprintf("%.2f",$amount);
3760     $setuptax   = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3761     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3762     $classnum   = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3763     $additional = $_[0]->{additional} || [];
3764     $taxproduct = $_[0]->{taxproductnum};
3765     $override   = { '' => $_[0]->{tax_override} };
3766     $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3767     $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3768     $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3769     $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3770     $separate_bill = $_[0]->{separate_bill} || '';
3771   } else { # yuck
3772     $amount     = shift;
3773     $setup_cost = '';
3774     $quantity   = 1;
3775     $start_date = '';
3776     $pkg        = @_ ? shift : 'One-time charge';
3777     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
3778     $setuptax   = '';
3779     $taxclass   = @_ ? shift : '';
3780     $additional = [];
3781   }
3782
3783   local $SIG{HUP} = 'IGNORE';
3784   local $SIG{INT} = 'IGNORE';
3785   local $SIG{QUIT} = 'IGNORE';
3786   local $SIG{TERM} = 'IGNORE';
3787   local $SIG{TSTP} = 'IGNORE';
3788   local $SIG{PIPE} = 'IGNORE';
3789
3790   my $oldAutoCommit = $FS::UID::AutoCommit;
3791   local $FS::UID::AutoCommit = 0;
3792   my $dbh = dbh;
3793
3794   my $part_pkg = new FS::part_pkg ( {
3795     'pkg'           => $pkg,
3796     'comment'       => $comment,
3797     'plan'          => 'flat',
3798     'freq'          => 0,
3799     'disabled'      => 'Y',
3800     'classnum'      => ( $classnum ? $classnum : '' ),
3801     'setuptax'      => $setuptax,
3802     'taxclass'      => $taxclass,
3803     'taxproductnum' => $taxproduct,
3804     'setup_cost'    => $setup_cost,
3805   } );
3806
3807   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3808                         ( 0 .. @$additional - 1 )
3809                   ),
3810                   'additional_count' => scalar(@$additional),
3811                   'setup_fee' => $amount,
3812                 );
3813
3814   my $error = $part_pkg->insert( options       => \%options,
3815                                  tax_overrides => $override,
3816                                );
3817   if ( $error ) {
3818     $dbh->rollback if $oldAutoCommit;
3819     return $error;
3820   }
3821
3822   my $pkgpart = $part_pkg->pkgpart;
3823   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3824   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3825     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3826     $error = $type_pkgs->insert;
3827     if ( $error ) {
3828       $dbh->rollback if $oldAutoCommit;
3829       return $error;
3830     }
3831   }
3832
3833   my $cust_pkg = new FS::cust_pkg ( {
3834     'custnum'    => $self->custnum,
3835     'pkgpart'    => $pkgpart,
3836     'quantity'   => $quantity,
3837     'start_date' => $start_date,
3838     'no_auto'    => $no_auto,
3839     'separate_bill' => $separate_bill,
3840     'locationnum'=> $locationnum,
3841   } );
3842
3843   $error = $cust_pkg->insert;
3844   if ( $error ) {
3845     $dbh->rollback if $oldAutoCommit;
3846     return $error;
3847   } elsif ( $cust_pkg_ref ) {
3848     ${$cust_pkg_ref} = $cust_pkg;
3849   }
3850
3851   if ( $bill_now ) {
3852     my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3853                              'pkg_list'      => [ $cust_pkg ],
3854                            );
3855     if ( $error ) {
3856       $dbh->rollback if $oldAutoCommit;
3857       return $error;
3858     }   
3859   }
3860
3861   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3862   return '';
3863
3864 }
3865
3866 #=item charge_postal_fee
3867 #
3868 #Applies a one time charge this customer.  If there is an error,
3869 #returns the error, returns the cust_pkg charge object or false
3870 #if there was no charge.
3871 #
3872 #=cut
3873 #
3874 # This should be a customer event.  For that to work requires that bill
3875 # also be a customer event.
3876
3877 sub charge_postal_fee {
3878   my $self = shift;
3879
3880   my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3881   return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3882
3883   my $cust_pkg = new FS::cust_pkg ( {
3884     'custnum'  => $self->custnum,
3885     'pkgpart'  => $pkgpart,
3886     'quantity' => 1,
3887   } );
3888
3889   my $error = $cust_pkg->insert;
3890   $error ? $error : $cust_pkg;
3891 }
3892
3893 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3894
3895 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3896
3897 Optionally, a list or hashref of additional arguments to the qsearch call can
3898 be passed.
3899
3900 =cut
3901
3902 sub cust_bill {
3903   my $self = shift;
3904   my $opt = ref($_[0]) ? shift : { @_ };
3905
3906   #return $self->num_cust_bill unless wantarray || keys %$opt;
3907
3908   $opt->{'table'} = 'cust_bill';
3909   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3910   $opt->{'hashref'}{'custnum'} = $self->custnum;
3911   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3912
3913   map { $_ } #behavior of sort undefined in scalar context
3914     sort { $a->_date <=> $b->_date }
3915       qsearch($opt);
3916 }
3917
3918 =item open_cust_bill
3919
3920 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3921 customer.
3922
3923 =cut
3924
3925 sub open_cust_bill {
3926   my $self = shift;
3927
3928   $self->cust_bill(
3929     'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3930     #@_
3931   );
3932
3933 }
3934
3935 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3936
3937 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3938
3939 =cut
3940
3941 sub legacy_cust_bill {
3942   my $self = shift;
3943
3944   #return $self->num_legacy_cust_bill unless wantarray;
3945
3946   map { $_ } #behavior of sort undefined in scalar context
3947     sort { $a->_date <=> $b->_date }
3948       qsearch({ 'table'    => 'legacy_cust_bill',
3949                 'hashref'  => { 'custnum' => $self->custnum, },
3950                 'order_by' => 'ORDER BY _date ASC',
3951              });
3952 }
3953
3954 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3955
3956 Returns all the statements (see L<FS::cust_statement>) for this customer.
3957
3958 Optionally, a list or hashref of additional arguments to the qsearch call can
3959 be passed.
3960
3961 =cut
3962
3963 =item cust_bill_void
3964
3965 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3966
3967 =cut
3968
3969 sub cust_bill_void {
3970   my $self = shift;
3971
3972   map { $_ } #return $self->num_cust_bill_void unless wantarray;
3973   sort { $a->_date <=> $b->_date }
3974     qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3975 }
3976
3977 sub cust_statement {
3978   my $self = shift;
3979   my $opt = ref($_[0]) ? shift : { @_ };
3980
3981   #return $self->num_cust_statement unless wantarray || keys %$opt;
3982
3983   $opt->{'table'} = 'cust_statement';
3984   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3985   $opt->{'hashref'}{'custnum'} = $self->custnum;
3986   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3987
3988   map { $_ } #behavior of sort undefined in scalar context
3989     sort { $a->_date <=> $b->_date }
3990       qsearch($opt);
3991 }
3992
3993 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3994
3995 Returns all services of type SVCDB (such as 'svc_acct') for this customer.  
3996
3997 Optionally, a list or hashref of additional arguments to the qsearch call can 
3998 be passed following the SVCDB.
3999
4000 =cut
4001
4002 sub svc_x {
4003   my $self = shift;
4004   my $svcdb = shift;
4005   if ( ! $svcdb =~ /^svc_\w+$/ ) {
4006     warn "$me svc_x requires a svcdb";
4007     return;
4008   }
4009   my $opt = ref($_[0]) ? shift : { @_ };
4010
4011   $opt->{'table'} = $svcdb;
4012   $opt->{'addl_from'} = 
4013     'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
4014     ($opt->{'addl_from'} || '');
4015
4016   my $custnum = $self->custnum;
4017   $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
4018   my $where = "cust_pkg.custnum = $custnum";
4019
4020   my $extra_sql = $opt->{'extra_sql'} || '';
4021   if ( keys %{ $opt->{'hashref'} } ) {
4022     $extra_sql = " AND $where $extra_sql";
4023   }
4024   else {
4025     if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
4026       $extra_sql = "WHERE $where AND $1";
4027     }
4028     else {
4029       $extra_sql = "WHERE $where $extra_sql";
4030     }
4031   }
4032   $opt->{'extra_sql'} = $extra_sql;
4033
4034   qsearch($opt);
4035 }
4036
4037 # required for use as an eventtable; 
4038 sub svc_acct {
4039   my $self = shift;
4040   $self->svc_x('svc_acct', @_);
4041 }
4042
4043 =item cust_credit
4044
4045 Returns all the credits (see L<FS::cust_credit>) for this customer.
4046
4047 =cut
4048
4049 sub cust_credit {
4050   my $self = shift;
4051   map { $_ } #return $self->num_cust_credit unless wantarray;
4052   sort { $a->_date <=> $b->_date }
4053     qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4054 }
4055
4056 =item cust_credit_pkgnum
4057
4058 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
4059 package when using experimental package balances.
4060
4061 =cut
4062
4063 sub cust_credit_pkgnum {
4064   my( $self, $pkgnum ) = @_;
4065   map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
4066   sort { $a->_date <=> $b->_date }
4067     qsearch( 'cust_credit', { 'custnum' => $self->custnum,
4068                               'pkgnum'  => $pkgnum,
4069                             }
4070     );
4071 }
4072
4073 =item cust_credit_void
4074
4075 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
4076
4077 =cut
4078
4079 sub cust_credit_void {
4080   my $self = shift;
4081   map { $_ }
4082   sort { $a->_date <=> $b->_date }
4083     qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
4084 }
4085
4086 =item cust_pay
4087
4088 Returns all the payments (see L<FS::cust_pay>) for this customer.
4089
4090 =cut
4091
4092 sub cust_pay {
4093   my $self = shift;
4094   my $opt = ref($_[0]) ? shift : { @_ };
4095
4096   return $self->num_cust_pay unless wantarray || keys %$opt;
4097
4098   $opt->{'table'} = 'cust_pay';
4099   $opt->{'hashref'}{'custnum'} = $self->custnum;
4100
4101   map { $_ } #behavior of sort undefined in scalar context
4102     sort { $a->_date <=> $b->_date }
4103       qsearch($opt);
4104
4105 }
4106
4107 =item num_cust_pay
4108
4109 Returns the number of payments (see L<FS::cust_pay>) for this customer.  Also
4110 called automatically when the cust_pay method is used in a scalar context.
4111
4112 =cut
4113
4114 sub num_cust_pay {
4115   my $self = shift;
4116   my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
4117   my $sth = dbh->prepare($sql) or die dbh->errstr;
4118   $sth->execute($self->custnum) or die $sth->errstr;
4119   $sth->fetchrow_arrayref->[0];
4120 }
4121
4122 =item unapplied_cust_pay
4123
4124 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
4125
4126 =cut
4127
4128 sub unapplied_cust_pay {
4129   my $self = shift;
4130
4131   $self->cust_pay(
4132     'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
4133     #@_
4134   );
4135
4136 }
4137
4138 =item cust_pay_pkgnum
4139
4140 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
4141 package when using experimental package balances.
4142
4143 =cut
4144
4145 sub cust_pay_pkgnum {
4146   my( $self, $pkgnum ) = @_;
4147   map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
4148   sort { $a->_date <=> $b->_date }
4149     qsearch( 'cust_pay', { 'custnum' => $self->custnum,
4150                            'pkgnum'  => $pkgnum,
4151                          }
4152     );
4153 }
4154
4155 =item cust_pay_void
4156
4157 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4158
4159 =cut
4160
4161 sub cust_pay_void {
4162   my $self = shift;
4163   map { $_ } #return $self->num_cust_pay_void unless wantarray;
4164   sort { $a->_date <=> $b->_date }
4165     qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4166 }
4167
4168 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4169
4170 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
4171
4172 Optionally, a list or hashref of additional arguments to the qsearch call can
4173 be passed.
4174
4175 =cut
4176
4177 sub cust_pay_batch {
4178   my $self = shift;
4179   my $opt = ref($_[0]) ? shift : { @_ };
4180
4181   #return $self->num_cust_statement unless wantarray || keys %$opt;
4182
4183   $opt->{'table'} = 'cust_pay_batch';
4184   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4185   $opt->{'hashref'}{'custnum'} = $self->custnum;
4186   $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
4187
4188   map { $_ } #behavior of sort undefined in scalar context
4189     sort { $a->paybatchnum <=> $b->paybatchnum }
4190       qsearch($opt);
4191 }
4192
4193 =item cust_pay_pending
4194
4195 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
4196 (without status "done").
4197
4198 =cut
4199
4200 sub cust_pay_pending {
4201   my $self = shift;
4202   return $self->num_cust_pay_pending unless wantarray;
4203   sort { $a->_date <=> $b->_date }
4204     qsearch( 'cust_pay_pending', {
4205                                    'custnum' => $self->custnum,
4206                                    'status'  => { op=>'!=', value=>'done' },
4207                                  },
4208            );
4209 }
4210
4211 =item cust_pay_pending_attempt
4212
4213 Returns all payment attempts / declined payments for this customer, as pending
4214 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
4215 a corresponding payment (see L<FS::cust_pay>).
4216
4217 =cut
4218
4219 sub cust_pay_pending_attempt {
4220   my $self = shift;
4221   return $self->num_cust_pay_pending_attempt unless wantarray;
4222   sort { $a->_date <=> $b->_date }
4223     qsearch( 'cust_pay_pending', {
4224                                    'custnum' => $self->custnum,
4225                                    'status'  => 'done',
4226                                    'paynum'  => '',
4227                                  },
4228            );
4229 }
4230
4231 =item num_cust_pay_pending
4232
4233 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4234 customer (without status "done").  Also called automatically when the
4235 cust_pay_pending method is used in a scalar context.
4236
4237 =cut
4238
4239 sub num_cust_pay_pending {
4240   my $self = shift;
4241   $self->scalar_sql(
4242     " SELECT COUNT(*) FROM cust_pay_pending ".
4243       " WHERE custnum = ? AND status != 'done' ",
4244     $self->custnum
4245   );
4246 }
4247
4248 =item num_cust_pay_pending_attempt
4249
4250 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4251 customer, with status "done" but without a corresp.  Also called automatically when the
4252 cust_pay_pending method is used in a scalar context.
4253
4254 =cut
4255
4256 sub num_cust_pay_pending_attempt {
4257   my $self = shift;
4258   $self->scalar_sql(
4259     " SELECT COUNT(*) FROM cust_pay_pending ".
4260       " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4261     $self->custnum
4262   );
4263 }
4264
4265 =item cust_refund
4266
4267 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4268
4269 =cut
4270
4271 sub cust_refund {
4272   my $self = shift;
4273   map { $_ } #return $self->num_cust_refund unless wantarray;
4274   sort { $a->_date <=> $b->_date }
4275     qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4276 }
4277
4278 =item display_custnum
4279
4280 Returns the displayed customer number for this customer: agent_custid if
4281 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4282
4283 =cut
4284
4285 sub display_custnum {
4286   my $self = shift;
4287
4288   return $self->agent_custid
4289     if $default_agent_custid && $self->agent_custid;
4290
4291   my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4292
4293   if ( $prefix ) {
4294     return $prefix . 
4295            sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
4296   } elsif ( $custnum_display_length ) {
4297     return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
4298   } else {
4299     return $self->custnum;
4300   }
4301 }
4302
4303 =item name
4304
4305 Returns a name string for this customer, either "Company (Last, First)" or
4306 "Last, First".
4307
4308 =cut
4309
4310 sub name {
4311   my $self = shift;
4312   my $name = $self->contact;
4313   $name = $self->company. " ($name)" if $self->company;
4314   $name;
4315 }
4316
4317 =item service_contact
4318
4319 Returns the L<FS::contact> object for this customer that has the 'Service'
4320 contact class, or undef if there is no such contact.  Deprecated; don't use
4321 this in new code.
4322
4323 =cut
4324
4325 sub service_contact {
4326   my $self = shift;
4327   if ( !exists($self->{service_contact}) ) {
4328     my $classnum = $self->scalar_sql(
4329       'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4330     ) || 0; #if it's zero, qsearchs will return nothing
4331     $self->{service_contact} = qsearchs('contact', { 
4332         'classnum' => $classnum, 'custnum' => $self->custnum
4333       }) || undef;
4334   }
4335   $self->{service_contact};
4336 }
4337
4338 =item ship_name
4339
4340 Returns a name string for this (service/shipping) contact, either
4341 "Company (Last, First)" or "Last, First".
4342
4343 =cut
4344
4345 sub ship_name {
4346   my $self = shift;
4347
4348   my $name = $self->ship_contact;
4349   $name = $self->company. " ($name)" if $self->company;
4350   $name;
4351 }
4352
4353 =item name_short
4354
4355 Returns a name string for this customer, either "Company" or "First Last".
4356
4357 =cut
4358
4359 sub name_short {
4360   my $self = shift;
4361   $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4362 }
4363
4364 =item ship_name_short
4365
4366 Returns a name string for this (service/shipping) contact, either "Company"
4367 or "First Last".
4368
4369 =cut
4370
4371 sub ship_name_short {
4372   my $self = shift;
4373   $self->service_contact 
4374     ? $self->ship_contact_firstlast 
4375     : $self->name_short
4376 }
4377
4378 =item contact
4379
4380 Returns this customer's full (billing) contact name only, "Last, First"
4381
4382 =cut
4383
4384 sub contact {
4385   my $self = shift;
4386   $self->get('last'). ', '. $self->first;
4387 }
4388
4389 =item ship_contact
4390
4391 Returns this customer's full (shipping) contact name only, "Last, First"
4392
4393 =cut
4394
4395 sub ship_contact {
4396   my $self = shift;
4397   my $contact = $self->service_contact || $self;
4398   $contact->get('last') . ', ' . $contact->get('first');
4399 }
4400
4401 =item contact_firstlast
4402
4403 Returns this customers full (billing) contact name only, "First Last".
4404
4405 =cut
4406
4407 sub contact_firstlast {
4408   my $self = shift;
4409   $self->first. ' '. $self->get('last');
4410 }
4411
4412 =item ship_contact_firstlast
4413
4414 Returns this customer's full (shipping) contact name only, "First Last".
4415
4416 =cut
4417
4418 sub ship_contact_firstlast {
4419   my $self = shift;
4420   my $contact = $self->service_contact || $self;
4421   $contact->get('first') . ' '. $contact->get('last');
4422 }
4423
4424 sub bill_country_full {
4425   my $self = shift;
4426   $self->bill_location->country_full;
4427 }
4428
4429 sub ship_country_full {
4430   my $self = shift;
4431   $self->ship_location->country_full;
4432 }
4433
4434 =item county_state_county [ PREFIX ]
4435
4436 Returns a string consisting of just the county, state and country.
4437
4438 =cut
4439
4440 sub county_state_country {
4441   my $self = shift;
4442   my $locationnum;
4443   if ( @_ && $_[0] && $self->has_ship_address ) {
4444     $locationnum = $self->ship_locationnum;
4445   } else {
4446     $locationnum = $self->bill_locationnum;
4447   }
4448   my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4449   $cust_location->county_state_country;
4450 }
4451
4452 =item geocode DATA_VENDOR
4453
4454 Returns a value for the customer location as encoded by DATA_VENDOR.
4455 Currently this only makes sense for "CCH" as DATA_VENDOR.
4456
4457 =cut
4458
4459 =item cust_status
4460
4461 =item status
4462
4463 Returns a status string for this customer, currently:
4464
4465 =over 4
4466
4467 =item prospect - No packages have ever been ordered
4468
4469 =item ordered - Recurring packages all are new (not yet billed).
4470
4471 =item active - One or more recurring packages is active
4472
4473 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4474
4475 =item suspended - All non-cancelled recurring packages are suspended
4476
4477 =item cancelled - All recurring packages are cancelled
4478
4479 =back
4480
4481 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4482 cust_main-status_module configuration option.
4483
4484 =cut
4485
4486 sub status { shift->cust_status(@_); }
4487
4488 sub cust_status {
4489   my $self = shift;
4490   return $self->hashref->{cust_status} if $self->hashref->{cust_status};
4491   for my $status ( FS::cust_main->statuses() ) {
4492     my $method = $status.'_sql';
4493     my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4494     my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4495     $sth->execute( ($self->custnum) x $numnum )
4496       or die "Error executing 'SELECT $sql': ". $sth->errstr;
4497     if ( $sth->fetchrow_arrayref->[0] ) {
4498       $self->hashref->{cust_status} = $status;
4499       return $status;
4500     }
4501   }
4502 }
4503
4504 =item is_status_delay_cancel
4505
4506 Returns true if customer status is 'suspended'
4507 and all suspended cust_pkg return true for
4508 cust_pkg->is_status_delay_cancel.
4509
4510 This is not a real status, this only meant for hacking display 
4511 values, because otherwise treating the customer as suspended is 
4512 really the whole point of the delay_cancel option.
4513
4514 =cut
4515
4516 sub is_status_delay_cancel {
4517   my ($self) = @_;
4518   return 0 unless $self->status eq 'suspended';
4519   foreach my $cust_pkg ($self->ncancelled_pkgs) {
4520     return 0 unless $cust_pkg->is_status_delay_cancel;
4521   }
4522   return 1;
4523 }
4524
4525 =item ucfirst_cust_status
4526
4527 =item ucfirst_status
4528
4529 Returns the status with the first character capitalized.
4530
4531 =cut
4532
4533 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4534
4535 sub ucfirst_cust_status {
4536   my $self = shift;
4537   ucfirst($self->cust_status);
4538 }
4539
4540 =item statuscolor
4541
4542 Returns a hex triplet color string for this customer's status.
4543
4544 =cut
4545
4546 sub statuscolor { shift->cust_statuscolor(@_); }
4547
4548 sub cust_statuscolor {
4549   my $self = shift;
4550   __PACKAGE__->statuscolors->{$self->cust_status};
4551 }
4552
4553 =item tickets [ STATUS ]
4554
4555 Returns an array of hashes representing the customer's RT tickets.
4556
4557 An optional status (or arrayref or hashref of statuses) may be specified.
4558
4559 =cut
4560
4561 sub tickets {
4562   my $self = shift;
4563   my $status = ( @_ && $_[0] ) ? shift : '';
4564
4565   my $num = $conf->config('cust_main-max_tickets') || 10;
4566   my @tickets = ();
4567
4568   if ( $conf->config('ticket_system') ) {
4569     unless ( $conf->config('ticket_system-custom_priority_field') ) {
4570
4571       @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4572                                                         $num,
4573                                                         undef,
4574                                                         $status,
4575                                                       )
4576                   };
4577
4578     } else {
4579
4580       foreach my $priority (
4581         $conf->config('ticket_system-custom_priority_field-values'), ''
4582       ) {
4583         last if scalar(@tickets) >= $num;
4584         push @tickets, 
4585           @{ FS::TicketSystem->customer_tickets( $self->custnum,
4586                                                  $num - scalar(@tickets),
4587                                                  $priority,
4588                                                  $status,
4589                                                )
4590            };
4591       }
4592     }
4593   }
4594   (@tickets);
4595 }
4596
4597 =item appointments [ STATUS ]
4598
4599 Returns an array of hashes representing the customer's RT tickets which
4600 are appointments.
4601
4602 =cut
4603
4604 sub appointments {
4605   my $self = shift;
4606   my $status = ( @_ && $_[0] ) ? shift : '';
4607
4608   return () unless $conf->config('ticket_system');
4609
4610   my $queueid = $conf->config('ticket_system-appointment-queueid');
4611
4612   @{ FS::TicketSystem->customer_tickets( $self->custnum,
4613                                          99,
4614                                          undef,
4615                                          $status,
4616                                          $queueid,
4617                                        )
4618   };
4619 }
4620
4621 # Return services representing svc_accts in customer support packages
4622 sub support_services {
4623   my $self = shift;
4624   my %packages = map { $_ => 1 } $conf->config('support_packages');
4625
4626   grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4627     grep { $_->part_svc->svcdb eq 'svc_acct' }
4628     map { $_->cust_svc }
4629     grep { exists $packages{ $_->pkgpart } }
4630     $self->ncancelled_pkgs;
4631
4632 }
4633
4634 # Return a list of latitude/longitude for one of the services (if any)
4635 sub service_coordinates {
4636   my $self = shift;
4637
4638   my @svc_X = 
4639     grep { $_->latitude && $_->longitude }
4640     map { $_->svc_x }
4641     map { $_->cust_svc }
4642     $self->ncancelled_pkgs;
4643
4644   scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4645 }
4646
4647 =item masked FIELD
4648
4649 Returns a masked version of the named field
4650
4651 =cut
4652
4653 sub masked {
4654 my ($self,$field) = @_;
4655
4656 # Show last four
4657
4658 'x'x(length($self->getfield($field))-4).
4659   substr($self->getfield($field), (length($self->getfield($field))-4));
4660
4661 }
4662
4663 =item payment_history
4664
4665 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4666 cust_credit and cust_refund objects.  Each hashref has the following fields:
4667
4668 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4669
4670 I<date> - value of _date field, unix timestamp
4671
4672 I<date_pretty> - user-friendly date
4673
4674 I<description> - user-friendly description of item
4675
4676 I<amount> - impact of item on user's balance 
4677 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4678 Not to be confused with the native 'amount' field in cust_credit, see below.
4679
4680 I<amount_pretty> - includes money char
4681
4682 I<balance> - customer balance, chronologically as of this item
4683
4684 I<balance_pretty> - includes money char
4685
4686 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4687
4688 I<paid> - amount paid for cust_pay records, undef for other types
4689
4690 I<credit> - amount credited for cust_credit records, undef for other types.
4691 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4692
4693 I<refund> - amount refunded for cust_refund records, undef for other types
4694
4695 The four table-specific keys always have positive values, whether they reflect charges or payments.
4696
4697 The following options may be passed to this method:
4698
4699 I<line_items> - if true, returns charges ('Line item') rather than invoices
4700
4701 I<start_date> - unix timestamp, only include records on or after.
4702 If specified, an item of type 'Previous' will also be included.
4703 It does not have table-specific fields.
4704
4705 I<end_date> - unix timestamp, only include records before
4706
4707 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4708
4709 I<conf> - optional already-loaded FS::Conf object.
4710
4711 =cut
4712
4713 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4714 # and also for sending customer statements, which should both be kept customer-friendly.
4715 # If you add anything that shouldn't be passed on through the API or exposed 
4716 # to customers, add a new option to include it, don't include it by default
4717 sub payment_history {
4718   my $self = shift;
4719   my $opt = ref($_[0]) ? $_[0] : { @_ };
4720
4721   my $conf = $$opt{'conf'} || new FS::Conf;
4722   my $money_char = $conf->config("money_char") || '$',
4723
4724   #first load entire history, 
4725   #need previous to calculate previous balance
4726   #loading after end_date shouldn't hurt too much?
4727   my @history = ();
4728   if ( $$opt{'line_items'} ) {
4729
4730     foreach my $cust_bill ( $self->cust_bill ) {
4731
4732       push @history, {
4733         'type'        => 'Line item',
4734         'description' => $_->desc( $self->locale ).
4735                            ( $_->sdate && $_->edate
4736                                ? ' '. time2str('%d-%b-%Y', $_->sdate).
4737                                  ' To '. time2str('%d-%b-%Y', $_->edate)
4738                                : ''
4739                            ),
4740         'amount'      => sprintf('%.2f', $_->setup + $_->recur ),
4741         'charged'     => sprintf('%.2f', $_->setup + $_->recur ),
4742         'date'        => $cust_bill->_date,
4743         'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4744       }
4745         foreach $cust_bill->cust_bill_pkg;
4746
4747     }
4748
4749   } else {
4750
4751     push @history, {
4752                      'type'        => 'Invoice',
4753                      'description' => 'Invoice #'. $_->display_invnum,
4754                      'amount'      => sprintf('%.2f', $_->charged ),
4755                      'charged'     => sprintf('%.2f', $_->charged ),
4756                      'date'        => $_->_date,
4757                      'date_pretty' => $self->time2str_local('short', $_->_date ),
4758                    }
4759       foreach $self->cust_bill;
4760
4761   }
4762
4763   push @history, {
4764                    'type'        => 'Payment',
4765                    'description' => 'Payment', #XXX type
4766                    'amount'      => sprintf('%.2f', 0 - $_->paid ),
4767                    'paid'        => sprintf('%.2f', $_->paid ),
4768                    'date'        => $_->_date,
4769                    'date_pretty' => $self->time2str_local('short', $_->_date ),
4770                  }
4771     foreach $self->cust_pay;
4772
4773   push @history, {
4774                    'type'        => 'Credit',
4775                    'description' => 'Credit', #more info?
4776                    'amount'      => sprintf('%.2f', 0 -$_->amount ),
4777                    'credit'      => sprintf('%.2f', $_->amount ),
4778                    'date'        => $_->_date,
4779                    'date_pretty' => $self->time2str_local('short', $_->_date ),
4780                  }
4781     foreach $self->cust_credit;
4782
4783   push @history, {
4784                    'type'        => 'Refund',
4785                    'description' => 'Refund', #more info?  type, like payment?
4786                    'amount'      => $_->refund,
4787                    'refund'      => $_->refund,
4788                    'date'        => $_->_date,
4789                    'date_pretty' => $self->time2str_local('short', $_->_date ),
4790                  }
4791     foreach $self->cust_refund;
4792
4793   #put it all in chronological order
4794   @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4795
4796   #calculate balance, filter items outside date range
4797   my $previous = 0;
4798   my $balance = 0;
4799   my @out = ();
4800   foreach my $item (@history) {
4801     last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4802     $balance += $$item{'amount'};
4803     if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4804       $previous += $$item{'amount'};
4805       next;
4806     }
4807     $$item{'balance'} = sprintf("%.2f",$balance);
4808     foreach my $key ( qw(amount balance) ) {
4809       $$item{$key.'_pretty'} = money_pretty($$item{$key});
4810     }
4811     push(@out,$item);
4812   }
4813
4814   # start with previous balance, if there was one
4815   if ($previous) {
4816     my $item = {
4817       'type'        => 'Previous',
4818       'description' => 'Previous balance',
4819       'amount'      => sprintf("%.2f",$previous),
4820       'balance'     => sprintf("%.2f",$previous),
4821       'date'        => $$opt{'start_date'},
4822       'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4823     };
4824     #false laziness with above
4825     foreach my $key ( qw(amount balance) ) {
4826       $$item{$key.'_pretty'} = $$item{$key};
4827       $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4828     }
4829     unshift(@out,$item);
4830   }
4831
4832   @out = reverse @history if $$opt{'reverse_sort'};
4833
4834   return @out;
4835 }
4836
4837 =back
4838
4839 =head1 CLASS METHODS
4840
4841 =over 4
4842
4843 =item statuses
4844
4845 Class method that returns the list of possible status strings for customers
4846 (see L<the status method|/status>).  For example:
4847
4848   @statuses = FS::cust_main->statuses();
4849
4850 =cut
4851
4852 sub statuses {
4853   my $self = shift;
4854   keys %{ $self->statuscolors };
4855 }
4856
4857 =item cust_status_sql
4858
4859 Returns an SQL fragment to determine the status of a cust_main record, as a 
4860 string.
4861
4862 =cut
4863
4864 sub cust_status_sql {
4865   my $sql = 'CASE';
4866   for my $status ( FS::cust_main->statuses() ) {
4867     my $method = $status.'_sql';
4868     $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4869   }
4870   $sql .= ' END';
4871   return $sql;
4872 }
4873
4874
4875 =item prospect_sql
4876
4877 Returns an SQL expression identifying prospective cust_main records (customers
4878 with no packages ever ordered)
4879
4880 =cut
4881
4882 use vars qw($select_count_pkgs);
4883 $select_count_pkgs =
4884   "SELECT COUNT(*) FROM cust_pkg
4885     WHERE cust_pkg.custnum = cust_main.custnum";
4886
4887 sub select_count_pkgs_sql {
4888   $select_count_pkgs;
4889 }
4890
4891 sub prospect_sql {
4892   " 0 = ( $select_count_pkgs ) ";
4893 }
4894
4895 =item ordered_sql
4896
4897 Returns an SQL expression identifying ordered cust_main records (customers with
4898 no active packages, but recurring packages not yet setup or one time charges
4899 not yet billed).
4900
4901 =cut
4902
4903 sub ordered_sql {
4904   FS::cust_main->none_active_sql.
4905   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4906 }
4907
4908 =item active_sql
4909
4910 Returns an SQL expression identifying active cust_main records (customers with
4911 active recurring packages).
4912
4913 =cut
4914
4915 sub active_sql {
4916   " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4917 }
4918
4919 =item none_active_sql
4920
4921 Returns an SQL expression identifying cust_main records with no active
4922 recurring packages.  This includes customers of status prospect, ordered,
4923 inactive, and suspended.
4924
4925 =cut
4926
4927 sub none_active_sql {
4928   " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4929 }
4930
4931 =item inactive_sql
4932
4933 Returns an SQL expression identifying inactive cust_main records (customers with
4934 no active recurring packages, but otherwise unsuspended/uncancelled).
4935
4936 =cut
4937
4938 sub inactive_sql {
4939   FS::cust_main->none_active_sql.
4940   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4941 }
4942
4943 =item susp_sql
4944 =item suspended_sql
4945
4946 Returns an SQL expression identifying suspended cust_main records.
4947
4948 =cut
4949
4950
4951 sub suspended_sql { susp_sql(@_); }
4952 sub susp_sql {
4953   FS::cust_main->none_active_sql.
4954   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4955 }
4956
4957 =item cancel_sql
4958 =item cancelled_sql
4959
4960 Returns an SQL expression identifying cancelled cust_main records.
4961
4962 =cut
4963
4964 sub cancel_sql { shift->cancelled_sql(@_); }
4965
4966 =item uncancel_sql
4967 =item uncancelled_sql
4968
4969 Returns an SQL expression identifying un-cancelled cust_main records.
4970
4971 =cut
4972
4973 sub uncancelled_sql { uncancel_sql(@_); }
4974 sub uncancel_sql { "
4975   ( 0 < ( $select_count_pkgs
4976                    AND ( cust_pkg.cancel IS NULL
4977                          OR cust_pkg.cancel = 0
4978                        )
4979         )
4980     OR 0 = ( $select_count_pkgs )
4981   )
4982 "; }
4983
4984 =item balance_sql
4985
4986 Returns an SQL fragment to retreive the balance.
4987
4988 =cut
4989
4990 sub balance_sql { "
4991     ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4992         WHERE cust_bill.custnum   = cust_main.custnum     )
4993   - ( SELECT COALESCE( SUM(paid),    0 ) FROM cust_pay
4994         WHERE cust_pay.custnum    = cust_main.custnum     )
4995   - ( SELECT COALESCE( SUM(amount),  0 ) FROM cust_credit
4996         WHERE cust_credit.custnum = cust_main.custnum     )
4997   + ( SELECT COALESCE( SUM(refund),  0 ) FROM cust_refund
4998         WHERE cust_refund.custnum = cust_main.custnum     )
4999 "; }
5000
5001 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
5002
5003 Returns an SQL fragment to retreive the balance for this customer, optionally
5004 considering invoices with date earlier than START_TIME, and not
5005 later than END_TIME (total_owed_date minus total_unapplied_credits minus
5006 total_unapplied_payments).
5007
5008 Times are specified as SQL fragments or numeric
5009 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
5010 L<Date::Parse> for conversion functions.  The empty string can be passed
5011 to disable that time constraint completely.
5012
5013 Available options are:
5014
5015 =over 4
5016
5017 =item unapplied_date
5018
5019 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)
5020
5021 =item total
5022
5023 (unused.  obsolete?)
5024 set to true to remove all customer comparison clauses, for totals
5025
5026 =item where
5027
5028 (unused.  obsolete?)
5029 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5030
5031 =item join
5032
5033 (unused.  obsolete?)
5034 JOIN clause (typically used with the total option)
5035
5036 =item cutoff
5037
5038 An absolute cutoff time.  Payments, credits, and refunds I<applied> after this 
5039 time will be ignored.  Note that START_TIME and END_TIME only limit the date 
5040 range for invoices and I<unapplied> payments, credits, and refunds.
5041
5042 =back
5043
5044 =cut
5045
5046 sub balance_date_sql {
5047   my( $class, $start, $end, %opt ) = @_;
5048
5049   my $cutoff = $opt{'cutoff'};
5050
5051   my $owed         = FS::cust_bill->owed_sql($cutoff);
5052   my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
5053   my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
5054   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
5055
5056   my $j = $opt{'join'} || '';
5057
5058   my $owed_wh   = $class->_money_table_where( 'cust_bill',   $start,$end,%opt );
5059   my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5060   my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5061   my $pay_wh    = $class->_money_table_where( 'cust_pay',    $start,$end,%opt );
5062
5063   "   ( SELECT COALESCE(SUM($owed),         0) FROM cust_bill   $j $owed_wh   )
5064     + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5065     - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5066     - ( SELECT COALESCE(SUM($unapp_pay),    0) FROM cust_pay    $j $pay_wh    )
5067   ";
5068
5069 }
5070
5071 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
5072
5073 Returns an SQL fragment to retreive the total unapplied payments for this
5074 customer, only considering payments with date earlier than START_TIME, and
5075 optionally not later than END_TIME.
5076
5077 Times are specified as SQL fragments or numeric
5078 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
5079 L<Date::Parse> for conversion functions.  The empty string can be passed
5080 to disable that time constraint completely.
5081
5082 Available options are:
5083
5084 =cut
5085
5086 sub unapplied_payments_date_sql {
5087   my( $class, $start, $end, %opt ) = @_;
5088
5089   my $cutoff = $opt{'cutoff'};
5090
5091   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
5092
5093   my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
5094                                                           'unapplied_date'=>1 );
5095
5096   " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
5097 }
5098
5099 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5100
5101 Helper method for balance_date_sql; name (and usage) subject to change
5102 (suggestions welcome).
5103
5104 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5105 cust_refund, cust_credit or cust_pay).
5106
5107 If TABLE is "cust_bill" or the unapplied_date option is true, only
5108 considers records with date earlier than START_TIME, and optionally not
5109 later than END_TIME .
5110
5111 =cut
5112
5113 sub _money_table_where {
5114   my( $class, $table, $start, $end, %opt ) = @_;
5115
5116   my @where = ();
5117   push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5118   if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5119     push @where, "$table._date <= $start" if defined($start) && length($start);
5120     push @where, "$table._date >  $end"   if defined($end)   && length($end);
5121   }
5122   push @where, @{$opt{'where'}} if $opt{'where'};
5123   my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5124
5125   $where;
5126
5127 }
5128
5129 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
5130 use FS::cust_main::Search;
5131 sub search {
5132   my $class = shift;
5133   FS::cust_main::Search->search(@_);
5134 }
5135
5136 =back
5137
5138 =head1 SUBROUTINES
5139
5140 =over 4
5141
5142 =item batch_charge
5143
5144 =cut
5145
5146 sub batch_charge {
5147   my $param = shift;
5148   #warn join('-',keys %$param);
5149   my $fh = $param->{filehandle};
5150   my $agentnum = $param->{agentnum};
5151   my $format = $param->{format};
5152
5153   my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
5154
5155   my @fields;
5156   if ( $format eq 'simple' ) {
5157     @fields = qw( custnum agent_custid amount pkg );
5158   } else {
5159     die "unknown format $format";
5160   }
5161
5162   eval "use Text::CSV_XS;";
5163   die $@ if $@;
5164
5165   my $csv = new Text::CSV_XS;
5166   #warn $csv;
5167   #warn $fh;
5168
5169   my $imported = 0;
5170   #my $columns;
5171
5172   local $SIG{HUP} = 'IGNORE';
5173   local $SIG{INT} = 'IGNORE';
5174   local $SIG{QUIT} = 'IGNORE';
5175   local $SIG{TERM} = 'IGNORE';
5176   local $SIG{TSTP} = 'IGNORE';
5177   local $SIG{PIPE} = 'IGNORE';
5178
5179   my $oldAutoCommit = $FS::UID::AutoCommit;
5180   local $FS::UID::AutoCommit = 0;
5181   my $dbh = dbh;
5182   
5183   #while ( $columns = $csv->getline($fh) ) {
5184   my $line;
5185   while ( defined($line=<$fh>) ) {
5186
5187     $csv->parse($line) or do {
5188       $dbh->rollback if $oldAutoCommit;
5189       return "can't parse: ". $csv->error_input();
5190     };
5191
5192     my @columns = $csv->fields();
5193     #warn join('-',@columns);
5194
5195     my %row = ();
5196     foreach my $field ( @fields ) {
5197       $row{$field} = shift @columns;
5198     }
5199
5200     if ( $row{custnum} && $row{agent_custid} ) {
5201       dbh->rollback if $oldAutoCommit;
5202       return "can't specify custnum with agent_custid $row{agent_custid}";
5203     }
5204
5205     my %hash = ();
5206     if ( $row{agent_custid} && $agentnum ) {
5207       %hash = ( 'agent_custid' => $row{agent_custid},
5208                 'agentnum'     => $agentnum,
5209               );
5210     }
5211
5212     if ( $row{custnum} ) {
5213       %hash = ( 'custnum' => $row{custnum} );
5214     }
5215
5216     unless ( scalar(keys %hash) ) {
5217       $dbh->rollback if $oldAutoCommit;
5218       return "can't find customer without custnum or agent_custid and agentnum";
5219     }
5220
5221     my $cust_main = qsearchs('cust_main', { %hash } );
5222     unless ( $cust_main ) {
5223       $dbh->rollback if $oldAutoCommit;
5224       my $custnum = $row{custnum} || $row{agent_custid};
5225       return "unknown custnum $custnum";
5226     }
5227
5228     if ( $row{'amount'} > 0 ) {
5229       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5230       if ( $error ) {
5231         $dbh->rollback if $oldAutoCommit;
5232         return $error;
5233       }
5234       $imported++;
5235     } elsif ( $row{'amount'} < 0 ) {
5236       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5237                                       $row{'pkg'}                         );
5238       if ( $error ) {
5239         $dbh->rollback if $oldAutoCommit;
5240         return $error;
5241       }
5242       $imported++;
5243     } else {
5244       #hmm?
5245     }
5246
5247   }
5248
5249   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5250
5251   return "Empty file!" unless $imported;
5252
5253   ''; #no error
5254
5255 }
5256
5257 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5258
5259 Deprecated.  Use event notification and message templates 
5260 (L<FS::msg_template>) instead.
5261
5262 Sends a templated email notification to the customer (see L<Text::Template>).
5263
5264 OPTIONS is a hash and may include
5265
5266 I<from> - the email sender (default is invoice_from)
5267
5268 I<to> - comma-separated scalar or arrayref of recipients 
5269    (default is invoicing_list)
5270
5271 I<subject> - The subject line of the sent email notification
5272    (default is "Notice from company_name")
5273
5274 I<extra_fields> - a hashref of name/value pairs which will be substituted
5275    into the template
5276
5277 The following variables are vavailable in the template.
5278
5279 I<$first> - the customer first name
5280 I<$last> - the customer last name
5281 I<$company> - the customer company
5282 I<$payby> - a description of the method of payment for the customer
5283             # would be nice to use FS::payby::shortname
5284 I<$payinfo> - the account information used to collect for this customer
5285 I<$expdate> - the expiration of the customer payment in seconds from epoch
5286
5287 =cut
5288
5289 sub notify {
5290   my ($self, $template, %options) = @_;
5291
5292   return unless $conf->exists($template);
5293
5294   my $from = $conf->invoice_from_full($self->agentnum)
5295     if $conf->exists('invoice_from', $self->agentnum);
5296   $from = $options{from} if exists($options{from});
5297
5298   my $to = join(',', $self->invoicing_list_emailonly);
5299   $to = $options{to} if exists($options{to});
5300   
5301   my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5302     if $conf->exists('company_name', $self->agentnum);
5303   $subject = $options{subject} if exists($options{subject});
5304
5305   my $notify_template = new Text::Template (TYPE => 'ARRAY',
5306                                             SOURCE => [ map "$_\n",
5307                                               $conf->config($template)]
5308                                            )
5309     or die "can't create new Text::Template object: Text::Template::ERROR";
5310   $notify_template->compile()
5311     or die "can't compile template: Text::Template::ERROR";
5312
5313   $FS::notify_template::_template::company_name =
5314     $conf->config('company_name', $self->agentnum);
5315   $FS::notify_template::_template::company_address =
5316     join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5317
5318   my $paydate = $self->paydate || '2037-12-31';
5319   $FS::notify_template::_template::first = $self->first;
5320   $FS::notify_template::_template::last = $self->last;
5321   $FS::notify_template::_template::company = $self->company;
5322   $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5323   my $payby = $self->payby;
5324   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5325   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5326
5327   #credit cards expire at the end of the month/year of their exp date
5328   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5329     $FS::notify_template::_template::payby = 'credit card';
5330     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5331     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5332     $expire_time--;
5333   }elsif ($payby eq 'COMP') {
5334     $FS::notify_template::_template::payby = 'complimentary account';
5335   }else{
5336     $FS::notify_template::_template::payby = 'current method';
5337   }
5338   $FS::notify_template::_template::expdate = $expire_time;
5339
5340   for (keys %{$options{extra_fields}}){
5341     no strict "refs";
5342     ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5343   }
5344
5345   send_email(from => $from,
5346              to => $to,
5347              subject => $subject,
5348              body => $notify_template->fill_in( PACKAGE =>
5349                                                 'FS::notify_template::_template'                                              ),
5350             );
5351
5352 }
5353
5354 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5355
5356 Generates a templated notification to the customer (see L<Text::Template>).
5357
5358 OPTIONS is a hash and may include
5359
5360 I<extra_fields> - a hashref of name/value pairs which will be substituted
5361    into the template.  These values may override values mentioned below
5362    and those from the customer record.
5363
5364 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5365
5366 The following variables are available in the template instead of or in addition
5367 to the fields of the customer record.
5368
5369 I<$payby> - a description of the method of payment for the customer
5370             # would be nice to use FS::payby::shortname
5371 I<$payinfo> - the masked account information used to collect for this customer
5372 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5373 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5374
5375 =cut
5376
5377 # a lot like cust_bill::print_latex
5378 sub generate_letter {
5379   my ($self, $template, %options) = @_;
5380
5381   warn "Template $template does not exist" && return
5382     unless $conf->exists($template) || $options{'template_text'};
5383
5384   my $template_source = $options{'template_text'} 
5385                         ? [ $options{'template_text'} ] 
5386                         : [ map "$_\n", $conf->config($template) ];
5387
5388   my $letter_template = new Text::Template
5389                         ( TYPE       => 'ARRAY',
5390                           SOURCE     => $template_source,
5391                           DELIMITERS => [ '[@--', '--@]' ],
5392                         )
5393     or die "can't create new Text::Template object: Text::Template::ERROR";
5394
5395   $letter_template->compile()
5396     or die "can't compile template: Text::Template::ERROR";
5397
5398   my %letter_data = map { $_ => $self->$_ } $self->fields;
5399   $letter_data{payinfo} = $self->mask_payinfo;
5400
5401   #my $paydate = $self->paydate || '2037-12-31';
5402   my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5403
5404   my $payby = $self->payby;
5405   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5406   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5407
5408   #credit cards expire at the end of the month/year of their exp date
5409   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5410     $letter_data{payby} = 'credit card';
5411     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5412     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5413     $expire_time--;
5414   }elsif ($payby eq 'COMP') {
5415     $letter_data{payby} = 'complimentary account';
5416   }else{
5417     $letter_data{payby} = 'current method';
5418   }
5419   $letter_data{expdate} = $expire_time;
5420
5421   for (keys %{$options{extra_fields}}){
5422     $letter_data{$_} = $options{extra_fields}->{$_};
5423   }
5424
5425   unless(exists($letter_data{returnaddress})){
5426     my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5427                                                   $self->agent_template)
5428                      );
5429     if ( length($retadd) ) {
5430       $letter_data{returnaddress} = $retadd;
5431     } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5432       $letter_data{returnaddress} =
5433         join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5434                           s/$/\\\\\*/;
5435                           $_;
5436                         }
5437                     ( $conf->config('company_name', $self->agentnum),
5438                       $conf->config('company_address', $self->agentnum),
5439                     )
5440         );
5441     } else {
5442       $letter_data{returnaddress} = '~';
5443     }
5444   }
5445
5446   $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5447
5448   $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5449
5450   my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5451
5452   my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5453                            DIR      => $dir,
5454                            SUFFIX   => '.eps',
5455                            UNLINK   => 0,
5456                          ) or die "can't open temp file: $!\n";
5457   print $lh $conf->config_binary('logo.eps', $self->agentnum)
5458     or die "can't write temp file: $!\n";
5459   close $lh;
5460   $letter_data{'logo_file'} = $lh->filename;
5461
5462   my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5463                            DIR      => $dir,
5464                            SUFFIX   => '.tex',
5465                            UNLINK   => 0,
5466                          ) or die "can't open temp file: $!\n";
5467
5468   $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5469   close $fh;
5470   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5471   return ($1, $letter_data{'logo_file'});
5472
5473 }
5474
5475 =item print_ps TEMPLATE 
5476
5477 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5478
5479 =cut
5480
5481 sub print_ps {
5482   my $self = shift;
5483   my($file, $lfile) = $self->generate_letter(@_);
5484   my $ps = FS::Misc::generate_ps($file);
5485   unlink($file.'.tex');
5486   unlink($lfile);
5487
5488   $ps;
5489 }
5490
5491 =item print TEMPLATE
5492
5493 Prints the filled in template.
5494
5495 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5496
5497 =cut
5498
5499 sub queueable_print {
5500   my %opt = @_;
5501
5502   my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5503     or die "invalid customer number: " . $opt{custnum};
5504
5505   my $error = $self->print( { 'template' => $opt{template} } );
5506   die $error if $error;
5507 }
5508
5509 sub print {
5510   my ($self, $template) = (shift, shift);
5511   do_print(
5512     [ $self->print_ps($template) ],
5513     'agentnum' => $self->agentnum,
5514   );
5515 }
5516
5517 #these three subs should just go away once agent stuff is all config overrides
5518
5519 sub agent_template {
5520   my $self = shift;
5521   $self->_agent_plandata('agent_templatename');
5522 }
5523
5524 sub agent_invoice_from {
5525   my $self = shift;
5526   $self->_agent_plandata('agent_invoice_from');
5527 }
5528
5529 sub _agent_plandata {
5530   my( $self, $option ) = @_;
5531
5532   #yuck.  this whole thing needs to be reconciled better with 1.9's idea of
5533   #agent-specific Conf
5534
5535   use FS::part_event::Condition;
5536   
5537   my $agentnum = $self->agentnum;
5538
5539   my $regexp = regexp_sql();
5540
5541   my $part_event_option =
5542     qsearchs({
5543       'select'    => 'part_event_option.*',
5544       'table'     => 'part_event_option',
5545       'addl_from' => q{
5546         LEFT JOIN part_event USING ( eventpart )
5547         LEFT JOIN part_event_option AS peo_agentnum
5548           ON ( part_event.eventpart = peo_agentnum.eventpart
5549                AND peo_agentnum.optionname = 'agentnum'
5550                AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5551              )
5552         LEFT JOIN part_event_condition
5553           ON ( part_event.eventpart = part_event_condition.eventpart
5554                AND part_event_condition.conditionname = 'cust_bill_age'
5555              )
5556         LEFT JOIN part_event_condition_option
5557           ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5558                AND part_event_condition_option.optionname = 'age'
5559              )
5560       },
5561       #'hashref'   => { 'optionname' => $option },
5562       #'hashref'   => { 'part_event_option.optionname' => $option },
5563       'extra_sql' =>
5564         " WHERE part_event_option.optionname = ". dbh->quote($option).
5565         " AND action = 'cust_bill_send_agent' ".
5566         " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5567         " AND peo_agentnum.optionname = 'agentnum' ".
5568         " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5569         " ORDER BY
5570            CASE WHEN part_event_condition_option.optionname IS NULL
5571            THEN -1
5572            ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5573         " END
5574           , part_event.weight".
5575         " LIMIT 1"
5576     });
5577     
5578   unless ( $part_event_option ) {
5579     return $self->agent->invoice_template || ''
5580       if $option eq 'agent_templatename';
5581     return '';
5582   }
5583
5584   $part_event_option->optionvalue;
5585
5586 }
5587
5588 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5589
5590 Subroutine (not a method), designed to be called from the queue.
5591
5592 Takes a list of options and values.
5593
5594 Pulls up the customer record via the custnum option and calls bill_and_collect.
5595
5596 =cut
5597
5598 sub queued_bill {
5599   my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5600
5601   my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5602   warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5603
5604   #without this errors don't get rolled back
5605   $args{'fatal'} = 1; # runs from job queue, will be caught
5606
5607   $cust_main->bill_and_collect( %args );
5608 }
5609
5610 sub process_bill_and_collect {
5611   my $job = shift;
5612   my $param = thaw(decode_base64(shift));
5613   my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5614       or die "custnum '$param->{custnum}' not found!\n";
5615   $param->{'job'}   = $job;
5616   $param->{'fatal'} = 1; # runs from job queue, will be caught
5617   $param->{'retry'} = 1;
5618
5619   $cust_main->bill_and_collect( %$param );
5620 }
5621
5622 #starting to take quite a while for big dbs
5623 #   (JRNL: journaled so it only happens once per database)
5624 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5625 # JRNL seq scan of cust_main on signupdate... index signupdate?  will that help?
5626 # JRNL seq scan of cust_main on paydate... index on substrings?  maybe set an
5627 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5628 # JRNL leading/trailing spaces in first, last, company
5629 # - otaker upgrade?  journal and call it good?  (double check to make sure
5630 #    we're not still setting otaker here)
5631 #
5632 #only going to get worse with new location stuff...
5633
5634 sub _upgrade_data { #class method
5635   my ($class, %opts) = @_;
5636
5637   my @statements = (
5638     'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5639   );
5640
5641   #this seems to be the only expensive one.. why does it take so long?
5642   unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5643     push @statements,
5644       'UPDATE cust_main SET signupdate = (SELECT signupdate FROM h_cust_main WHERE signupdate IS NOT NULL AND h_cust_main.custnum = cust_main.custnum ORDER BY historynum DESC LIMIT 1) WHERE signupdate IS NULL';
5645     FS::upgrade_journal->set_done('cust_main__signupdate');
5646   }
5647
5648   unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5649
5650     # fix yyyy-m-dd formatted paydates
5651     if ( driver_name =~ /^mysql/i ) {
5652       push @statements,
5653       "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5654     } else { # the SQL standard
5655       push @statements, 
5656       "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5657     }
5658     FS::upgrade_journal->set_done('cust_main__paydate');
5659   }
5660
5661   unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5662
5663     push @statements, #fix the weird BILL with a cc# in payinfo problem
5664       #DCRD to be safe
5665       "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5666
5667     FS::upgrade_journal->set_done('cust_main__payinfo');
5668     
5669   }
5670
5671   my $t = time;
5672   foreach my $sql ( @statements ) {
5673     my $sth = dbh->prepare($sql) or die dbh->errstr;
5674     $sth->execute or die $sth->errstr;
5675     #warn ( (time - $t). " seconds\n" );
5676     #$t = time;
5677   }
5678
5679   local($ignore_expired_card) = 1;
5680   local($ignore_banned_card) = 1;
5681   local($skip_fuzzyfiles) = 1;
5682   local($import) = 1; #prevent automatic geocoding (need its own variable?)
5683
5684   FS::cust_main::Location->_upgrade_data(%opts);
5685
5686   unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5687
5688     foreach my $cust_main ( qsearch({
5689       'table'     => 'cust_main', 
5690       'hashref'   => {},
5691       'extra_sql' => 'WHERE '.
5692                        join(' OR ',
5693                          map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '%  %'",
5694                            qw( first last company )
5695                        ),
5696     }) ) {
5697       my $error = $cust_main->replace;
5698       die $error if $error;
5699     }
5700
5701     FS::upgrade_journal->set_done('cust_main__trimspaces');
5702
5703   }
5704
5705   $class->_upgrade_otaker(%opts);
5706
5707 }
5708
5709 =back
5710
5711 =head1 BUGS
5712
5713 The delete method.
5714
5715 The delete method should possibly take an FS::cust_main object reference
5716 instead of a scalar customer number.
5717
5718 Bill and collect options should probably be passed as references instead of a
5719 list.
5720
5721 There should probably be a configuration file with a list of allowed credit
5722 card types.
5723
5724 No multiple currency support (probably a larger project than just this module).
5725
5726 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5727
5728 Birthdates rely on negative epoch values.
5729
5730 The payby for card/check batches is broken.  With mixed batching, bad
5731 things will happen.
5732
5733 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5734
5735 =head1 SEE ALSO
5736
5737 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5738 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5739 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
5740
5741 =cut
5742
5743 1;
5744