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