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