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