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