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