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