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