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