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