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