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