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