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