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