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