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