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