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