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