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