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