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