RT# 82094 - updated UI for bulk emailing from advanced customer reports
[freeside.git] / FS / FS / cust_main.pm
1 package FS::cust_main;
2 use base qw( FS::cust_main::Packages
3              FS::cust_main::Status
4              FS::cust_main::NationalID
5              FS::cust_main::Billing
6              FS::cust_main::Billing_Realtime
7              FS::cust_main::Billing_Batch
8              FS::cust_main::Billing_Discount
9              FS::cust_main::Billing_ThirdParty
10              FS::cust_main::Location
11              FS::cust_main::Credit_Limit
12              FS::cust_main::Merge
13              FS::cust_main::API
14              FS::otaker_Mixin FS::cust_main_Mixin
15              FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
16              FS::o2m_Common
17              FS::Record
18            );
19
20 require 5.006;
21 use strict;
22 use Carp;
23 use Try::Tiny;
24 use Scalar::Util qw( blessed );
25 use List::Util qw(min);
26 use Tie::IxHash;
27 use File::Temp; #qw( tempfile );
28 use Data::Dumper;
29 use Time::Local qw(timelocal);
30 use Date::Format;
31 #use Date::Manip;
32 use Email::Address;
33 use Business::CreditCard 0.28;
34 use FS::UID qw( dbh driver_name );
35 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
36 use FS::Cursor;
37 use FS::Misc qw( generate_ps do_print money_pretty card_types );
38 use FS::Msgcat qw(gettext);
39 use FS::CurrentUser;
40 use FS::TicketSystem;
41 use FS::payby;
42 use FS::cust_pkg;
43 use FS::cust_svc;
44 use FS::cust_bill;
45 use FS::cust_bill_void;
46 use FS::legacy_cust_bill;
47 use FS::cust_pay;
48 use FS::cust_pay_pending;
49 use FS::cust_pay_void;
50 use FS::cust_pay_batch;
51 use FS::cust_credit;
52 use FS::cust_refund;
53 use FS::part_referral;
54 use FS::cust_main_county;
55 use FS::cust_location;
56 use FS::cust_class;
57 use FS::tax_status;
58 use FS::cust_main_exemption;
59 use FS::cust_tax_adjustment;
60 use FS::cust_tax_location;
61 use FS::agent_currency;
62 use FS::cust_main_invoice;
63 use FS::cust_tag;
64 use FS::prepay_credit;
65 use FS::queue;
66 use FS::part_pkg;
67 use FS::part_export;
68 #use FS::cust_event;
69 use FS::type_pkgs;
70 use FS::payment_gateway;
71 use FS::agent_payment_gateway;
72 use FS::banned_pay;
73 use FS::cust_main_note;
74 use FS::cust_attachment;
75 use FS::cust_contact;
76 use FS::Locales;
77 use FS::upgrade_journal;
78 use FS::sales;
79 use FS::cust_payby;
80 use FS::contact;
81 use FS::reason;
82 use FS::Misc::Savepoint;
83
84 # 1 is mostly method/subroutine entry and options
85 # 2 traces progress of some operations
86 # 3 is even more information including possibly sensitive data
87 our $DEBUG = 0;
88 our $me = '[FS::cust_main]';
89
90 our $import = 0;
91 our $ignore_expired_card = 0;
92 our $ignore_banned_card = 0;
93 our $ignore_invalid_card = 0;
94
95 our $skip_fuzzyfiles = 0;
96
97 our $ucfirst_nowarn = 0;
98
99 #this info is in cust_payby as of 4.x
100 #this and the fields themselves can be removed in 5.x
101 our @encrypted_fields = ('payinfo', 'paycvv');
102 sub nohistory_fields { ('payinfo', 'paycvv'); }
103
104 our $conf;
105 our $default_agent_custid;
106 our $custnum_display_length;
107 #ask FS::UID to run this stuff for us later
108 #$FS::UID::callback{'FS::cust_main'} = sub { 
109 install_callback FS::UID sub { 
110   $conf = new FS::Conf;
111   $ignore_invalid_card    = $conf->exists('allow_invalid_cards');
112   $default_agent_custid   = $conf->exists('cust_main-default_agent_custid');
113   $custnum_display_length = $conf->config('cust_main-custnum-display_length');
114 };
115
116 sub _cache {
117   my $self = shift;
118   my ( $hashref, $cache ) = @_;
119   if ( exists $hashref->{'pkgnum'} ) {
120     #@{ $self->{'_pkgnum'} } = ();
121     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
122     $self->{'_pkgnum'} = $subcache;
123     #push @{ $self->{'_pkgnum'} },
124     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
125   }
126 }
127
128 =head1 NAME
129
130 FS::cust_main - Object methods for cust_main records
131
132 =head1 SYNOPSIS
133
134   use FS::cust_main;
135
136   $record = new FS::cust_main \%hash;
137   $record = new FS::cust_main { 'column' => 'value' };
138
139   $error = $record->insert;
140
141   $error = $new_record->replace($old_record);
142
143   $error = $record->delete;
144
145   $error = $record->check;
146
147   @cust_pkg = $record->all_pkgs;
148
149   @cust_pkg = $record->ncancelled_pkgs;
150
151   @cust_pkg = $record->suspended_pkgs;
152
153   $error = $record->bill;
154   $error = $record->bill %options;
155   $error = $record->bill 'time' => $time;
156
157   $error = $record->collect;
158   $error = $record->collect %options;
159   $error = $record->collect 'invoice_time'   => $time,
160                           ;
161
162 =head1 DESCRIPTION
163
164 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
165 FS::Record.  The following fields are currently supported:
166
167 =over 4
168
169 =item custnum
170
171 Primary key (assigned automatically for new customers)
172
173 =item agentnum
174
175 Agent (see L<FS::agent>)
176
177 =item refnum
178
179 Advertising source (see L<FS::part_referral>)
180
181 =item first
182
183 First name
184
185 =item last
186
187 Last name
188
189 =item ss
190
191 Cocial security number (optional)
192
193 =item company
194
195 (optional)
196
197 =item daytime
198
199 phone (optional)
200
201 =item night
202
203 phone (optional)
204
205 =item fax
206
207 phone (optional)
208
209 =item mobile
210
211 phone (optional)
212
213 =item payby
214
215 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
216
217 =item payinfo
218
219 Payment Information (See L<FS::payinfo_Mixin> for data format)
220
221 =item paymask
222
223 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
224
225 =item paycvv
226
227 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
228
229 =item paydate
230
231 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
232
233 =item paystart_month
234
235 Start date month (maestro/solo cards only)
236
237 =item paystart_year
238
239 Start date year (maestro/solo cards only)
240
241 =item payissue
242
243 Issue number (maestro/solo cards only)
244
245 =item payname
246
247 Name on card or billing name
248
249 =item payip
250
251 IP address from which payment information was received
252
253 =item tax
254
255 Tax exempt, empty or `Y'
256
257 =item usernum
258
259 Order taker (see L<FS::access_user>)
260
261 =item comments
262
263 Comments (optional)
264
265 =item referral_custnum
266
267 Referring customer number
268
269 =item spool_cdr
270
271 Enable individual CDR spooling, empty or `Y'
272
273 =item dundate
274
275 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
276
277 =item squelch_cdr
278
279 Discourage individual CDR printing, empty or `Y'
280
281 =item edit_subject
282
283 Allow self-service editing of ticket subjects, empty or 'Y'
284
285 =item calling_list_exempt
286
287 Do not call, empty or 'Y'
288
289 =item invoice_ship_address
290
291 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
292
293 =back
294
295 =head1 METHODS
296
297 =over 4
298
299 =item new HASHREF
300
301 Creates a new customer.  To add the customer to the database, see L<"insert">.
302
303 Note that this stores the hash reference, not a distinct copy of the hash it
304 points to.  You can ask the object for a copy with the I<hash> method.
305
306 =cut
307
308 sub table { 'cust_main'; }
309
310 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
311
312 Adds this customer to the database.  If there is an error, returns the error,
313 otherwise returns false.
314
315 Usually the customer's location will not yet exist in the database, and
316 the C<bill_location> and C<ship_location> pseudo-fields must be set to 
317 uninserted L<FS::cust_location> objects.  These will be inserted and linked
318 (in both directions) to the new customer record.  If they're references 
319 to the same object, they will become the same location.
320
321 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
322 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
323 are inserted atomicly, or the transaction is rolled back.  Passing an empty
324 hash reference is equivalent to not supplying this parameter.  There should be
325 a better explanation of this, but until then, here's an example:
326
327   use Tie::RefHash;
328   tie %hash, 'Tie::RefHash'; #this part is important
329   %hash = (
330     $cust_pkg => [ $svc_acct ],
331     ...
332   );
333   $cust_main->insert( \%hash );
334
335 INVOICING_LIST_ARYREF: No longer supported.
336
337 Currently available options are: I<depend_jobnum>, I<noexport>,
338 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
339
340 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
341 on the supplied jobnum (they will not run until the specific job completes).
342 This can be used to defer provisioning until some action completes (such
343 as running the customer's credit card successfully).
344
345 The I<noexport> option is deprecated.  If I<noexport> is set true, no
346 provisioning jobs (exports) are scheduled.  (You can schedule them later with
347 the B<reexport> method.)
348
349 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
350 of tax names and exemption numbers.  FS::cust_main_exemption records will be
351 created and inserted.
352
353 If I<prospectnum> is set, moves contacts and locations from that prospect.
354
355 If I<contact> is set to an arrayref of FS::contact objects, those will be
356 inserted.
357
358 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
359 unset), inserts those new contacts with this new customer.  Handles CGI
360 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
361
362 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
363 new stored payment records with this new customer.  Handles CGI parameters
364 for an "m2" multiple entry field as passed by edit/cust_main.cgi
365
366 =cut
367
368 sub insert {
369   my $self = shift;
370   my $cust_pkgs = @_ ? shift : {};
371   my $invoicing_list;
372   if ( $_[0] and ref($_[0]) eq 'ARRAY' ) {
373     warn "cust_main::insert using deprecated invoicing list argument";
374     $invoicing_list = shift;
375   }
376   my %options = @_;
377   warn "$me insert called with options ".
378        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
379     if $DEBUG;
380
381   return "You are not permitted to change customer invoicing terms."
382     if $self->invoice_terms #i.e. not the default
383     && ! $FS::CurrentUser::CurrentUser->access_right('Edit customer invoice terms');
384
385   local $SIG{HUP} = 'IGNORE';
386   local $SIG{INT} = 'IGNORE';
387   local $SIG{QUIT} = 'IGNORE';
388   local $SIG{TERM} = 'IGNORE';
389   local $SIG{TSTP} = 'IGNORE';
390   local $SIG{PIPE} = 'IGNORE';
391
392   my $oldAutoCommit = $FS::UID::AutoCommit;
393   local $FS::UID::AutoCommit = 0;
394   my $dbh = dbh;
395
396   my $prepay_identifier = '';
397   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
398   my $payby = '';
399   if ( $self->payby eq 'PREPAY' ) {
400
401     $self->payby(''); #'BILL');
402     $prepay_identifier = $self->payinfo;
403     $self->payinfo('');
404
405     warn "  looking up prepaid card $prepay_identifier\n"
406       if $DEBUG > 1;
407
408     my $error = $self->get_prepay( $prepay_identifier,
409                                    'amount_ref'     => \$amount,
410                                    'seconds_ref'    => \$seconds,
411                                    'upbytes_ref'    => \$upbytes,
412                                    'downbytes_ref'  => \$downbytes,
413                                    'totalbytes_ref' => \$totalbytes,
414                                  );
415     if ( $error ) {
416       $dbh->rollback if $oldAutoCommit;
417       #return "error applying prepaid card (transaction rolled back): $error";
418       return $error;
419     }
420
421     $payby = 'PREP' if $amount;
422
423   } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
424
425     $payby = $1;
426     $self->payby(''); #'BILL');
427     $amount = $self->paid;
428
429   }
430
431   # insert locations
432   foreach my $l (qw(bill_location ship_location)) {
433
434     my $loc = delete $self->hashref->{$l} or next;
435
436     if ( !$loc->locationnum ) {
437       # warn the location that we're going to insert it with no custnum
438       $loc->set(custnum_pending => 1);
439       warn "  inserting $l\n"
440         if $DEBUG > 1;
441       my $error = $loc->insert;
442       if ( $error ) {
443         $dbh->rollback if $oldAutoCommit;
444         my $label = $l eq 'ship_location' ? 'service' : 'billing';
445         return "$error (in $label location)";
446       }
447
448     } elsif ( $loc->prospectnum ) {
449
450       $loc->prospectnum('');
451       $loc->set(custnum_pending => 1);
452       my $error = $loc->replace;
453       if ( $error ) {
454         $dbh->rollback if $oldAutoCommit;
455         my $label = $l eq 'ship_location' ? 'service' : 'billing';
456         return "$error (moving $label location)";
457       }
458
459     } elsif ( ($loc->custnum || 0) > 0 ) {
460       # then it somehow belongs to another customer--shouldn't happen
461       $dbh->rollback if $oldAutoCommit;
462       return "$l belongs to customer ".$loc->custnum;
463     }
464     # else it already belongs to this customer 
465     # (happens when ship_location is identical to bill_location)
466
467     $self->set($l.'num', $loc->locationnum);
468
469     if ( $self->get($l.'num') eq '' ) {
470       $dbh->rollback if $oldAutoCommit;
471       return "$l not set";
472     }
473   }
474
475   warn "  inserting $self\n"
476     if $DEBUG > 1;
477
478   $self->signupdate(time) unless $self->signupdate;
479
480   $self->auto_agent_custid()
481     if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
482
483   my $error =  $self->check_payinfo_cardtype
484             || $self->SUPER::insert;
485   if ( $error ) {
486     $dbh->rollback if $oldAutoCommit;
487     #return "inserting cust_main record (transaction rolled back): $error";
488     return $error;
489   }
490
491   # now set cust_location.custnum
492   foreach my $l (qw(bill_location ship_location)) {
493     warn "  setting $l.custnum\n"
494       if $DEBUG > 1;
495     my $loc = $self->$l or next;
496     unless ( $loc->custnum ) {
497       $loc->set(custnum => $self->custnum);
498       $error ||= $loc->replace;
499     }
500
501     if ( $error ) {
502       $dbh->rollback if $oldAutoCommit;
503       return "error setting $l custnum: $error";
504     }
505   }
506
507   warn "  setting customer tags\n"
508     if $DEBUG > 1;
509
510   foreach my $tagnum ( @{ $self->tagnum || [] } ) {
511     my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
512                                       'custnum' => $self->custnum };
513     my $error = $cust_tag->insert;
514     if ( $error ) {
515       $dbh->rollback if $oldAutoCommit;
516       return $error;
517     }
518   }
519
520   my $prospectnum = delete $options{'prospectnum'};
521   if ( $prospectnum ) {
522
523     warn "  moving contacts and locations from prospect $prospectnum\n"
524       if $DEBUG > 1;
525
526     my $prospect_main =
527       qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
528     unless ( $prospect_main ) {
529       $dbh->rollback if $oldAutoCommit;
530       return "Unknown prospectnum $prospectnum";
531     }
532     $prospect_main->custnum($self->custnum);
533     $prospect_main->disabled('Y');
534     my $error = $prospect_main->replace;
535     if ( $error ) {
536       $dbh->rollback if $oldAutoCommit;
537       return $error;
538     }
539
540     foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
541       my $cust_contact = new FS::cust_contact {
542         'custnum' => $self->custnum,
543         'invoice_dest' => 'Y', # invoice_dest currently not set for prospect contacts
544         map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
545       };
546       my $error =  $cust_contact->insert
547                 || $prospect_contact->delete;
548       if ( $error ) {
549         $dbh->rollback if $oldAutoCommit;
550         return $error;
551       }
552     }
553
554     my @cust_location = $prospect_main->cust_location;
555     my @qual = $prospect_main->qual;
556
557     foreach my $r ( @cust_location, @qual ) {
558       $r->prospectnum('');
559       $r->custnum($self->custnum);
560       my $error = $r->replace;
561       if ( $error ) {
562         $dbh->rollback if $oldAutoCommit;
563         return $error;
564       }
565     }
566     # since we set invoice_dest on all migrated prospect contacts (for now),
567     # don't process invoicing_list.
568     delete $options{'invoicing_list'};
569     $invoicing_list = undef;
570   }
571
572   warn "  setting contacts\n"
573     if $DEBUG > 1;
574
575   $invoicing_list ||= $options{'invoicing_list'};
576   if ( $invoicing_list ) {
577
578     $invoicing_list = [ $invoicing_list ] if !ref($invoicing_list);
579
580     my $email = '';
581     foreach my $dest (@$invoicing_list ) {
582       if ($dest eq 'POST') {
583         $self->set('postal_invoice', 'Y');
584       } else {
585
586         my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
587         if ( $contact_email ) {
588           my $cust_contact = FS::cust_contact->new({
589               contactnum    => $contact_email->contactnum,
590               custnum       => $self->custnum,
591           });
592           $cust_contact->set('invoice_dest', 'Y');
593           my $error = $cust_contact->insert;
594           if ( $error ) {
595             $dbh->rollback if $oldAutoCommit;
596             return "$error (linking to email address $dest)";
597           }
598
599         } else {
600           # this email address is not yet linked to any contact
601           $email .= ',' if length($email);
602           $email .= $dest;
603         }
604       }
605     }
606
607     if ( $email ) {
608
609       my $contact = FS::contact->new({
610         'custnum'       => $self->get('custnum'),
611         'last'          => $self->get('last'),
612         'first'         => $self->get('first'),
613         'emailaddress'  => $email,
614         'invoice_dest'  => 'Y', # yes, you can set this via the contact
615       });
616       my $error = $contact->insert;
617       if ( $error ) {
618         $dbh->rollback if $oldAutoCommit;
619         return $error;
620       }
621
622     }
623
624   }
625
626   if ( my $contact = delete $options{'contact'} ) {
627
628     foreach my $c ( @$contact ) {
629       $c->custnum($self->custnum);
630       my $error = $c->insert;
631       if ( $error ) {
632         $dbh->rollback if $oldAutoCommit;
633         return $error;
634       }
635
636     }
637
638   } elsif ( my $contact_params = delete $options{'contact_params'} ) {
639
640     my $error = $self->process_o2m( 'table'  => 'contact',
641                                     'fields' => FS::contact->cgi_contact_fields,
642                                     'params' => $contact_params,
643                                   );
644     if ( $error ) {
645       $dbh->rollback if $oldAutoCommit;
646       return $error;
647     }
648   }
649
650   warn "  setting cust_payby\n"
651     if $DEBUG > 1;
652
653   if ( $options{cust_payby} ) {
654
655     foreach my $cust_payby ( @{ $options{cust_payby} } ) {
656       $cust_payby->custnum($self->custnum);
657       my $error = $cust_payby->insert;
658       if ( $error ) {
659         $dbh->rollback if $oldAutoCommit;
660         return $error;
661       }
662     }
663
664   } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
665
666     my $error = $self->process_o2m(
667       'table'         => 'cust_payby',
668       'fields'        => FS::cust_payby->cgi_cust_payby_fields,
669       'params'        => $cust_payby_params,
670       'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
671     );
672     if ( $error ) {
673       $dbh->rollback if $oldAutoCommit;
674       return $error;
675     }
676
677   }
678
679   warn "  setting cust_main_exemption\n"
680     if $DEBUG > 1;
681
682   my $tax_exemption = delete $options{'tax_exemption'};
683   if ( $tax_exemption ) {
684
685     $tax_exemption = { map { $_ => '' } @$tax_exemption }
686       if ref($tax_exemption) eq 'ARRAY';
687
688     foreach my $taxname ( keys %$tax_exemption ) {
689       my $cust_main_exemption = new FS::cust_main_exemption {
690         'custnum'       => $self->custnum,
691         'taxname'       => $taxname,
692         'exempt_number' => $tax_exemption->{$taxname},
693       };
694       my $error = $cust_main_exemption->insert;
695       if ( $error ) {
696         $dbh->rollback if $oldAutoCommit;
697         return "inserting cust_main_exemption (transaction rolled back): $error";
698       }
699     }
700   }
701
702   warn "  ordering packages\n"
703     if $DEBUG > 1;
704
705   $error = $self->order_pkgs( $cust_pkgs,
706                               %options,
707                               'seconds_ref'    => \$seconds,
708                               'upbytes_ref'    => \$upbytes,
709                               'downbytes_ref'  => \$downbytes,
710                               'totalbytes_ref' => \$totalbytes,
711                             );
712   if ( $error ) {
713     $dbh->rollback if $oldAutoCommit;
714     return $error;
715   }
716
717   if ( $seconds ) {
718     $dbh->rollback if $oldAutoCommit;
719     return "No svc_acct record to apply pre-paid time";
720   }
721   if ( $upbytes || $downbytes || $totalbytes ) {
722     $dbh->rollback if $oldAutoCommit;
723     return "No svc_acct record to apply pre-paid data";
724   }
725
726   if ( $amount ) {
727     warn "  inserting initial $payby payment of $amount\n"
728       if $DEBUG > 1;
729     $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
730     if ( $error ) {
731       $dbh->rollback if $oldAutoCommit;
732       return "inserting payment (transaction rolled back): $error";
733     }
734   }
735
736   unless ( $import || $skip_fuzzyfiles ) {
737     warn "  queueing fuzzyfiles update\n"
738       if $DEBUG > 1;
739     $error = $self->queue_fuzzyfiles_update;
740     if ( $error ) {
741       $dbh->rollback if $oldAutoCommit;
742       return "updating fuzzy search cache: $error";
743     }
744   }
745
746   # cust_main exports!
747   warn "  exporting\n" if $DEBUG > 1;
748
749   my $export_args = $options{'export_args'} || [];
750
751   my @part_export =
752     map qsearch( 'part_export', {exportnum=>$_} ),
753       $conf->config('cust_main-exports'); #, $agentnum
754
755   foreach my $part_export ( @part_export ) {
756     my $error = $part_export->export_insert($self, @$export_args);
757     if ( $error ) {
758       $dbh->rollback if $oldAutoCommit;
759       return "exporting to ". $part_export->exporttype.
760              " (transaction rolled back): $error";
761     }
762   }
763
764   #foreach my $depend_jobnum ( @$depend_jobnums ) {
765   #    warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
766   #      if $DEBUG;
767   #    foreach my $jobnum ( @jobnums ) {
768   #      my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
769   #      warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
770   #        if $DEBUG;
771   #      my $error = $queue->depend_insert($depend_jobnum);
772   #      if ( $error ) {
773   #        $dbh->rollback if $oldAutoCommit;
774   #        return "error queuing job dependancy: $error";
775   #      }
776   #    }
777   #  }
778   #
779   #}
780   #
781   #if ( exists $options{'jobnums'} ) {
782   #  push @{ $options{'jobnums'} }, @jobnums;
783   #}
784
785   warn "  insert complete; committing transaction\n"
786     if $DEBUG > 1;
787
788   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
789   '';
790
791 }
792
793 use File::CounterFile;
794 sub auto_agent_custid {
795   my $self = shift;
796
797   my $format = $conf->config('cust_main-auto_agent_custid');
798   my $agent_custid;
799   if ( $format eq '1YMMXXXXXXXX' ) {
800
801     my $counter = new File::CounterFile 'cust_main.agent_custid';
802     $counter->lock;
803
804     my $ym = 100000000000 + time2str('%y%m00000000', time);
805     if ( $ym > $counter->value ) {
806       $counter->{'value'} = $agent_custid = $ym;
807       $counter->{'updated'} = 1;
808     } else {
809       $agent_custid = $counter->inc;
810     }
811
812     $counter->unlock;
813
814   } else {
815     die "Unknown cust_main-auto_agent_custid format: $format";
816   }
817
818   $self->agent_custid($agent_custid);
819
820 }
821
822 =item PACKAGE METHODS
823
824 Documentation on customer package methods has been moved to
825 L<FS::cust_main::Packages>.
826
827 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
828
829 Recharges this (existing) customer with the specified prepaid card (see
830 L<FS::prepay_credit>), specified either by I<identifier> or as an
831 FS::prepay_credit object.  If there is an error, returns the error, otherwise
832 returns false.
833
834 Optionally, five scalar references can be passed as well.  They will have their
835 values filled in with the amount, number of seconds, and number of upload,
836 download, and total bytes applied by this prepaid card.
837
838 =cut
839
840 #the ref bullshit here should be refactored like get_prepay.  MyAccount.pm is
841 #the only place that uses these args
842 sub recharge_prepay { 
843   my( $self, $prepay_credit, $amountref, $secondsref, 
844       $upbytesref, $downbytesref, $totalbytesref ) = @_;
845
846   local $SIG{HUP} = 'IGNORE';
847   local $SIG{INT} = 'IGNORE';
848   local $SIG{QUIT} = 'IGNORE';
849   local $SIG{TERM} = 'IGNORE';
850   local $SIG{TSTP} = 'IGNORE';
851   local $SIG{PIPE} = 'IGNORE';
852
853   my $oldAutoCommit = $FS::UID::AutoCommit;
854   local $FS::UID::AutoCommit = 0;
855   my $dbh = dbh;
856
857   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
858
859   my $error = $self->get_prepay( $prepay_credit,
860                                  'amount_ref'     => \$amount,
861                                  'seconds_ref'    => \$seconds,
862                                  'upbytes_ref'    => \$upbytes,
863                                  'downbytes_ref'  => \$downbytes,
864                                  'totalbytes_ref' => \$totalbytes,
865                                )
866            || $self->increment_seconds($seconds)
867            || $self->increment_upbytes($upbytes)
868            || $self->increment_downbytes($downbytes)
869            || $self->increment_totalbytes($totalbytes)
870            || $self->insert_cust_pay_prepay( $amount,
871                                              ref($prepay_credit)
872                                                ? $prepay_credit->identifier
873                                                : $prepay_credit
874                                            );
875
876   if ( $error ) {
877     $dbh->rollback if $oldAutoCommit;
878     return $error;
879   }
880
881   if ( defined($amountref)  ) { $$amountref  = $amount;  }
882   if ( defined($secondsref) ) { $$secondsref = $seconds; }
883   if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
884   if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
885   if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
886
887   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
888   '';
889
890 }
891
892 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
893
894 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
895 specified either by I<identifier> or as an FS::prepay_credit object.
896
897 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.  The scalars (provided by references) will be
898 incremented by the values of the prepaid card.
899
900 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
901 check or set this customer's I<agentnum>.
902
903 If there is an error, returns the error, otherwise returns false.
904
905 =cut
906
907
908 sub get_prepay {
909   my( $self, $prepay_credit, %opt ) = @_;
910
911   local $SIG{HUP} = 'IGNORE';
912   local $SIG{INT} = 'IGNORE';
913   local $SIG{QUIT} = 'IGNORE';
914   local $SIG{TERM} = 'IGNORE';
915   local $SIG{TSTP} = 'IGNORE';
916   local $SIG{PIPE} = 'IGNORE';
917
918   my $oldAutoCommit = $FS::UID::AutoCommit;
919   local $FS::UID::AutoCommit = 0;
920   my $dbh = dbh;
921
922   unless ( ref($prepay_credit) ) {
923
924     my $identifier = $prepay_credit;
925
926     $prepay_credit = qsearchs(
927       'prepay_credit',
928       { 'identifier' => $identifier },
929       '',
930       'FOR UPDATE'
931     );
932
933     unless ( $prepay_credit ) {
934       $dbh->rollback if $oldAutoCommit;
935       return "Invalid prepaid card: ". $identifier;
936     }
937
938   }
939
940   if ( $prepay_credit->agentnum ) {
941     if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
942       $dbh->rollback if $oldAutoCommit;
943       return "prepaid card not valid for agent ". $self->agentnum;
944     }
945     $self->agentnum($prepay_credit->agentnum);
946   }
947
948   my $error = $prepay_credit->delete;
949   if ( $error ) {
950     $dbh->rollback if $oldAutoCommit;
951     return "removing prepay_credit (transaction rolled back): $error";
952   }
953
954   ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
955     for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
956
957   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
958   '';
959
960 }
961
962 =item increment_upbytes SECONDS
963
964 Updates this customer's single or primary account (see L<FS::svc_acct>) by
965 the specified number of upbytes.  If there is an error, returns the error,
966 otherwise returns false.
967
968 =cut
969
970 sub increment_upbytes {
971   _increment_column( shift, 'upbytes', @_);
972 }
973
974 =item increment_downbytes SECONDS
975
976 Updates this customer's single or primary account (see L<FS::svc_acct>) by
977 the specified number of downbytes.  If there is an error, returns the error,
978 otherwise returns false.
979
980 =cut
981
982 sub increment_downbytes {
983   _increment_column( shift, 'downbytes', @_);
984 }
985
986 =item increment_totalbytes SECONDS
987
988 Updates this customer's single or primary account (see L<FS::svc_acct>) by
989 the specified number of totalbytes.  If there is an error, returns the error,
990 otherwise returns false.
991
992 =cut
993
994 sub increment_totalbytes {
995   _increment_column( shift, 'totalbytes', @_);
996 }
997
998 =item increment_seconds SECONDS
999
1000 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1001 the specified number of seconds.  If there is an error, returns the error,
1002 otherwise returns false.
1003
1004 =cut
1005
1006 sub increment_seconds {
1007   _increment_column( shift, 'seconds', @_);
1008 }
1009
1010 =item _increment_column AMOUNT
1011
1012 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1013 the specified number of seconds or bytes.  If there is an error, returns
1014 the error, otherwise returns false.
1015
1016 =cut
1017
1018 sub _increment_column {
1019   my( $self, $column, $amount ) = @_;
1020   warn "$me increment_column called: $column, $amount\n"
1021     if $DEBUG;
1022
1023   return '' unless $amount;
1024
1025   my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1026                       $self->ncancelled_pkgs;
1027
1028   if ( ! @cust_pkg ) {
1029     return 'No packages with primary or single services found'.
1030            ' to apply pre-paid time';
1031   } elsif ( scalar(@cust_pkg) > 1 ) {
1032     #maybe have a way to specify the package/account?
1033     return 'Multiple packages found to apply pre-paid time';
1034   }
1035
1036   my $cust_pkg = $cust_pkg[0];
1037   warn "  found package pkgnum ". $cust_pkg->pkgnum. "\n"
1038     if $DEBUG > 1;
1039
1040   my @cust_svc =
1041     $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1042
1043   if ( ! @cust_svc ) {
1044     return 'No account found to apply pre-paid time';
1045   } elsif ( scalar(@cust_svc) > 1 ) {
1046     return 'Multiple accounts found to apply pre-paid time';
1047   }
1048   
1049   my $svc_acct = $cust_svc[0]->svc_x;
1050   warn "  found service svcnum ". $svc_acct->pkgnum.
1051        ' ('. $svc_acct->email. ")\n"
1052     if $DEBUG > 1;
1053
1054   $column = "increment_$column";
1055   $svc_acct->$column($amount);
1056
1057 }
1058
1059 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1060
1061 Inserts a prepayment in the specified amount for this customer.  An optional
1062 second argument can specify the prepayment identifier for tracking purposes.
1063 If there is an error, returns the error, otherwise returns false.
1064
1065 =cut
1066
1067 sub insert_cust_pay_prepay {
1068   shift->insert_cust_pay('PREP', @_);
1069 }
1070
1071 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1072
1073 Inserts a cash payment in the specified amount for this customer.  An optional
1074 second argument can specify the payment identifier for tracking purposes.
1075 If there is an error, returns the error, otherwise returns false.
1076
1077 =cut
1078
1079 sub insert_cust_pay_cash {
1080   shift->insert_cust_pay('CASH', @_);
1081 }
1082
1083 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1084
1085 Inserts a Western Union payment in the specified amount for this customer.  An
1086 optional second argument can specify the prepayment identifier for tracking
1087 purposes.  If there is an error, returns the error, otherwise returns false.
1088
1089 =cut
1090
1091 sub insert_cust_pay_west {
1092   shift->insert_cust_pay('WEST', @_);
1093 }
1094
1095 sub insert_cust_pay {
1096   my( $self, $payby, $amount ) = splice(@_, 0, 3);
1097   my $payinfo = scalar(@_) ? shift : '';
1098
1099   my $cust_pay = new FS::cust_pay {
1100     'custnum' => $self->custnum,
1101     'paid'    => sprintf('%.2f', $amount),
1102     #'_date'   => #date the prepaid card was purchased???
1103     'payby'   => $payby,
1104     'payinfo' => $payinfo,
1105   };
1106   $cust_pay->insert;
1107
1108 }
1109
1110 =item delete [ OPTION => VALUE ... ]
1111
1112 This deletes the customer.  If there is an error, returns the error, otherwise
1113 returns false.
1114
1115 This will completely remove all traces of the customer record.  This is not
1116 what you want when a customer cancels service; for that, cancel all of the
1117 customer's packages (see L</cancel>).
1118
1119 If the customer has any uncancelled packages, you need to pass a new (valid)
1120 customer number for those packages to be transferred to, as the "new_customer"
1121 option.  Cancelled packages will be deleted.  Did I mention that this is NOT
1122 what you want when a customer cancels service and that you really should be
1123 looking at L<FS::cust_pkg/cancel>?  
1124
1125 You can't delete a customer with invoices (see L<FS::cust_bill>),
1126 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1127 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1128 set the "delete_financials" option to a true value.
1129
1130 =cut
1131
1132 sub delete {
1133   my( $self, %opt ) = @_;
1134
1135   local $SIG{HUP} = 'IGNORE';
1136   local $SIG{INT} = 'IGNORE';
1137   local $SIG{QUIT} = 'IGNORE';
1138   local $SIG{TERM} = 'IGNORE';
1139   local $SIG{TSTP} = 'IGNORE';
1140   local $SIG{PIPE} = 'IGNORE';
1141
1142   my $oldAutoCommit = $FS::UID::AutoCommit;
1143   local $FS::UID::AutoCommit = 0;
1144   my $dbh = dbh;
1145
1146   if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1147      $dbh->rollback if $oldAutoCommit;
1148      return "Can't delete a master agent customer";
1149   }
1150
1151   #use FS::access_user
1152   if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1153      $dbh->rollback if $oldAutoCommit;
1154      return "Can't delete a master employee customer";
1155   }
1156
1157   tie my %financial_tables, 'Tie::IxHash',
1158     'cust_bill'      => 'invoices',
1159     'cust_statement' => 'statements',
1160     'cust_credit'    => 'credits',
1161     'cust_pay'       => 'payments',
1162     'cust_refund'    => 'refunds',
1163   ;
1164    
1165   foreach my $table ( keys %financial_tables ) {
1166
1167     my @records = $self->$table();
1168
1169     if ( @records && ! $opt{'delete_financials'} ) {
1170       $dbh->rollback if $oldAutoCommit;
1171       return "Can't delete a customer with ". $financial_tables{$table};
1172     }
1173
1174     foreach my $record ( @records ) {
1175       my $error = $record->delete;
1176       if ( $error ) {
1177         $dbh->rollback if $oldAutoCommit;
1178         return "Error deleting ". $financial_tables{$table}. ": $error\n";
1179       }
1180     }
1181
1182   }
1183
1184   my @cust_pkg = $self->ncancelled_pkgs;
1185   if ( @cust_pkg ) {
1186     my $new_custnum = $opt{'new_custnum'};
1187     unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1188       $dbh->rollback if $oldAutoCommit;
1189       return "Invalid new customer number: $new_custnum";
1190     }
1191     foreach my $cust_pkg ( @cust_pkg ) {
1192       my %hash = $cust_pkg->hash;
1193       $hash{'custnum'} = $new_custnum;
1194       my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1195       my $error = $new_cust_pkg->replace($cust_pkg,
1196                                          options => { $cust_pkg->options },
1197                                         );
1198       if ( $error ) {
1199         $dbh->rollback if $oldAutoCommit;
1200         return $error;
1201       }
1202     }
1203   }
1204   my @cancelled_cust_pkg = $self->all_pkgs;
1205   foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1206     my $error = $cust_pkg->delete;
1207     if ( $error ) {
1208       $dbh->rollback if $oldAutoCommit;
1209       return $error;
1210     }
1211   }
1212
1213   #cust_tax_adjustment in financials?
1214   #cust_pay_pending?  ouch
1215   foreach my $table (qw(
1216     cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1217     cust_payby cust_location cust_main_note cust_tax_adjustment
1218     cust_pay_void cust_pay_batch queue cust_tax_exempt
1219   )) {
1220     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1221       my $error = $record->delete;
1222       if ( $error ) {
1223         $dbh->rollback if $oldAutoCommit;
1224         return $error;
1225       }
1226     }
1227   }
1228
1229   my $sth = $dbh->prepare(
1230     'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1231   ) or do {
1232     my $errstr = $dbh->errstr;
1233     $dbh->rollback if $oldAutoCommit;
1234     return $errstr;
1235   };
1236   $sth->execute($self->custnum) or do {
1237     my $errstr = $sth->errstr;
1238     $dbh->rollback if $oldAutoCommit;
1239     return $errstr;
1240   };
1241
1242   #tickets
1243
1244   my $ticket_dbh = '';
1245   if ($conf->config('ticket_system') eq 'RT_Internal') {
1246     $ticket_dbh = $dbh;
1247   } elsif ($conf->config('ticket_system') eq 'RT_External') {
1248     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1249     $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1250       #or die "RT_External DBI->connect error: $DBI::errstr\n";
1251   }
1252
1253   if ( $ticket_dbh ) {
1254
1255     my $ticket_sth = $ticket_dbh->prepare(
1256       'DELETE FROM Links WHERE Target = ?'
1257     ) or do {
1258       my $errstr = $ticket_dbh->errstr;
1259       $dbh->rollback if $oldAutoCommit;
1260       return $errstr;
1261     };
1262     $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1263       or do {
1264         my $errstr = $ticket_sth->errstr;
1265         $dbh->rollback if $oldAutoCommit;
1266         return $errstr;
1267       };
1268
1269     #check and see if the customer is the only link on the ticket, and
1270     #if so, set the ticket to deleted status in RT?
1271     #maybe someday, for now this will at least fix tickets not displaying
1272
1273   }
1274
1275   #delete the customer record
1276
1277   my $error = $self->SUPER::delete;
1278   if ( $error ) {
1279     $dbh->rollback if $oldAutoCommit;
1280     return $error;
1281   }
1282
1283   # cust_main exports!
1284
1285   #my $export_args = $options{'export_args'} || [];
1286
1287   my @part_export =
1288     map qsearch( 'part_export', {exportnum=>$_} ),
1289       $conf->config('cust_main-exports'); #, $agentnum
1290
1291   foreach my $part_export ( @part_export ) {
1292     my $error = $part_export->export_delete( $self ); #, @$export_args);
1293     if ( $error ) {
1294       $dbh->rollback if $oldAutoCommit;
1295       return "exporting to ". $part_export->exporttype.
1296              " (transaction rolled back): $error";
1297     }
1298   }
1299
1300   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1301   '';
1302
1303 }
1304
1305 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1306
1307 Replaces the OLD_RECORD with this one in the database.  If there is an error,
1308 returns the error, otherwise returns false.
1309
1310 To change the customer's address, set the pseudo-fields C<bill_location> and
1311 C<ship_location>.  The address will still only change if at least one of the
1312 address fields differs from the existing values.
1313
1314 INVOICING_LIST_ARYREF: If you pass an arrayref to this method, it will be
1315 set as the contact email address for a default contact with the same name as
1316 the customer.
1317
1318 Currently available options are: I<tax_exemption>, I<cust_payby_params>, 
1319 I<contact_params>, I<invoicing_list>, and I<move_pkgs>.
1320
1321 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1322 of tax names and exemption numbers.  FS::cust_main_exemption records will be
1323 deleted and inserted as appropriate.
1324
1325 I<cust_payby_params> and I<contact_params> can be hashrefs of named parameter
1326 groups (describing the customer's payment methods and contacts, respectively)
1327 in the style supported by L<FS::o2m_Common/process_o2m>. See L<FS::cust_payby>
1328 and L<FS::contact> for the fields these can contain.
1329
1330 I<invoicing_list> is a synonym for the INVOICING_LIST_ARYREF parameter, and
1331 should be used instead if possible.
1332
1333 If I<move_pkgs> is an arrayref, it will override the list of packages
1334 to be moved to the new address (see L<FS::cust_location/move_pkgs>.)
1335
1336 =cut
1337
1338 sub replace {
1339   my $self = shift;
1340
1341   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1342               ? shift
1343               : $self->replace_old;
1344
1345   my @param = @_;
1346
1347   warn "$me replace called\n"
1348     if $DEBUG;
1349
1350   my $curuser = $FS::CurrentUser::CurrentUser;
1351   return "You are not permitted to create complimentary accounts."
1352     if $self->complimentary eq 'Y'
1353     && $self->complimentary ne $old->complimentary
1354     && ! $curuser->access_right('Complimentary customer');
1355
1356   local($ignore_expired_card) = 1
1357     if $old->payby  =~ /^(CARD|DCRD)$/
1358     && $self->payby =~ /^(CARD|DCRD)$/
1359     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1360
1361   local($ignore_banned_card) = 1
1362     if (    $old->payby  =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1363          || $old->payby  =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1364     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1365
1366   if (    $self->payby =~ /^(CARD|DCRD)$/
1367        && $old->payinfo ne $self->payinfo
1368        && $old->paymask ne $self->paymask )
1369   {
1370     my $error = $self->check_payinfo_cardtype;
1371     return $error if $error;
1372   }
1373
1374   return "Invoicing locale is required"
1375     if $old->locale
1376     && ! $self->locale
1377     && $conf->exists('cust_main-require_locale');
1378
1379   return "You are not permitted to change customer invoicing terms."
1380     if $old->invoice_terms ne $self->invoice_terms
1381     && ! $curuser->access_right('Edit customer invoice terms');
1382
1383   local $SIG{HUP} = 'IGNORE';
1384   local $SIG{INT} = 'IGNORE';
1385   local $SIG{QUIT} = 'IGNORE';
1386   local $SIG{TERM} = 'IGNORE';
1387   local $SIG{TSTP} = 'IGNORE';
1388   local $SIG{PIPE} = 'IGNORE';
1389
1390   my $oldAutoCommit = $FS::UID::AutoCommit;
1391   local $FS::UID::AutoCommit = 0;
1392   my $dbh = dbh;
1393
1394   for my $l (qw(bill_location ship_location)) {
1395     #my $old_loc = $old->$l;
1396     my $new_loc = $self->$l or next;
1397
1398     # find the existing location if there is one
1399     $new_loc->set('custnum' => $self->custnum);
1400     my $error = $new_loc->find_or_insert;
1401     if ( $error ) {
1402       $dbh->rollback if $oldAutoCommit;
1403       return $error;
1404     }
1405     $self->set($l.'num', $new_loc->locationnum);
1406   } #for $l
1407
1408   my $invoicing_list;
1409   if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1410     warn "cust_main::replace: using deprecated invoicing list argument";
1411     $invoicing_list = shift @param;
1412   }
1413
1414   my %options = @param;
1415
1416   $invoicing_list ||= $options{invoicing_list};
1417
1418   my @contacts = map { $_->contact } $self->cust_contact;
1419   # find a contact that matches the customer's name
1420   my ($implicit_contact) = grep { $_->first eq $old->get('first')
1421                               and $_->last  eq $old->get('last') }
1422                             @contacts;
1423   $implicit_contact ||= FS::contact->new({
1424       'custnum'       => $self->custnum,
1425       'locationnum'   => $self->get('bill_locationnum'),
1426   });
1427
1428   # for any of these that are already contact emails, link to the existing
1429   # contact
1430   if ( $invoicing_list ) {
1431     my $email = '';
1432
1433     # kind of like process_m2m on these, except:
1434     # - the other side is two tables in a join
1435     # - and we might have to create new contact_emails
1436     # - and possibly a new contact
1437     # 
1438     # Find existing invoice emails that aren't on the implicit contact.
1439     # Any of these that are not on the new invoicing list will be removed.
1440     my %old_email_cust_contact;
1441     foreach my $cust_contact ($self->cust_contact) {
1442       next if !$cust_contact->invoice_dest;
1443       next if $cust_contact->contactnum == ($implicit_contact->contactnum || 0);
1444
1445       foreach my $contact_email ($cust_contact->contact->contact_email) {
1446         $old_email_cust_contact{ $contact_email->emailaddress } = $cust_contact;
1447       }
1448     }
1449
1450     foreach my $dest (@$invoicing_list) {
1451
1452       if ($dest eq 'POST') {
1453
1454         $self->set('postal_invoice', 'Y');
1455
1456       } elsif ( exists($old_email_cust_contact{$dest}) ) {
1457
1458         delete $old_email_cust_contact{$dest}; # don't need to remove it, then
1459
1460       } else {
1461
1462         # See if it belongs to some other contact; if so, link it.
1463         my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
1464         if ( $contact_email
1465              and $contact_email->contactnum != ($implicit_contact->contactnum || 0) ) {
1466           my $cust_contact = qsearchs('cust_contact', {
1467               contactnum  => $contact_email->contactnum,
1468               custnum     => $self->custnum,
1469           }) || FS::cust_contact->new({
1470               contactnum    => $contact_email->contactnum,
1471               custnum       => $self->custnum,
1472           });
1473           $cust_contact->set('invoice_dest', 'Y');
1474           my $error = $cust_contact->custcontactnum ?
1475                         $cust_contact->replace : $cust_contact->insert;
1476           if ( $error ) {
1477             $dbh->rollback if $oldAutoCommit;
1478             return "$error (linking to email address $dest)";
1479           }
1480
1481         } else {
1482           # This email address is not yet linked to any contact, so it will
1483           # be added to the implicit contact.
1484           $email .= ',' if length($email);
1485           $email .= $dest;
1486         }
1487       }
1488     }
1489
1490     foreach my $remove_dest (keys %old_email_cust_contact) {
1491       my $cust_contact = $old_email_cust_contact{$remove_dest};
1492       # These were not in the list of requested destinations, so take them off.
1493       $cust_contact->set('invoice_dest', '');
1494       my $error = $cust_contact->replace;
1495       if ( $error ) {
1496         $dbh->rollback if $oldAutoCommit;
1497         return "$error (unlinking email address $remove_dest)";
1498       }
1499     }
1500
1501     # make sure it keeps up with the changed customer name, if any
1502     $implicit_contact->set('last', $self->get('last'));
1503     $implicit_contact->set('first', $self->get('first'));
1504     $implicit_contact->set('emailaddress', $email);
1505     $implicit_contact->set('invoice_dest', 'Y');
1506     $implicit_contact->set('custnum', $self->custnum);
1507     my $i_cust_contact =
1508       qsearchs('cust_contact', {
1509                                  contactnum  => $implicit_contact->contactnum,
1510                                  custnum     => $self->custnum,
1511                                }
1512       );
1513     if ( $i_cust_contact ) {
1514       $implicit_contact->set($_, $i_cust_contact->$_)
1515         foreach qw( classnum selfservice_access comment );
1516     }
1517
1518     my $error;
1519     if ( $implicit_contact->contactnum ) {
1520       $error = $implicit_contact->replace;
1521     } elsif ( length($email) ) { # don't create a new contact if not needed
1522       $error = $implicit_contact->insert;
1523     }
1524
1525     if ( $error ) {
1526       $dbh->rollback if $oldAutoCommit;
1527       return "$error (adding email address $email)";
1528     }
1529
1530   }
1531
1532   # replace the customer record
1533   my $error = $self->SUPER::replace($old);
1534
1535   if ( $error ) {
1536     $dbh->rollback if $oldAutoCommit;
1537     return $error;
1538   }
1539
1540   # now move packages to the new service location
1541   $self->set('ship_location', ''); #flush cache
1542   if ( $old->ship_locationnum and # should only be null during upgrade...
1543        $old->ship_locationnum != $self->ship_locationnum ) {
1544     $error = $old->ship_location->move_to($self->ship_location, move_pkgs => $options{'move_pkgs'});
1545     if ( $error ) {
1546       $dbh->rollback if $oldAutoCommit;
1547       return $error;
1548     }
1549   }
1550   # don't move packages based on the billing location, but 
1551   # disable it if it's no longer in use
1552   if ( $old->bill_locationnum and
1553        $old->bill_locationnum != $self->bill_locationnum ) {
1554     $error = $old->bill_location->disable_if_unused;
1555     if ( $error ) {
1556       $dbh->rollback if $oldAutoCommit;
1557       return $error;
1558     }
1559   }
1560
1561   if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1562
1563     #this could be more efficient than deleting and re-inserting, if it matters
1564     foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1565       my $error = $cust_tag->delete;
1566       if ( $error ) {
1567         $dbh->rollback if $oldAutoCommit;
1568         return $error;
1569       }
1570     }
1571     foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1572       my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
1573                                         'custnum' => $self->custnum };
1574       my $error = $cust_tag->insert;
1575       if ( $error ) {
1576         $dbh->rollback if $oldAutoCommit;
1577         return $error;
1578       }
1579     }
1580
1581   }
1582
1583   my $tax_exemption = delete $options{'tax_exemption'};
1584   if ( $tax_exemption ) {
1585
1586     $tax_exemption = { map { $_ => '' } @$tax_exemption }
1587       if ref($tax_exemption) eq 'ARRAY';
1588
1589     my %cust_main_exemption =
1590       map { $_->taxname => $_ }
1591           qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1592
1593     foreach my $taxname ( keys %$tax_exemption ) {
1594
1595       if ( $cust_main_exemption{$taxname} && 
1596            $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1597          )
1598       {
1599         delete $cust_main_exemption{$taxname};
1600         next;
1601       }
1602
1603       my $cust_main_exemption = new FS::cust_main_exemption {
1604         'custnum'       => $self->custnum,
1605         'taxname'       => $taxname,
1606         'exempt_number' => $tax_exemption->{$taxname},
1607       };
1608       my $error = $cust_main_exemption->insert;
1609       if ( $error ) {
1610         $dbh->rollback if $oldAutoCommit;
1611         return "inserting cust_main_exemption (transaction rolled back): $error";
1612       }
1613     }
1614
1615     foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1616       my $error = $cust_main_exemption->delete;
1617       if ( $error ) {
1618         $dbh->rollback if $oldAutoCommit;
1619         return "deleting cust_main_exemption (transaction rolled back): $error";
1620       }
1621     }
1622
1623   }
1624
1625   if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1626
1627     my $error = $self->process_o2m(
1628       'table'         => 'cust_payby',
1629       'fields'        => FS::cust_payby->cgi_cust_payby_fields,
1630       'params'        => $cust_payby_params,
1631       'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1632     );
1633     if ( $error ) {
1634       $dbh->rollback if $oldAutoCommit;
1635       return $error;
1636     }
1637
1638   }
1639
1640   if ( my $contact_params = delete $options{'contact_params'} ) {
1641
1642     # this can potentially replace contacts that were created by the
1643     # invoicing list argument, but the UI shouldn't allow both of them
1644     # to be specified
1645
1646     my $error = $self->process_o2m(
1647       'table'         => 'contact',
1648       'fields'        => FS::contact->cgi_contact_fields,
1649       'params'        => $contact_params,
1650     );
1651     if ( $error ) {
1652       $dbh->rollback if $oldAutoCommit;
1653       return $error;
1654     }
1655
1656   }
1657
1658   unless ( $import || $skip_fuzzyfiles ) {
1659     $error = $self->queue_fuzzyfiles_update;
1660     if ( $error ) {
1661       $dbh->rollback if $oldAutoCommit;
1662       return "updating fuzzy search cache: $error";
1663     }
1664   }
1665
1666   # tax district update in cust_location
1667
1668   # cust_main exports!
1669
1670   my $export_args = $options{'export_args'} || [];
1671
1672   my @part_export =
1673     map qsearch( 'part_export', {exportnum=>$_} ),
1674       $conf->config('cust_main-exports'); #, $agentnum
1675
1676   foreach my $part_export ( @part_export ) {
1677     my $error = $part_export->export_replace( $self, $old, @$export_args);
1678     if ( $error ) {
1679       $dbh->rollback if $oldAutoCommit;
1680       return "exporting to ". $part_export->exporttype.
1681              " (transaction rolled back): $error";
1682     }
1683   }
1684
1685   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1686   '';
1687
1688 }
1689
1690 =item queue_fuzzyfiles_update
1691
1692 Used by insert & replace to update the fuzzy search cache
1693
1694 =cut
1695
1696 use FS::cust_main::Search;
1697 sub queue_fuzzyfiles_update {
1698   my $self = shift;
1699
1700   local $SIG{HUP} = 'IGNORE';
1701   local $SIG{INT} = 'IGNORE';
1702   local $SIG{QUIT} = 'IGNORE';
1703   local $SIG{TERM} = 'IGNORE';
1704   local $SIG{TSTP} = 'IGNORE';
1705   local $SIG{PIPE} = 'IGNORE';
1706
1707   my $oldAutoCommit = $FS::UID::AutoCommit;
1708   local $FS::UID::AutoCommit = 0;
1709   my $dbh = dbh;
1710
1711   foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1712     my $queue = new FS::queue { 
1713       'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1714     };
1715     my @args = "cust_main.$field", $self->get($field);
1716     my $error = $queue->insert( @args );
1717     if ( $error ) {
1718       $dbh->rollback if $oldAutoCommit;
1719       return "queueing job (transaction rolled back): $error";
1720     }
1721   }
1722
1723   my @locations = ();
1724   push @locations, $self->bill_location if $self->bill_locationnum;
1725   push @locations, $self->ship_location if @locations && $self->has_ship_address;
1726   foreach my $location (@locations) {
1727     my $queue = new FS::queue { 
1728       'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1729     };
1730     my @args = 'cust_location.address1', $location->address1;
1731     my $error = $queue->insert( @args );
1732     if ( $error ) {
1733       $dbh->rollback if $oldAutoCommit;
1734       return "queueing job (transaction rolled back): $error";
1735     }
1736   }
1737
1738   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1739   '';
1740
1741 }
1742
1743 =item check
1744
1745 Checks all fields to make sure this is a valid customer record.  If there is
1746 an error, returns the error, otherwise returns false.  Called by the insert
1747 and replace methods.
1748
1749 =cut
1750
1751 sub check {
1752   my $self = shift;
1753
1754   warn "$me check BEFORE: \n". $self->_dump
1755     if $DEBUG > 2;
1756
1757   my $error =
1758     $self->ut_numbern('custnum')
1759     || $self->ut_number('agentnum')
1760     || $self->ut_textn('agent_custid')
1761     || $self->ut_number('refnum')
1762     || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1763     || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1764     || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1765     || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1766     || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1767     || $self->ut_textn('custbatch')
1768     || $self->ut_name('last')
1769     || $self->ut_name('first')
1770     || $self->ut_snumbern('signupdate')
1771     || $self->ut_snumbern('birthdate')
1772     || $self->ut_namen('spouse_last')
1773     || $self->ut_namen('spouse_first')
1774     || $self->ut_snumbern('spouse_birthdate')
1775     || $self->ut_snumbern('anniversary_date')
1776     || $self->ut_textn('company')
1777     || $self->ut_textn('ship_company')
1778     || $self->ut_anything('comments')
1779     || $self->ut_numbern('referral_custnum')
1780     || $self->ut_textn('stateid')
1781     || $self->ut_textn('stateid_state')
1782     || $self->ut_textn('invoice_terms')
1783     || $self->ut_floatn('cdr_termination_percentage')
1784     || $self->ut_floatn('credit_limit')
1785     || $self->ut_numbern('billday')
1786     || $self->ut_numbern('prorate_day')
1787     || $self->ut_flag('force_prorate_day')
1788     || $self->ut_flag('edit_subject')
1789     || $self->ut_flag('calling_list_exempt')
1790     || $self->ut_flag('invoice_noemail')
1791     || $self->ut_flag('message_noemail')
1792     || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1793     || $self->ut_currencyn('currency')
1794     || $self->ut_textn('po_number')
1795     || $self->ut_enum('complimentary', [ '', 'Y' ])
1796     || $self->ut_flag('invoice_ship_address')
1797     || $self->ut_flag('invoice_dest')
1798   ;
1799
1800   foreach (qw(company ship_company)) {
1801     my $company = $self->get($_);
1802     $company =~ s/^\s+//; 
1803     $company =~ s/\s+$//; 
1804     $company =~ s/\s+/ /g;
1805     $self->set($_, $company);
1806   }
1807
1808   #barf.  need message catalogs.  i18n.  etc.
1809   $error .= "Please select an advertising source."
1810     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1811   return $error if $error;
1812
1813   my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1814     or return "Unknown agent";
1815
1816   if ( $self->currency ) {
1817     my $agent_currency = qsearchs( 'agent_currency', {
1818       'agentnum' => $agent->agentnum,
1819       'currency' => $self->currency,
1820     })
1821       or return "Agent ". $agent->agent.
1822                 " not permitted to offer ".  $self->currency. " invoicing";
1823   }
1824
1825   return "Unknown refnum"
1826     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1827
1828   return "Unknown referring custnum: ". $self->referral_custnum
1829     unless ! $self->referral_custnum 
1830            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1831
1832   if ( $self->ss eq '' ) {
1833     $self->ss('');
1834   } else {
1835     my $ss = $self->ss;
1836     $ss =~ s/\D//g;
1837     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1838       or return "Illegal social security number: ". $self->ss;
1839     $self->ss("$1-$2-$3");
1840   }
1841
1842   #turn off invoice_ship_address if ship & bill are the same
1843   if ($self->bill_locationnum eq $self->ship_locationnum) {
1844     $self->invoice_ship_address('');
1845   }
1846
1847   # cust_main_county verification now handled by cust_location check
1848
1849   $error =
1850        $self->ut_phonen('daytime', $self->country)
1851     || $self->ut_phonen('night',   $self->country)
1852     || $self->ut_phonen('fax',     $self->country)
1853     || $self->ut_phonen('mobile',  $self->country)
1854   ;
1855   return $error if $error;
1856
1857   if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1858        && ! $import
1859        && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1860      ) {
1861
1862     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1863                           ? 'Day Phone'
1864                           : FS::Msgcat::_gettext('daytime');
1865     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1866                         ? 'Night Phone'
1867                         : FS::Msgcat::_gettext('night');
1868
1869     my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1870                         ? 'Mobile Phone'
1871                         : FS::Msgcat::_gettext('mobile');
1872
1873     return "$daytime_label, $night_label or $mobile_label is required"
1874   
1875   }
1876
1877   return "Please select an invoicing locale"
1878     if ! $self->locale
1879     && ! $self->custnum
1880     && $conf->exists('cust_main-require_locale');
1881
1882   return "Please select a customer class"
1883     if ! $self->classnum
1884     && $conf->exists('cust_main-require_classnum');
1885
1886   foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1887     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1888     $self->$flag($1);
1889   }
1890
1891   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1892
1893   warn "$me check AFTER: \n". $self->_dump
1894     if $DEBUG > 2;
1895
1896   $self->SUPER::check;
1897 }
1898
1899 sub check_payinfo_cardtype {
1900   my $self = shift;
1901
1902   return '' unless $self->payby =~ /^(CARD|DCRD)$/;
1903
1904   my $payinfo = $self->payinfo;
1905   $payinfo =~ s/\D//g;
1906
1907   return '' if $self->tokenized($payinfo); #token
1908
1909   my %bop_card_types = map { $_=>1 } values %{ card_types() };
1910   my $cardtype = cardtype($payinfo);
1911
1912   return "$cardtype not accepted" unless $bop_card_types{$cardtype};
1913
1914   '';
1915
1916 }
1917
1918 =item replace_check
1919
1920 Additional checks for replace only.
1921
1922 =cut
1923
1924 sub replace_check {
1925   my ($new,$old) = @_;
1926   #preserve old value if global config is set
1927   if ($old && $conf->exists('invoice-ship_address')) {
1928     $new->invoice_ship_address($old->invoice_ship_address);
1929   }
1930   return '';
1931 }
1932
1933 =item addr_fields 
1934
1935 Returns a list of fields which have ship_ duplicates.
1936
1937 =cut
1938
1939 sub addr_fields {
1940   qw( last first company
1941       locationname
1942       address1 address2 city county state zip country
1943       latitude longitude
1944       daytime night fax mobile
1945     );
1946 }
1947
1948 =item has_ship_address
1949
1950 Returns true if this customer record has a separate shipping address.
1951
1952 =cut
1953
1954 sub has_ship_address {
1955   my $self = shift;
1956   $self->bill_locationnum != $self->ship_locationnum;
1957 }
1958
1959 =item location_hash
1960
1961 Returns a list of key/value pairs, with the following keys: address1, 
1962 adddress2, city, county, state, zip, country, district, and geocode.  The 
1963 shipping address is used if present.
1964
1965 =cut
1966
1967 sub location_hash {
1968   my $self = shift;
1969   $self->ship_location->location_hash;
1970 }
1971
1972 =item cust_location
1973
1974 Returns all locations (see L<FS::cust_location>) for this customer.
1975
1976 =cut
1977
1978 sub cust_location {
1979   my $self = shift;
1980   qsearch({
1981     'table'   => 'cust_location',
1982     'hashref' => { 'custnum'     => $self->custnum,
1983                    'prospectnum' => '',
1984                  },
1985     'order_by' => 'ORDER BY country, LOWER(state), LOWER(city), LOWER(county), LOWER(address1), LOWER(address2)',
1986   });
1987 }
1988
1989 =item cust_contact
1990
1991 Returns all contact associations (see L<FS::cust_contact>) for this customer.
1992
1993 =cut
1994
1995 sub cust_contact {
1996   my $self = shift;
1997   qsearch('cust_contact', { 'custnum' => $self->custnum } );
1998 }
1999
2000 =item cust_payby PAYBY
2001
2002 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2003
2004 If one or more PAYBY are specified, returns only payment methods for specified PAYBY.
2005 Does not validate PAYBY.
2006
2007 =cut
2008
2009 sub cust_payby {
2010   my $self = shift;
2011   my @payby = @_;
2012   my $search = {
2013     'table'    => 'cust_payby',
2014     'hashref'  => { 'custnum' => $self->custnum },
2015     'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
2016   };
2017   $search->{'extra_sql'} = ' AND payby IN ( '.
2018                                join(',', map dbh->quote($_), @payby).
2019                              ' ) '
2020     if @payby;
2021
2022   qsearch($search);
2023 }
2024
2025 =item has_cust_payby_auto
2026
2027 Returns true if customer has an automatic payment method ('CARD' or 'CHEK')
2028
2029 =cut
2030
2031 sub has_cust_payby_auto {
2032   my $self = shift;
2033   scalar( qsearch({ 
2034     'table'     => 'cust_payby',
2035     'hashref'   => { 'custnum' => $self->custnum, },
2036     'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2037     'order_by'  => 'LIMIT 1',
2038   }) );
2039
2040 }
2041
2042 =item unsuspend
2043
2044 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2045 and L<FS::cust_pkg>) for this customer, except those on hold.
2046
2047 Returns a list: an empty list on success or a list of errors.
2048
2049 =cut
2050
2051 sub unsuspend {
2052   my $self = shift;
2053   grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs(@_);
2054 }
2055
2056 =item release_hold
2057
2058 Unsuspends all suspended packages in the on-hold state (those without setup 
2059 dates) for this customer. 
2060
2061 =cut
2062
2063 sub release_hold {
2064   my $self = shift;
2065   grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2066 }
2067
2068 =item suspend
2069
2070 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2071
2072 Returns a list: an empty list on success or a list of errors.
2073
2074 =cut
2075
2076 sub suspend {
2077   my $self = shift;
2078   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2079 }
2080
2081 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2082
2083 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2084 PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref instead
2085 of a list of pkgparts; the hashref has the following keys:
2086
2087 =over 4
2088
2089 =item pkgparts - listref of pkgparts
2090
2091 =item (other options are passed to the suspend method)
2092
2093 =back
2094
2095
2096 Returns a list: an empty list on success or a list of errors.
2097
2098 =cut
2099
2100 sub suspend_if_pkgpart {
2101   my $self = shift;
2102   my (@pkgparts, %opt);
2103   if (ref($_[0]) eq 'HASH'){
2104     @pkgparts = @{$_[0]{pkgparts}};
2105     %opt      = %{$_[0]};
2106   }else{
2107     @pkgparts = @_;
2108   }
2109   grep { $_->suspend(%opt) }
2110     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2111       $self->unsuspended_pkgs;
2112 }
2113
2114 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2115
2116 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2117 given PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref
2118 instead of a list of pkgparts; the hashref has the following keys:
2119
2120 =over 4
2121
2122 =item pkgparts - listref of pkgparts
2123
2124 =item (other options are passed to the suspend method)
2125
2126 =back
2127
2128 Returns a list: an empty list on success or a list of errors.
2129
2130 =cut
2131
2132 sub suspend_unless_pkgpart {
2133   my $self = shift;
2134   my (@pkgparts, %opt);
2135   if (ref($_[0]) eq 'HASH'){
2136     @pkgparts = @{$_[0]{pkgparts}};
2137     %opt      = %{$_[0]};
2138   }else{
2139     @pkgparts = @_;
2140   }
2141   grep { $_->suspend(%opt) }
2142     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2143       $self->unsuspended_pkgs;
2144 }
2145
2146 =item cancel [ OPTION => VALUE ... ]
2147
2148 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2149 The cancellation time will be now.
2150
2151 =back
2152
2153 Always returns a list: an empty list on success or a list of errors.
2154
2155 =cut
2156
2157 sub cancel {
2158   my $self = shift;
2159   my %opt = @_;
2160   warn "$me cancel called on customer ". $self->custnum. " with options ".
2161        join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2162     if $DEBUG;
2163   my @pkgs = $self->ncancelled_pkgs;
2164
2165   $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2166 }
2167
2168 =item cancel_pkgs OPTIONS
2169
2170 Cancels a specified list of packages. OPTIONS can include:
2171
2172 =over 4
2173
2174 =item cust_pkg - an arrayref of the packages. Required.
2175
2176 =item time - the cancellation time, used to calculate final bills and
2177 unused-time credits if any. Will be passed through to the bill() and
2178 FS::cust_pkg::cancel() methods.
2179
2180 =item quiet - can be set true to supress email cancellation notices.
2181
2182 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a
2183 reasonnum of an existing reason, or passing a hashref will create a new reason.
2184 The hashref should have the following keys:
2185 typenum - Reason type (see L<FS::reason_type>)
2186 reason - Text of the new reason.
2187
2188 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2189 for the individual packages, parallel to the C<cust_pkg> argument. The
2190 reason and reason_otaker arguments will be taken from those objects.
2191
2192 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2193
2194 =item nobill - can be set true to skip billing if it might otherwise be done.
2195
2196 =cut
2197
2198 sub cancel_pkgs {
2199   my( $self, %opt ) = @_;
2200
2201   # we're going to cancel services, which is not reversible
2202   #   unless exports are suppressed
2203   die "cancel_pkgs cannot be run inside a transaction"
2204     if !$FS::UID::AutoCommit && !$FS::svc_Common::noexport_hack;
2205
2206   my $oldAutoCommit = $FS::UID::AutoCommit;
2207   local $FS::UID::AutoCommit = 0;
2208
2209   savepoint_create('cancel_pkgs');
2210
2211   return ( 'access denied' )
2212     unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2213
2214   if ( $opt{'ban'} ) {
2215
2216     foreach my $cust_payby ( $self->cust_payby ) {
2217
2218       #well, if they didn't get decrypted on search, then we don't have to 
2219       # try again... queue a job for the server that does have decryption
2220       # capability if we're in a paranoid multi-server implementation?
2221       return ( "Can't (yet) ban encrypted credit cards" )
2222         if $cust_payby->is_encrypted($cust_payby->payinfo);
2223
2224       my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2225       my $error = $ban->insert;
2226       if ($error) {
2227         savepoint_rollback_and_release('cancel_pkgs');
2228         dbh->rollback if $oldAutoCommit;
2229         return ( $error );
2230       }
2231
2232     }
2233
2234   }
2235
2236   my @pkgs = @{ delete $opt{'cust_pkg'} };
2237   my $cancel_time = $opt{'time'} || time;
2238
2239   # bill all packages first, so we don't lose usage, service counts for
2240   # bulk billing, etc.
2241   if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2242     $opt{nobill} = 1;
2243     my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2244                              'cancel'   => 1,
2245                              'time'     => $cancel_time );
2246     if ($error) {
2247       warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2248       savepoint_rollback_and_release('cancel_pkgs');
2249       dbh->rollback if $oldAutoCommit;
2250       return ( "Error billing during cancellation: $error" );
2251     }
2252   }
2253   savepoint_release('cancel_pkgs');
2254   dbh->commit if $oldAutoCommit;
2255
2256   my @errors;
2257   # try to cancel each service, the same way we would for individual packages,
2258   # but in cancel weight order.
2259   my @cust_svc = map { $_->cust_svc } @pkgs;
2260   my @sorted_cust_svc =
2261     map  { $_->[0] }
2262     sort { $a->[1] <=> $b->[1] }
2263     map  { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2264   ;
2265   warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2266     $self->custnum."\n"
2267     if $DEBUG;
2268   my $i = 0;
2269   foreach my $cust_svc (@sorted_cust_svc) {
2270     my $savepoint = 'cancel_pkgs_'.$i++;
2271     savepoint_create( $savepoint );
2272     my $part_svc = $cust_svc->part_svc;
2273     next if ( defined($part_svc) and $part_svc->preserve );
2274     # immediate cancel, no date option
2275     # transactionize individually
2276     my $error = try { $cust_svc->cancel } catch { $_ };
2277     if ( $error ) {
2278       savepoint_rollback_and_release( $savepoint );
2279       dbh->rollback if $oldAutoCommit;
2280       push @errors, $error;
2281     } else {
2282       savepoint_release( $savepoint );
2283       dbh->commit if $oldAutoCommit;
2284     }
2285   }
2286   if (@errors) {
2287     return @errors;
2288   }
2289
2290   warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2291     $self->custnum. "\n"
2292     if $DEBUG;
2293
2294   my @cprs;
2295   if ($opt{'cust_pkg_reason'}) {
2296     @cprs = @{ delete $opt{'cust_pkg_reason'} };
2297   }
2298   my $null_reason;
2299   $i = 0;
2300   foreach (@pkgs) {
2301     my %lopt = %opt;
2302     my $savepoint = 'cancel_pkgs_'.$i++;
2303     savepoint_create( $savepoint );
2304     if (@cprs) {
2305       my $cpr = shift @cprs;
2306       if ( $cpr ) {
2307         $lopt{'reason'}        = $cpr->reasonnum;
2308         $lopt{'reason_otaker'} = $cpr->otaker;
2309       } else {
2310         warn "no reason found when canceling package ".$_->pkgnum."\n";
2311         # we're not actually required to pass a reason to cust_pkg::cancel,
2312         # but if we're getting to this point, something has gone awry.
2313         $null_reason ||= FS::reason->new_or_existing(
2314           reason  => 'unknown reason',
2315           type    => 'Cancel Reason',
2316           class   => 'C',
2317         );
2318         $lopt{'reason'} = $null_reason->reasonnum;
2319         $lopt{'reason_otaker'} = $FS::CurrentUser::CurrentUser->username;
2320       }
2321     }
2322     my $error = $_->cancel(%lopt);
2323     if ( $error ) {
2324       savepoint_rollback_and_release( $savepoint );
2325       dbh->rollback if $oldAutoCommit;
2326       push @errors, 'pkgnum '.$_->pkgnum.': '.$error;
2327     } else {
2328       savepoint_release( $savepoint );
2329       dbh->commit if $oldAutoCommit;
2330     }
2331   }
2332
2333   return @errors;
2334 }
2335
2336 sub _banned_pay_hashref {
2337   die 'cust_main->_banned_pay_hashref deprecated';
2338
2339   my $self = shift;
2340
2341   my %payby2ban = (
2342     'CARD' => 'CARD',
2343     'DCRD' => 'CARD',
2344     'CHEK' => 'CHEK',
2345     'DCHK' => 'CHEK'
2346   );
2347
2348   {
2349     'payby'   => $payby2ban{$self->payby},
2350     'payinfo' => $self->payinfo,
2351     #don't ever *search* on reason! #'reason'  =>
2352   };
2353 }
2354
2355 =item notes
2356
2357 Returns all notes (see L<FS::cust_main_note>) for this customer.
2358
2359 =cut
2360
2361 sub notes {
2362   my($self,$orderby_classnum) = (shift,shift);
2363   my $orderby = "sticky DESC, _date DESC";
2364   $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2365   qsearch( 'cust_main_note',
2366            { 'custnum' => $self->custnum },
2367            '',
2368            "ORDER BY $orderby",
2369          );
2370 }
2371
2372 =item agent
2373
2374 Returns the agent (see L<FS::agent>) for this customer.
2375
2376 =item agent_name
2377
2378 Returns the agent name (see L<FS::agent>) for this customer.
2379
2380 =cut
2381
2382 sub agent_name {
2383   my $self = shift;
2384   $self->agent->agent;
2385 }
2386
2387 =item cust_tag
2388
2389 Returns any tags associated with this customer, as FS::cust_tag objects,
2390 or an empty list if there are no tags.
2391
2392 =item part_tag
2393
2394 Returns any tags associated with this customer, as FS::part_tag objects,
2395 or an empty list if there are no tags.
2396
2397 =cut
2398
2399 sub part_tag {
2400   my $self = shift;
2401   map $_->part_tag, $self->cust_tag; 
2402 }
2403
2404
2405 =item cust_class
2406
2407 Returns the customer class, as an FS::cust_class object, or the empty string
2408 if there is no customer class.
2409
2410 =item categoryname 
2411
2412 Returns the customer category name, or the empty string if there is no customer
2413 category.
2414
2415 =cut
2416
2417 sub categoryname {
2418   my $self = shift;
2419   my $cust_class = $self->cust_class;
2420   $cust_class
2421     ? $cust_class->categoryname
2422     : '';
2423 }
2424
2425 =item classname 
2426
2427 Returns the customer class name, or the empty string if there is no customer
2428 class.
2429
2430 =cut
2431
2432 sub classname {
2433   my $self = shift;
2434   my $cust_class = $self->cust_class;
2435   $cust_class
2436     ? $cust_class->classname
2437     : '';
2438 }
2439
2440 =item tax_status
2441
2442 Returns the external tax status, as an FS::tax_status object, or the empty 
2443 string if there is no tax status.
2444
2445 =cut
2446
2447 sub tax_status {
2448   my $self = shift;
2449   if ( $self->taxstatusnum ) {
2450     qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2451   } else {
2452     return '';
2453   } 
2454 }
2455
2456 =item taxstatus
2457
2458 Returns the tax status code if there is one.
2459
2460 =cut
2461
2462 sub taxstatus {
2463   my $self = shift;
2464   my $tax_status = $self->tax_status;
2465   $tax_status
2466     ? $tax_status->taxstatus
2467     : '';
2468 }
2469
2470 =item BILLING METHODS
2471
2472 Documentation on billing methods has been moved to
2473 L<FS::cust_main::Billing>.
2474
2475 =item REALTIME BILLING METHODS
2476
2477 Documentation on realtime billing methods has been moved to
2478 L<FS::cust_main::Billing_Realtime>.
2479
2480 =item remove_cvv
2481
2482 Removes the I<paycvv> field from the database directly.
2483
2484 If there is an error, returns the error, otherwise returns false.
2485
2486 DEPRECATED.  Use L</remove_cvv_from_cust_payby> instead.
2487
2488 =cut
2489
2490 sub remove_cvv {
2491   die 'cust_main->remove_cvv deprecated';
2492   my $self = shift;
2493   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2494     or return dbh->errstr;
2495   $sth->execute($self->custnum)
2496     or return $sth->errstr;
2497   $self->paycvv('');
2498   '';
2499 }
2500
2501 =item total_owed
2502
2503 Returns the total owed for this customer on all invoices
2504 (see L<FS::cust_bill/owed>).
2505
2506 =cut
2507
2508 sub total_owed {
2509   my $self = shift;
2510   $self->total_owed_date(2145859200); #12/31/2037
2511 }
2512
2513 =item total_owed_date TIME
2514
2515 Returns the total owed for this customer on all invoices with date earlier than
2516 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2517 see L<Time::Local> and L<Date::Parse> for conversion functions.
2518
2519 =cut
2520
2521 sub total_owed_date {
2522   my $self = shift;
2523   my $time = shift;
2524
2525   my $custnum = $self->custnum;
2526
2527   my $owed_sql = FS::cust_bill->owed_sql;
2528
2529   my $sql = "
2530     SELECT SUM($owed_sql) FROM cust_bill
2531       WHERE custnum = $custnum
2532         AND _date <= $time
2533   ";
2534
2535   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2536
2537 }
2538
2539 =item total_owed_pkgnum PKGNUM
2540
2541 Returns the total owed on all invoices for this customer's specific package
2542 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2543
2544 =cut
2545
2546 sub total_owed_pkgnum {
2547   my( $self, $pkgnum ) = @_;
2548   $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2549 }
2550
2551 =item total_owed_date_pkgnum TIME PKGNUM
2552
2553 Returns the total owed for this customer's specific package when using
2554 experimental package balances on all invoices with date earlier than
2555 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2556 see L<Time::Local> and L<Date::Parse> for conversion functions.
2557
2558 =cut
2559
2560 sub total_owed_date_pkgnum {
2561   my( $self, $time, $pkgnum ) = @_;
2562
2563   my $total_bill = 0;
2564   foreach my $cust_bill (
2565     grep { $_->_date <= $time }
2566       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2567   ) {
2568     $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2569   }
2570   sprintf( "%.2f", $total_bill );
2571
2572 }
2573
2574 =item total_paid
2575
2576 Returns the total amount of all payments.
2577
2578 =cut
2579
2580 sub total_paid {
2581   my $self = shift;
2582   my $total = 0;
2583   $total += $_->paid foreach $self->cust_pay;
2584   sprintf( "%.2f", $total );
2585 }
2586
2587 =item total_unapplied_credits
2588
2589 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2590 customer.  See L<FS::cust_credit/credited>.
2591
2592 =item total_credited
2593
2594 Old name for total_unapplied_credits.  Don't use.
2595
2596 =cut
2597
2598 sub total_credited {
2599   #carp "total_credited deprecated, use total_unapplied_credits";
2600   shift->total_unapplied_credits(@_);
2601 }
2602
2603 sub total_unapplied_credits {
2604   my $self = shift;
2605
2606   my $custnum = $self->custnum;
2607
2608   my $unapplied_sql = FS::cust_credit->unapplied_sql;
2609
2610   my $sql = "
2611     SELECT SUM($unapplied_sql) FROM cust_credit
2612       WHERE custnum = $custnum
2613   ";
2614
2615   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2616
2617 }
2618
2619 =item total_unapplied_credits_pkgnum PKGNUM
2620
2621 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2622 customer.  See L<FS::cust_credit/credited>.
2623
2624 =cut
2625
2626 sub total_unapplied_credits_pkgnum {
2627   my( $self, $pkgnum ) = @_;
2628   my $total_credit = 0;
2629   $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2630   sprintf( "%.2f", $total_credit );
2631 }
2632
2633
2634 =item total_unapplied_payments
2635
2636 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2637 See L<FS::cust_pay/unapplied>.
2638
2639 =cut
2640
2641 sub total_unapplied_payments {
2642   my $self = shift;
2643
2644   my $custnum = $self->custnum;
2645
2646   my $unapplied_sql = FS::cust_pay->unapplied_sql;
2647
2648   my $sql = "
2649     SELECT SUM($unapplied_sql) FROM cust_pay
2650       WHERE custnum = $custnum
2651   ";
2652
2653   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2654
2655 }
2656
2657 =item total_unapplied_payments_pkgnum PKGNUM
2658
2659 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2660 specific package when using experimental package balances.  See
2661 L<FS::cust_pay/unapplied>.
2662
2663 =cut
2664
2665 sub total_unapplied_payments_pkgnum {
2666   my( $self, $pkgnum ) = @_;
2667   my $total_unapplied = 0;
2668   $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2669   sprintf( "%.2f", $total_unapplied );
2670 }
2671
2672
2673 =item total_unapplied_refunds
2674
2675 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2676 customer.  See L<FS::cust_refund/unapplied>.
2677
2678 =cut
2679
2680 sub total_unapplied_refunds {
2681   my $self = shift;
2682   my $custnum = $self->custnum;
2683
2684   my $unapplied_sql = FS::cust_refund->unapplied_sql;
2685
2686   my $sql = "
2687     SELECT SUM($unapplied_sql) FROM cust_refund
2688       WHERE custnum = $custnum
2689   ";
2690
2691   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2692
2693 }
2694
2695 =item balance
2696
2697 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2698 total_unapplied_credits minus total_unapplied_payments).
2699
2700 =cut
2701
2702 sub balance {
2703   my $self = shift;
2704   $self->balance_date_range;
2705 }
2706
2707 =item balance_date TIME
2708
2709 Returns the balance for this customer, only considering invoices with date
2710 earlier than TIME (total_owed_date minus total_credited minus
2711 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
2712 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
2713 functions.
2714
2715 =cut
2716
2717 sub balance_date {
2718   my $self = shift;
2719   $self->balance_date_range(shift);
2720 }
2721
2722 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2723
2724 Returns the balance for this customer, optionally considering invoices with
2725 date earlier than START_TIME, and not later than END_TIME
2726 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2727
2728 Times are specified as SQL fragments or numeric
2729 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
2730 L<Date::Parse> for conversion functions.  The empty string can be passed
2731 to disable that time constraint completely.
2732
2733 Accepts the same options as L<balance_date_sql>:
2734
2735 =over 4
2736
2737 =item unapplied_date
2738
2739 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
2740
2741 =item cutoff
2742
2743 An absolute cutoff time.  Payments, credits, and refunds I<applied> after this 
2744 time will be ignored.  Note that START_TIME and END_TIME only limit the date 
2745 range for invoices and I<unapplied> payments, credits, and refunds.
2746
2747 =back
2748
2749 =cut
2750
2751 sub balance_date_range {
2752   my $self = shift;
2753   my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2754             ') FROM cust_main WHERE custnum='. $self->custnum;
2755   sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2756 }
2757
2758 =item balance_pkgnum PKGNUM
2759
2760 Returns the balance for this customer's specific package when using
2761 experimental package balances (total_owed plus total_unrefunded, minus
2762 total_unapplied_credits minus total_unapplied_payments)
2763
2764 =cut
2765
2766 sub balance_pkgnum {
2767   my( $self, $pkgnum ) = @_;
2768
2769   sprintf( "%.2f",
2770       $self->total_owed_pkgnum($pkgnum)
2771 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2772 #    + $self->total_unapplied_refunds_pkgnum($pkgnum)
2773     - $self->total_unapplied_credits_pkgnum($pkgnum)
2774     - $self->total_unapplied_payments_pkgnum($pkgnum)
2775   );
2776 }
2777
2778 =item payment_info
2779
2780 Returns a hash of useful information for making a payment.
2781
2782 =over 4
2783
2784 =item balance
2785
2786 Current balance.
2787
2788 =item payby
2789
2790 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2791 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2792 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2793
2794 =back
2795
2796 For credit card transactions:
2797
2798 =over 4
2799
2800 =item card_type 1
2801
2802 =item payname
2803
2804 Exact name on card
2805
2806 =back
2807
2808 For electronic check transactions:
2809
2810 =over 4
2811
2812 =item stateid_state
2813
2814 =back
2815
2816 =cut
2817
2818 #XXX i need to be updated for 4.x+
2819 sub payment_info {
2820   my $self = shift;
2821
2822   my %return = ();
2823
2824   $return{balance} = $self->balance;
2825
2826   $return{payname} = $self->payname
2827                      || ( $self->first. ' '. $self->get('last') );
2828
2829   $return{$_} = $self->bill_location->$_
2830     for qw(address1 address2 city state zip);
2831
2832   $return{payby} = $self->payby;
2833   $return{stateid_state} = $self->stateid_state;
2834
2835   if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2836     $return{card_type} = cardtype($self->payinfo);
2837     $return{payinfo} = $self->paymask;
2838
2839     @return{'month', 'year'} = $self->paydate_monthyear;
2840
2841   }
2842
2843   if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2844     my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2845     $return{payinfo1} = $payinfo1;
2846     $return{payinfo2} = $payinfo2;
2847     $return{paytype}  = $self->paytype;
2848     $return{paystate} = $self->paystate;
2849
2850   }
2851
2852   #doubleclick protection
2853   my $_date = time;
2854   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2855
2856   %return;
2857
2858 }
2859
2860 =item paydate_epoch
2861
2862 Returns the next payment expiration date for this customer. If they have no
2863 payment methods that will expire, returns 0.
2864
2865 =cut
2866
2867 sub paydate_epoch {
2868   my $self = shift;
2869   # filter out the ones that individually return 0, but then return 0 if
2870   # there are no results
2871   my @epochs = grep { $_ > 0 } map { $_->paydate_epoch } $self->cust_payby;
2872   min( @epochs ) || 0;
2873 }
2874
2875 =item paydate_epoch_sql
2876
2877 Returns an SQL expression to get the next payment expiration date for a
2878 customer. Returns 2143260000 (2037-12-01) if there are no payment expiration
2879 dates, so that it's safe to test for "will it expire before date X" for any
2880 date up to then.
2881
2882 =cut
2883
2884 sub paydate_epoch_sql {
2885   my $class = shift;
2886   my $paydate = FS::cust_payby->paydate_epoch_sql;
2887   "(SELECT COALESCE(MIN($paydate), 2143260000) FROM cust_payby WHERE cust_payby.custnum = cust_main.custnum)";
2888 }
2889
2890 sub tax_exemption {
2891   my( $self, $taxname ) = @_;
2892
2893   qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2894                                      'taxname' => $taxname,
2895                                    },
2896           );
2897 }
2898
2899 =item cust_main_exemption
2900
2901 =item invoicing_list
2902
2903 Returns a list of email addresses (with svcnum entries expanded), and the word
2904 'POST' if the customer receives postal invoices.
2905
2906 =cut
2907
2908 sub invoicing_list {
2909   my( $self, $arrayref ) = @_;
2910
2911   if ( $arrayref ) {
2912     warn "FS::cust_main::invoicing_list(ARRAY) is no longer supported.";
2913   }
2914   
2915   my @emails = $self->invoicing_list_emailonly;
2916   push @emails, 'POST' if $self->get('postal_invoice');
2917
2918   @emails;
2919 }
2920
2921 =item check_invoicing_list ARRAYREF
2922
2923 Checks these arguements as valid input for the invoicing_list method.  If there
2924 is an error, returns the error, otherwise returns false.
2925
2926 =cut
2927
2928 sub check_invoicing_list {
2929   my( $self, $arrayref ) = @_;
2930
2931   foreach my $address ( @$arrayref ) {
2932
2933     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2934       return 'Can\'t add FAX invoice destination with a blank FAX number.';
2935     }
2936
2937     my $cust_main_invoice = new FS::cust_main_invoice ( {
2938       'custnum' => $self->custnum,
2939       'dest'    => $address,
2940     } );
2941     my $error = $self->custnum
2942                 ? $cust_main_invoice->check
2943                 : $cust_main_invoice->checkdest
2944     ;
2945     return $error if $error;
2946
2947   }
2948
2949   return "Email address required"
2950     if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2951     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2952
2953   '';
2954 }
2955
2956 =item all_emails
2957
2958 Returns the email addresses of all accounts provisioned for this customer.
2959
2960 =cut
2961
2962 sub all_emails {
2963   my $self = shift;
2964   my %list;
2965   foreach my $cust_pkg ( $self->all_pkgs ) {
2966     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2967     my @svc_acct =
2968       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2969         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2970           @cust_svc;
2971     $list{$_}=1 foreach map { $_->email } @svc_acct;
2972   }
2973   keys %list;
2974 }
2975
2976 =item invoicing_list_addpost
2977
2978 Adds postal invoicing to this customer.  If this customer is already configured
2979 to receive postal invoices, does nothing.
2980
2981 =cut
2982
2983 sub invoicing_list_addpost {
2984   my $self = shift;
2985   if ( $self->get('postal_invoice') eq '' ) {
2986     $self->set('postal_invoice', 'Y');
2987     my $error = $self->replace;
2988     warn $error if $error; # should fail harder, but this is traditional
2989   }
2990 }
2991
2992 =item invoicing_list_emailonly
2993
2994 Returns the list of email invoice recipients (invoicing_list without non-email
2995 destinations such as POST and FAX).
2996
2997 =cut
2998
2999 sub invoicing_list_emailonly {
3000   my $self = shift;
3001   warn "$me invoicing_list_emailonly called"
3002     if $DEBUG;
3003   return () if !$self->custnum; # not yet inserted
3004   return map { $_->emailaddress }
3005     qsearch({
3006         table     => 'cust_contact',
3007         select    => 'emailaddress',
3008         addl_from => ' JOIN contact USING (contactnum) '.
3009                      ' JOIN contact_email USING (contactnum)',
3010         hashref   => { 'custnum' => $self->custnum, },
3011         extra_sql => q( AND cust_contact.invoice_dest = 'Y'),
3012     });
3013 }
3014
3015 =item invoicing_list_emailonly_scalar
3016
3017 Returns the list of email invoice recipients (invoicing_list without non-email
3018 destinations such as POST and FAX) as a comma-separated scalar.
3019
3020 =cut
3021
3022 sub invoicing_list_emailonly_scalar {
3023   my $self = shift;
3024   warn "$me invoicing_list_emailonly_scalar called"
3025     if $DEBUG;
3026   join(', ', $self->invoicing_list_emailonly);
3027 }
3028
3029 =item contact_list [ CLASSNUM, DEST_FLAG... ]
3030
3031 Returns a list of contacts (L<FS::contact> objects) for the customer.
3032
3033 If no arguments are given, returns all contacts for the customer.
3034
3035 Arguments may contain classnums.  When classnums are specified, only
3036 contacts with a matching cust_contact.classnum are returned.  When a
3037 classnum of 0 is given, contacts with a null classnum are also included.
3038
3039 Arguments may also contain the dest flag names 'invoice' or 'message'.
3040 If given, contacts who's invoice_dest and/or message_dest flags are
3041 not set to 'Y' will be excluded.
3042
3043 =cut
3044
3045 sub contact_list {
3046   my $self = shift;
3047   my $search = {
3048     table       => 'contact',
3049     select      => join(', ',(
3050                     'contact.*',
3051                     'cust_contact.invoice_dest',
3052                     'cust_contact.message_dest',
3053     )),
3054     addl_from   => ' JOIN cust_contact USING (contactnum)',
3055     extra_sql   => ' WHERE cust_contact.custnum = '.$self->custnum,
3056   };
3057
3058   # Bugfix notes:
3059   #   Calling methods were relying on this method to use invoice_dest to
3060   #   block e-mail messages.  Depending on parameters, this may or may not
3061   #   have actually happened.
3062   #
3063   #   The bug could cause this SQL to be used to filter e-mail addresses:
3064   #
3065   #   AND (
3066   #     cust_contact.classnums IN (1,2,3)
3067   #     OR cust_contact.invoice_dest = 'Y'
3068   #   )
3069   #
3070   #   improperly including everybody with the opt-in flag AND everybody
3071   #   in the contact classes
3072   #
3073   # Possibility to introduce new bugs:
3074   #   If callers of this method called it incorrectly, and didn't notice
3075   #   because it seemed to send the e-mails they wanted.
3076
3077   # WHERE ...
3078   # AND (
3079   #   (
3080   #     cust_contact.classnum IN (1,2,3)
3081   #     OR
3082   #     cust_contact.classnum IS NULL
3083   #   )
3084   #   AND (
3085   #     cust_contact.invoice_dest = 'Y'
3086   #     OR
3087   #     cust_contact.message_dest = 'Y'
3088   #   )
3089   # )
3090
3091   my @and_dest;
3092   my @or_classnum;
3093   my @classnums;
3094   for (@_) {
3095     if ($_ eq 'invoice' || $_ eq 'message') {
3096       push @and_dest, " cust_contact.${_}_dest = 'Y' ";
3097     } elsif ($_ eq '0') {
3098       push @or_classnum, ' cust_contact.classnum IS NULL ';
3099     } elsif ( /^\d+$/ ) {
3100       push @classnums, $_;
3101     } else {
3102       croak "bad classnum argument '$_'";
3103     }
3104   }
3105
3106   push @or_classnum, 'cust_contact.classnum IN ('.join(',',@classnums).')'
3107     if @classnums;
3108
3109   if (@or_classnum || @and_dest) { # catch, no arguments given
3110     $search->{extra_sql} .= ' AND ( ';
3111
3112       if (@or_classnum) {
3113         $search->{extra_sql} .= ' ( ';
3114         $search->{extra_sql} .= join ' OR ', map {" $_ "} @or_classnum;
3115         $search->{extra_sql} .= ' ) ';
3116         $search->{extra_sql} .= ' AND ( ' if @and_dest;
3117       }
3118
3119       if (@and_dest) {
3120         $search->{extra_sql} .= join ' OR ', map {" $_ "} @and_dest;
3121         $search->{extra_sql} .= ' ) ' if @or_classnum;
3122       }
3123
3124     $search->{extra_sql} .= ' ) ';
3125
3126     warn "\$extra_sql: $search->{extra_sql} \n" if $DEBUG;
3127   }
3128
3129   qsearch($search);
3130 }
3131
3132 =item contact_list_email [ CLASSNUM, ... ]
3133
3134 Same as L</contact_list>, but returns email destinations instead of contact
3135 objects.
3136
3137 =cut
3138
3139 sub contact_list_email {
3140   my $self = shift;
3141   my @contacts = $self->contact_list(@_);
3142   my @emails;
3143   foreach my $contact (@contacts) {
3144     foreach my $contact_email ($contact->contact_email) {
3145       push @emails,  Email::Address->new( $contact->firstlast,
3146                                           $contact_email->emailaddress
3147                      )->format;
3148     }
3149   }
3150   @emails;
3151 }
3152
3153 =item contact_list_email_destinations
3154
3155 Returns a list of emails and whether they receive invoices or messages destinations.
3156 { emailaddress => 'email.com', invoice => 'Y', message => '', }
3157
3158 =cut
3159
3160 sub contact_list_email_destinations {
3161   my $self = shift;
3162   warn "$me contact_list_email_destinations"
3163     if $DEBUG;
3164   return () if !$self->custnum; # not yet inserted
3165   return map { $_ }
3166     qsearch({
3167         table     => 'cust_contact',
3168         select    => 'emailaddress, cust_contact.invoice_dest as invoice, cust_contact.message_dest as message',
3169         addl_from => ' JOIN contact USING (contactnum) '.
3170                      ' JOIN contact_email USING (contactnum)',
3171         hashref   => { 'custnum' => $self->custnum, },
3172         order_by  => 'ORDER BY custcontactnum DESC',
3173         extra_sql => '',
3174     });
3175 }
3176
3177 =item contact_list_emailonly
3178
3179 Returns an array of hashes containing the emails. Used for displaying contact email field in advanced customer reports.
3180 [ { data => 'email.com', }, ]
3181
3182 =cut
3183
3184 sub contact_list_emailonly {
3185   my $self = shift;
3186   warn "$me contact_list_emailonly called"
3187     if $DEBUG;
3188   my @emails;
3189   foreach ($self->contact_list_email_destinations) {
3190     my $data = [
3191       {
3192         'data'  => $_->emailaddress,
3193       },
3194     ];
3195     push @emails, $data;
3196   }
3197   return \@emails;
3198 }
3199
3200 =item contact_list_cust_invoice_only
3201
3202 Returns an array of hashes containing cust_contact.invoice_dest.  Does this email receive invoices. Used for displaying email Invoice field in advanced customer reports.
3203 [ { data => 'Yes', }, ]
3204
3205 =cut
3206
3207 sub contact_list_cust_invoice_only {
3208   my $self = shift;
3209   warn "$me contact_list_cust_invoice_only called"
3210     if $DEBUG;
3211   my @emails;
3212   foreach ($self->contact_list_email_destinations) {
3213     my $invoice = $_->invoice ? 'Yes' : 'No';
3214     my $data = [
3215       {
3216         'data'  => $invoice,
3217       },
3218     ];
3219     push @emails, $data;
3220   }
3221   return \@emails;
3222 }
3223
3224 =item contact_list_cust_message_only
3225
3226 Returns an array of hashes containing cust_contact.message_dest.  Does this email receive message notifications. Used for displaying email Message field in advanced customer reports.
3227 [ { data => 'Yes', }, ]
3228
3229 =cut
3230
3231 sub contact_list_cust_message_only {
3232   my $self = shift;
3233   warn "$me contact_list_cust_message_only called"
3234     if $DEBUG;
3235   my @emails;
3236   foreach ($self->contact_list_email_destinations) {
3237     my $message = $_->message ? 'Yes' : 'No';
3238     my $data = [
3239       {
3240         'data'  => $message,
3241       },
3242     ];
3243     push @emails, $data;
3244   }
3245   return \@emails;
3246 }
3247
3248 =item referral_custnum_cust_main
3249
3250 Returns the customer who referred this customer (or the empty string, if
3251 this customer was not referred).
3252
3253 Note the difference with referral_cust_main method: This method,
3254 referral_custnum_cust_main returns the single customer (if any) who referred
3255 this customer, while referral_cust_main returns an array of customers referred
3256 BY this customer.
3257
3258 =cut
3259
3260 sub referral_custnum_cust_main {
3261   my $self = shift;
3262   return '' unless $self->referral_custnum;
3263   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3264 }
3265
3266 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3267
3268 Returns an array of customers referred by this customer (referral_custnum set
3269 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
3270 customers referred by customers referred by this customer and so on, inclusive.
3271 The default behavior is DEPTH 1 (no recursion).
3272
3273 Note the difference with referral_custnum_cust_main method: This method,
3274 referral_cust_main, returns an array of customers referred BY this customer,
3275 while referral_custnum_cust_main returns the single customer (if any) who
3276 referred this customer.
3277
3278 =cut
3279
3280 sub referral_cust_main {
3281   my $self = shift;
3282   my $depth = @_ ? shift : 1;
3283   my $exclude = @_ ? shift : {};
3284
3285   my @cust_main =
3286     map { $exclude->{$_->custnum}++; $_; }
3287       grep { ! $exclude->{ $_->custnum } }
3288         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3289
3290   if ( $depth > 1 ) {
3291     push @cust_main,
3292       map { $_->referral_cust_main($depth-1, $exclude) }
3293         @cust_main;
3294   }
3295
3296   @cust_main;
3297 }
3298
3299 =item referral_cust_main_ncancelled
3300
3301 Same as referral_cust_main, except only returns customers with uncancelled
3302 packages.
3303
3304 =cut
3305
3306 sub referral_cust_main_ncancelled {
3307   my $self = shift;
3308   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3309 }
3310
3311 =item referral_cust_pkg [ DEPTH ]
3312
3313 Like referral_cust_main, except returns a flat list of all unsuspended (and
3314 uncancelled) packages for each customer.  The number of items in this list may
3315 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3316
3317 =cut
3318
3319 sub referral_cust_pkg {
3320   my $self = shift;
3321   my $depth = @_ ? shift : 1;
3322
3323   map { $_->unsuspended_pkgs }
3324     grep { $_->unsuspended_pkgs }
3325       $self->referral_cust_main($depth);
3326 }
3327
3328 =item referring_cust_main
3329
3330 Returns the single cust_main record for the customer who referred this customer
3331 (referral_custnum), or false.
3332
3333 =cut
3334
3335 sub referring_cust_main {
3336   my $self = shift;
3337   return '' unless $self->referral_custnum;
3338   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3339 }
3340
3341 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3342
3343 Applies a credit to this customer.  If there is an error, returns the error,
3344 otherwise returns false.
3345
3346 REASON can be a text string, an FS::reason object, or a scalar reference to
3347 a reasonnum.  If a text string, it will be automatically inserted as a new
3348 reason, and a 'reason_type' option must be passed to indicate the
3349 FS::reason_type for the new reason.
3350
3351 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3352 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3353 I<commission_pkgnum>.
3354
3355 Any other options are passed to FS::cust_credit::insert.
3356
3357 =cut
3358
3359 sub credit {
3360   my( $self, $amount, $reason, %options ) = @_;
3361
3362   my $cust_credit = new FS::cust_credit {
3363     'custnum' => $self->custnum,
3364     'amount'  => $amount,
3365   };
3366
3367   if ( ref($reason) ) {
3368
3369     if ( ref($reason) eq 'SCALAR' ) {
3370       $cust_credit->reasonnum( $$reason );
3371     } else {
3372       $cust_credit->reasonnum( $reason->reasonnum );
3373     }
3374
3375   } else {
3376     $cust_credit->set('reason', $reason)
3377   }
3378
3379   $cust_credit->$_( delete $options{$_} )
3380     foreach grep exists($options{$_}),
3381               qw( addlinfo eventnum ),
3382               map "commission_$_", qw( agentnum salesnum pkgnum );
3383
3384   $cust_credit->insert(%options);
3385
3386 }
3387
3388 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3389
3390 Creates a one-time charge for this customer.  If there is an error, returns
3391 the error, otherwise returns false.
3392
3393 New-style, with a hashref of options:
3394
3395   my $error = $cust_main->charge(
3396                                   {
3397                                     'amount'     => 54.32,
3398                                     'quantity'   => 1,
3399                                     'start_date' => str2time('7/4/2009'),
3400                                     'pkg'        => 'Description',
3401                                     'comment'    => 'Comment',
3402                                     'additional' => [], #extra invoice detail
3403                                     'classnum'   => 1,  #pkg_class
3404
3405                                     'setuptax'   => '', # or 'Y' for tax exempt
3406
3407                                     'locationnum'=> 1234, # optional
3408
3409                                     #internal taxation
3410                                     'taxclass'   => 'Tax class',
3411
3412                                     #vendor taxation
3413                                     'taxproduct' => 2,  #part_pkg_taxproduct
3414                                     'override'   => {}, #XXX describe
3415
3416                                     #will be filled in with the new object
3417                                     'cust_pkg_ref' => \$cust_pkg,
3418
3419                                     #generate an invoice immediately
3420                                     'bill_now' => 0,
3421                                     'invoice_terms' => '', #with these terms
3422                                   }
3423                                 );
3424
3425 Old-style:
3426
3427   my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3428
3429 =cut
3430
3431 #super false laziness w/quotation::charge
3432 sub charge {
3433   my $self = shift;
3434   my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3435   my ( $pkg, $comment, $additional );
3436   my ( $setuptax, $taxclass );   #internal taxes
3437   my ( $taxproduct, $override ); #vendor (CCH) taxes
3438   my $no_auto = '';
3439   my $separate_bill = '';
3440   my $cust_pkg_ref = '';
3441   my ( $bill_now, $invoice_terms ) = ( 0, '' );
3442   my $locationnum;
3443   my ( $discountnum, $discountnum_amount, $discountnum_percent ) = ( '','','' );
3444   if ( ref( $_[0] ) ) {
3445     $amount     = $_[0]->{amount};
3446     $setup_cost = $_[0]->{setup_cost};
3447     $quantity   = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3448     $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3449     $no_auto    = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3450     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3451     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
3452                                            : '$'. sprintf("%.2f",$amount);
3453     $setuptax   = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3454     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3455     $classnum   = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3456     $additional = $_[0]->{additional} || [];
3457     $taxproduct = $_[0]->{taxproductnum};
3458     $override   = { '' => $_[0]->{tax_override} };
3459     $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3460     $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3461     $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3462     $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3463     $separate_bill = $_[0]->{separate_bill} || '';
3464     $discountnum = $_[0]->{setup_discountnum};
3465     $discountnum_amount = $_[0]->{setup_discountnum_amount};
3466     $discountnum_percent = $_[0]->{setup_discountnum_percent};
3467   } else { # yuck
3468     $amount     = shift;
3469     $setup_cost = '';
3470     $quantity   = 1;
3471     $start_date = '';
3472     $pkg        = @_ ? shift : 'One-time charge';
3473     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
3474     $setuptax   = '';
3475     $taxclass   = @_ ? shift : '';
3476     $additional = [];
3477   }
3478
3479   local $SIG{HUP} = 'IGNORE';
3480   local $SIG{INT} = 'IGNORE';
3481   local $SIG{QUIT} = 'IGNORE';
3482   local $SIG{TERM} = 'IGNORE';
3483   local $SIG{TSTP} = 'IGNORE';
3484   local $SIG{PIPE} = 'IGNORE';
3485
3486   my $oldAutoCommit = $FS::UID::AutoCommit;
3487   local $FS::UID::AutoCommit = 0;
3488   my $dbh = dbh;
3489
3490   my $part_pkg = new FS::part_pkg ( {
3491     'pkg'           => $pkg,
3492     'comment'       => $comment,
3493     'plan'          => 'flat',
3494     'freq'          => 0,
3495     'disabled'      => 'Y',
3496     'classnum'      => ( $classnum ? $classnum : '' ),
3497     'setuptax'      => $setuptax,
3498     'taxclass'      => $taxclass,
3499     'taxproductnum' => $taxproduct,
3500     'setup_cost'    => $setup_cost,
3501   } );
3502
3503   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3504                         ( 0 .. @$additional - 1 )
3505                   ),
3506                   'additional_count' => scalar(@$additional),
3507                   'setup_fee' => $amount,
3508                 );
3509
3510   my $error = $part_pkg->insert( options       => \%options,
3511                                  tax_overrides => $override,
3512                                );
3513   if ( $error ) {
3514     $dbh->rollback if $oldAutoCommit;
3515     return $error;
3516   }
3517
3518   my $pkgpart = $part_pkg->pkgpart;
3519   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3520   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3521     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3522     $error = $type_pkgs->insert;
3523     if ( $error ) {
3524       $dbh->rollback if $oldAutoCommit;
3525       return $error;
3526     }
3527   }
3528
3529   my $cust_pkg = new FS::cust_pkg ( {
3530     'custnum'                   => $self->custnum,
3531     'pkgpart'                   => $pkgpart,
3532     'quantity'                  => $quantity,
3533     'start_date'                => $start_date,
3534     'no_auto'                   => $no_auto,
3535     'separate_bill'             => $separate_bill,
3536     'locationnum'               => $locationnum,
3537     'setup_discountnum'         => $discountnum,
3538     'setup_discountnum_amount'  => $discountnum_amount,
3539     'setup_discountnum_percent' => $discountnum_percent,
3540   } );
3541
3542   $error = $cust_pkg->insert;
3543   if ( $error ) {
3544     $dbh->rollback if $oldAutoCommit;
3545     return $error;
3546   } elsif ( $cust_pkg_ref ) {
3547     ${$cust_pkg_ref} = $cust_pkg;
3548   }
3549
3550   if ( $bill_now ) {
3551     my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3552                              'pkg_list'      => [ $cust_pkg ],
3553                            );
3554     if ( $error ) {
3555       $dbh->rollback if $oldAutoCommit;
3556       return $error;
3557     }   
3558   }
3559
3560   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3561   return '';
3562
3563 }
3564
3565 #=item charge_postal_fee
3566 #
3567 #Applies a one time charge this customer.  If there is an error,
3568 #returns the error, returns the cust_pkg charge object or false
3569 #if there was no charge.
3570 #
3571 #=cut
3572 #
3573 # This should be a customer event.  For that to work requires that bill
3574 # also be a customer event.
3575
3576 sub charge_postal_fee {
3577   my $self = shift;
3578
3579   my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3580   return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3581
3582   my $cust_pkg = new FS::cust_pkg ( {
3583     'custnum'  => $self->custnum,
3584     'pkgpart'  => $pkgpart,
3585     'quantity' => 1,
3586   } );
3587
3588   my $error = $cust_pkg->insert;
3589   $error ? $error : $cust_pkg;
3590 }
3591
3592 =item num_cust_attachment_deleted
3593
3594 Returns the number of deleted attachments for this customer (see
3595 L<FS::num_cust_attachment>).
3596
3597 =cut
3598
3599 sub num_cust_attachments_deleted {
3600   my $self = shift;
3601   $self->scalar_sql(
3602     " SELECT COUNT(*) FROM cust_attachment ".
3603       " WHERE custnum = ? AND disabled IS NOT NULL AND disabled > 0",
3604     $self->custnum
3605   );
3606 }
3607
3608 =item max_invnum
3609
3610 Returns the most recent invnum (invoice number) for this customer.
3611
3612 =cut
3613
3614 sub max_invnum {
3615   my $self = shift;
3616   $self->scalar_sql(
3617     " SELECT MAX(invnum) FROM cust_bill WHERE custnum = ?",
3618     $self->custnum
3619   );
3620 }
3621
3622 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3623
3624 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3625
3626 Optionally, a list or hashref of additional arguments to the qsearch call can
3627 be passed.
3628
3629 =cut
3630
3631 sub cust_bill {
3632   my $self = shift;
3633   my $opt = ref($_[0]) ? shift : { @_ };
3634
3635   #return $self->num_cust_bill unless wantarray || keys %$opt;
3636
3637   $opt->{'table'} = 'cust_bill';
3638   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3639   $opt->{'hashref'}{'custnum'} = $self->custnum;
3640   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3641
3642   map { $_ } #behavior of sort undefined in scalar context
3643     sort { $a->_date <=> $b->_date }
3644       qsearch($opt);
3645 }
3646
3647 =item open_cust_bill
3648
3649 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3650 customer.
3651
3652 =cut
3653
3654 sub open_cust_bill {
3655   my $self = shift;
3656
3657   $self->cust_bill(
3658     'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3659     #@_
3660   );
3661
3662 }
3663
3664 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3665
3666 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3667
3668 =cut
3669
3670 sub legacy_cust_bill {
3671   my $self = shift;
3672
3673   #return $self->num_legacy_cust_bill unless wantarray;
3674
3675   map { $_ } #behavior of sort undefined in scalar context
3676     sort { $a->_date <=> $b->_date }
3677       qsearch({ 'table'    => 'legacy_cust_bill',
3678                 'hashref'  => { 'custnum' => $self->custnum, },
3679                 'order_by' => 'ORDER BY _date ASC',
3680              });
3681 }
3682
3683 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3684
3685 Returns all the statements (see L<FS::cust_statement>) for this customer.
3686
3687 Optionally, a list or hashref of additional arguments to the qsearch call can
3688 be passed.
3689
3690 =cut
3691
3692 =item cust_bill_void
3693
3694 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3695
3696 =cut
3697
3698 sub cust_bill_void {
3699   my $self = shift;
3700
3701   map { $_ } #return $self->num_cust_bill_void unless wantarray;
3702   sort { $a->_date <=> $b->_date }
3703     qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3704 }
3705
3706 sub cust_statement {
3707   my $self = shift;
3708   my $opt = ref($_[0]) ? shift : { @_ };
3709
3710   #return $self->num_cust_statement unless wantarray || keys %$opt;
3711
3712   $opt->{'table'} = 'cust_statement';
3713   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3714   $opt->{'hashref'}{'custnum'} = $self->custnum;
3715   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3716
3717   map { $_ } #behavior of sort undefined in scalar context
3718     sort { $a->_date <=> $b->_date }
3719       qsearch($opt);
3720 }
3721
3722 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3723
3724 Returns all services of type SVCDB (such as 'svc_acct') for this customer.  
3725
3726 Optionally, a list or hashref of additional arguments to the qsearch call can 
3727 be passed following the SVCDB.
3728
3729 =cut
3730
3731 sub svc_x {
3732   my $self = shift;
3733   my $svcdb = shift;
3734   if ( ! $svcdb =~ /^svc_\w+$/ ) {
3735     warn "$me svc_x requires a svcdb";
3736     return;
3737   }
3738   my $opt = ref($_[0]) ? shift : { @_ };
3739
3740   $opt->{'table'} = $svcdb;
3741   $opt->{'addl_from'} = 
3742     'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3743     ($opt->{'addl_from'} || '');
3744
3745   my $custnum = $self->custnum;
3746   $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3747   my $where = "cust_pkg.custnum = $custnum";
3748
3749   my $extra_sql = $opt->{'extra_sql'} || '';
3750   if ( keys %{ $opt->{'hashref'} } ) {
3751     $extra_sql = " AND $where $extra_sql";
3752   }
3753   else {
3754     if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3755       $extra_sql = "WHERE $where AND $1";
3756     }
3757     else {
3758       $extra_sql = "WHERE $where $extra_sql";
3759     }
3760   }
3761   $opt->{'extra_sql'} = $extra_sql;
3762
3763   qsearch($opt);
3764 }
3765
3766 # required for use as an eventtable; 
3767 sub svc_acct {
3768   my $self = shift;
3769   $self->svc_x('svc_acct', @_);
3770 }
3771
3772 =item cust_credit
3773
3774 Returns all the credits (see L<FS::cust_credit>) for this customer.
3775
3776 =cut
3777
3778 sub cust_credit {
3779   my $self = shift;
3780
3781   #return $self->num_cust_credit unless wantarray;
3782
3783   map { $_ } #behavior of sort undefined in scalar context
3784     sort { $a->_date <=> $b->_date }
3785       qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3786 }
3787
3788 =item cust_credit_pkgnum
3789
3790 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3791 package when using experimental package balances.
3792
3793 =cut
3794
3795 sub cust_credit_pkgnum {
3796   my( $self, $pkgnum ) = @_;
3797   map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3798   sort { $a->_date <=> $b->_date }
3799     qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3800                               'pkgnum'  => $pkgnum,
3801                             }
3802     );
3803 }
3804
3805 =item cust_credit_void
3806
3807 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3808
3809 =cut
3810
3811 sub cust_credit_void {
3812   my $self = shift;
3813   map { $_ }
3814   sort { $a->_date <=> $b->_date }
3815     qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3816 }
3817
3818 =item cust_pay
3819
3820 Returns all the payments (see L<FS::cust_pay>) for this customer.
3821
3822 =cut
3823
3824 sub cust_pay {
3825   my $self = shift;
3826   my $opt = ref($_[0]) ? shift : { @_ };
3827
3828   return $self->num_cust_pay unless wantarray || keys %$opt;
3829
3830   $opt->{'table'} = 'cust_pay';
3831   $opt->{'hashref'}{'custnum'} = $self->custnum;
3832
3833   map { $_ } #behavior of sort undefined in scalar context
3834     sort { $a->_date <=> $b->_date }
3835       qsearch($opt);
3836
3837 }
3838
3839 =item num_cust_pay
3840
3841 Returns the number of payments (see L<FS::cust_pay>) for this customer.  Also
3842 called automatically when the cust_pay method is used in a scalar context.
3843
3844 =cut
3845
3846 sub num_cust_pay {
3847   my $self = shift;
3848   my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3849   my $sth = dbh->prepare($sql) or die dbh->errstr;
3850   $sth->execute($self->custnum) or die $sth->errstr;