multiple, named taxes for a single region
[freeside.git] / FS / FS / cust_main.pm
1 package FS::cust_main;
2
3 use strict;
4 use vars qw( @ISA $conf $Debug $import );
5 use Safe;
6 use Carp;
7 BEGIN {
8   eval "use Time::Local;";
9   die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
10     if $] < 5.006 && !defined($Time::Local::VERSION);
11   eval "use Time::Local qw(timelocal timelocal_nocheck);";
12 }
13 use Date::Format;
14 #use Date::Manip;
15 use Business::CreditCard;
16 use FS::UID qw( getotaker dbh );
17 use FS::Record qw( qsearchs qsearch dbdef );
18 use FS::cust_pkg;
19 use FS::cust_bill;
20 use FS::cust_bill_pkg;
21 use FS::cust_pay;
22 use FS::cust_credit;
23 use FS::part_referral;
24 use FS::cust_main_county;
25 use FS::agent;
26 use FS::cust_main_invoice;
27 use FS::cust_credit_bill;
28 use FS::cust_bill_pay;
29 use FS::prepay_credit;
30 use FS::queue;
31 use FS::part_pkg;
32 use FS::part_bill_event;
33 use FS::cust_bill_event;
34 use FS::cust_tax_exempt;
35 use FS::type_pkgs;
36 use FS::Msgcat qw(gettext);
37
38 @ISA = qw( FS::Record );
39
40 $Debug = 0;
41 #$Debug = 1;
42
43 $import = 0;
44
45 #ask FS::UID to run this stuff for us later
46 $FS::UID::callback{'FS::cust_main'} = sub { 
47   $conf = new FS::Conf;
48   #yes, need it for stuff below (prolly should be cached)
49 };
50
51 sub _cache {
52   my $self = shift;
53   my ( $hashref, $cache ) = @_;
54   if ( exists $hashref->{'pkgnum'} ) {
55 #    #@{ $self->{'_pkgnum'} } = ();
56     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
57     $self->{'_pkgnum'} = $subcache;
58     #push @{ $self->{'_pkgnum'} },
59     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
60   }
61 }
62
63 =head1 NAME
64
65 FS::cust_main - Object methods for cust_main records
66
67 =head1 SYNOPSIS
68
69   use FS::cust_main;
70
71   $record = new FS::cust_main \%hash;
72   $record = new FS::cust_main { 'column' => 'value' };
73
74   $error = $record->insert;
75
76   $error = $new_record->replace($old_record);
77
78   $error = $record->delete;
79
80   $error = $record->check;
81
82   @cust_pkg = $record->all_pkgs;
83
84   @cust_pkg = $record->ncancelled_pkgs;
85
86   @cust_pkg = $record->suspended_pkgs;
87
88   $error = $record->bill;
89   $error = $record->bill %options;
90   $error = $record->bill 'time' => $time;
91
92   $error = $record->collect;
93   $error = $record->collect %options;
94   $error = $record->collect 'invoice_time'   => $time,
95                             'batch_card'     => 'yes',
96                             'report_badcard' => 'yes',
97                           ;
98
99 =head1 DESCRIPTION
100
101 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
102 FS::Record.  The following fields are currently supported:
103
104 =over 4
105
106 =item custnum - primary key (assigned automatically for new customers)
107
108 =item agentnum - agent (see L<FS::agent>)
109
110 =item refnum - Advertising source (see L<FS::part_referral>)
111
112 =item first - name
113
114 =item last - name
115
116 =item ss - social security number (optional)
117
118 =item company - (optional)
119
120 =item address1
121
122 =item address2 - (optional)
123
124 =item city
125
126 =item county - (optional, see L<FS::cust_main_county>)
127
128 =item state - (see L<FS::cust_main_county>)
129
130 =item zip
131
132 =item country - (see L<FS::cust_main_county>)
133
134 =item daytime - phone (optional)
135
136 =item night - phone (optional)
137
138 =item fax - phone (optional)
139
140 =item ship_first - name
141
142 =item ship_last - name
143
144 =item ship_company - (optional)
145
146 =item ship_address1
147
148 =item ship_address2 - (optional)
149
150 =item ship_city
151
152 =item ship_county - (optional, see L<FS::cust_main_county>)
153
154 =item ship_state - (see L<FS::cust_main_county>)
155
156 =item ship_zip
157
158 =item ship_country - (see L<FS::cust_main_county>)
159
160 =item ship_daytime - phone (optional)
161
162 =item ship_night - phone (optional)
163
164 =item ship_fax - phone (optional)
165
166 =item payby - `CARD' (credit cards), `CHEK' (electronic check), `LECB' (Phone bill billing), `BILL' (billing), `COMP' (free), or `PREPAY' (special billing type: applies a credit - see L<FS::prepay_credit> and sets billing type to BILL)
167
168 =item payinfo - card number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
169
170 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
171
172 =item payname - name on card or billing name
173
174 =item tax - tax exempt, empty or `Y'
175
176 =item otaker - order taker (assigned automatically, see L<FS::UID>)
177
178 =item comments - comments (optional)
179
180 =back
181
182 =head1 METHODS
183
184 =over 4
185
186 =item new HASHREF
187
188 Creates a new customer.  To add the customer to the database, see L<"insert">.
189
190 Note that this stores the hash reference, not a distinct copy of the hash it
191 points to.  You can ask the object for a copy with the I<hash> method.
192
193 =cut
194
195 sub table { 'cust_main'; }
196
197 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
198
199 Adds this customer to the database.  If there is an error, returns the error,
200 otherwise returns false.
201
202 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
203 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
204 are inserted atomicly, or the transaction is rolled back.  Passing an empty
205 hash reference is equivalent to not supplying this parameter.  There should be
206 a better explanation of this, but until then, here's an example:
207
208   use Tie::RefHash;
209   tie %hash, 'Tie::RefHash'; #this part is important
210   %hash = (
211     $cust_pkg => [ $svc_acct ],
212     ...
213   );
214   $cust_main->insert( \%hash );
215
216 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
217 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
218 expected and rollback the entire transaction; it is not necessary to call 
219 check_invoicing_list first.  The invoicing_list is set after the records in the
220 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
221 invoicing_list destination to the newly-created svc_acct.  Here's an example:
222
223   $cust_main->insert( {}, [ $email, 'POST' ] );
224
225 Currently available options are: I<noexport>
226
227 If I<noexport> is set true, no provisioning jobs (exports) are scheduled.
228 (You can schedule them later with the B<reexport> method.)
229
230 =cut
231
232 sub insert {
233   my $self = shift;
234   my $cust_pkgs = @_ ? shift : {};
235   my $invoicing_list = @_ ? shift : '';
236   my %options = @_;
237
238   local $SIG{HUP} = 'IGNORE';
239   local $SIG{INT} = 'IGNORE';
240   local $SIG{QUIT} = 'IGNORE';
241   local $SIG{TERM} = 'IGNORE';
242   local $SIG{TSTP} = 'IGNORE';
243   local $SIG{PIPE} = 'IGNORE';
244
245   my $oldAutoCommit = $FS::UID::AutoCommit;
246   local $FS::UID::AutoCommit = 0;
247   my $dbh = dbh;
248
249   my $amount = 0;
250   my $seconds = 0;
251   if ( $self->payby eq 'PREPAY' ) {
252     $self->payby('BILL');
253     my $prepay_credit = qsearchs(
254       'prepay_credit',
255       { 'identifier' => $self->payinfo },
256       '',
257       'FOR UPDATE'
258     );
259     warn "WARNING: can't find pre-found prepay_credit: ". $self->payinfo
260       unless $prepay_credit;
261     $amount = $prepay_credit->amount;
262     $seconds = $prepay_credit->seconds;
263     my $error = $prepay_credit->delete;
264     if ( $error ) {
265       $dbh->rollback if $oldAutoCommit;
266       return "removing prepay_credit (transaction rolled back): $error";
267     }
268   }
269
270   my $error = $self->SUPER::insert;
271   if ( $error ) {
272     $dbh->rollback if $oldAutoCommit;
273     #return "inserting cust_main record (transaction rolled back): $error";
274     return $error;
275   }
276
277   # invoicing list
278   if ( $invoicing_list ) {
279     $error = $self->check_invoicing_list( $invoicing_list );
280     if ( $error ) {
281       $dbh->rollback if $oldAutoCommit;
282       return "checking invoicing_list (transaction rolled back): $error";
283     }
284     $self->invoicing_list( $invoicing_list );
285   }
286
287   # packages
288   local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
289   foreach my $cust_pkg ( keys %$cust_pkgs ) {
290     $cust_pkg->custnum( $self->custnum );
291     $error = $cust_pkg->insert;
292     if ( $error ) {
293       $dbh->rollback if $oldAutoCommit;
294       return "inserting cust_pkg (transaction rolled back): $error";
295     }
296     foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
297       $svc_something->pkgnum( $cust_pkg->pkgnum );
298       if ( $seconds && $svc_something->isa('FS::svc_acct') ) {
299         $svc_something->seconds( $svc_something->seconds + $seconds );
300         $seconds = 0;
301       }
302       $error = $svc_something->insert;
303       if ( $error ) {
304         $dbh->rollback if $oldAutoCommit;
305         #return "inserting svc_ (transaction rolled back): $error";
306         return $error;
307       }
308     }
309   }
310
311   if ( $seconds ) {
312     $dbh->rollback if $oldAutoCommit;
313     return "No svc_acct record to apply pre-paid time";
314   }
315
316   if ( $amount ) {
317     my $cust_credit = new FS::cust_credit {
318       'custnum' => $self->custnum,
319       'amount'  => $amount,
320     };
321     $error = $cust_credit->insert;
322     if ( $error ) {
323       $dbh->rollback if $oldAutoCommit;
324       return "inserting credit (transaction rolled back): $error";
325     }
326   }
327
328   $error = $self->queue_fuzzyfiles_update;
329   if ( $error ) {
330     $dbh->rollback if $oldAutoCommit;
331     return "updating fuzzy search cache: $error";
332   }
333
334   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
335   '';
336
337 }
338
339 =item delete NEW_CUSTNUM
340
341 This deletes the customer.  If there is an error, returns the error, otherwise
342 returns false.
343
344 This will completely remove all traces of the customer record.  This is not
345 what you want when a customer cancels service; for that, cancel all of the
346 customer's packages (see L</cancel>).
347
348 If the customer has any uncancelled packages, you need to pass a new (valid)
349 customer number for those packages to be transferred to.  Cancelled packages
350 will be deleted.  Did I mention that this is NOT what you want when a customer
351 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
352
353 You can't delete a customer with invoices (see L<FS::cust_bill>),
354 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
355 refunds (see L<FS::cust_refund>).
356
357 =cut
358
359 sub delete {
360   my $self = shift;
361
362   local $SIG{HUP} = 'IGNORE';
363   local $SIG{INT} = 'IGNORE';
364   local $SIG{QUIT} = 'IGNORE';
365   local $SIG{TERM} = 'IGNORE';
366   local $SIG{TSTP} = 'IGNORE';
367   local $SIG{PIPE} = 'IGNORE';
368
369   my $oldAutoCommit = $FS::UID::AutoCommit;
370   local $FS::UID::AutoCommit = 0;
371   my $dbh = dbh;
372
373   if ( qsearch( 'cust_bill', { 'custnum' => $self->custnum } ) ) {
374     $dbh->rollback if $oldAutoCommit;
375     return "Can't delete a customer with invoices";
376   }
377   if ( qsearch( 'cust_credit', { 'custnum' => $self->custnum } ) ) {
378     $dbh->rollback if $oldAutoCommit;
379     return "Can't delete a customer with credits";
380   }
381   if ( qsearch( 'cust_pay', { 'custnum' => $self->custnum } ) ) {
382     $dbh->rollback if $oldAutoCommit;
383     return "Can't delete a customer with payments";
384   }
385   if ( qsearch( 'cust_refund', { 'custnum' => $self->custnum } ) ) {
386     $dbh->rollback if $oldAutoCommit;
387     return "Can't delete a customer with refunds";
388   }
389
390   my @cust_pkg = $self->ncancelled_pkgs;
391   if ( @cust_pkg ) {
392     my $new_custnum = shift;
393     unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
394       $dbh->rollback if $oldAutoCommit;
395       return "Invalid new customer number: $new_custnum";
396     }
397     foreach my $cust_pkg ( @cust_pkg ) {
398       my %hash = $cust_pkg->hash;
399       $hash{'custnum'} = $new_custnum;
400       my $new_cust_pkg = new FS::cust_pkg ( \%hash );
401       my $error = $new_cust_pkg->replace($cust_pkg);
402       if ( $error ) {
403         $dbh->rollback if $oldAutoCommit;
404         return $error;
405       }
406     }
407   }
408   my @cancelled_cust_pkg = $self->all_pkgs;
409   foreach my $cust_pkg ( @cancelled_cust_pkg ) {
410     my $error = $cust_pkg->delete;
411     if ( $error ) {
412       $dbh->rollback if $oldAutoCommit;
413       return $error;
414     }
415   }
416
417   foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
418     qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
419   ) {
420     my $error = $cust_main_invoice->delete;
421     if ( $error ) {
422       $dbh->rollback if $oldAutoCommit;
423       return $error;
424     }
425   }
426
427   my $error = $self->SUPER::delete;
428   if ( $error ) {
429     $dbh->rollback if $oldAutoCommit;
430     return $error;
431   }
432
433   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
434   '';
435
436 }
437
438 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
439
440 Replaces the OLD_RECORD with this one in the database.  If there is an error,
441 returns the error, otherwise returns false.
442
443 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
444 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
445 expected and rollback the entire transaction; it is not necessary to call 
446 check_invoicing_list first.  Here's an example:
447
448   $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
449
450 =cut
451
452 sub replace {
453   my $self = shift;
454   my $old = shift;
455   my @param = @_;
456
457   local $SIG{HUP} = 'IGNORE';
458   local $SIG{INT} = 'IGNORE';
459   local $SIG{QUIT} = 'IGNORE';
460   local $SIG{TERM} = 'IGNORE';
461   local $SIG{TSTP} = 'IGNORE';
462   local $SIG{PIPE} = 'IGNORE';
463
464   if ( $self->payby eq 'COMP' && $self->payby ne $old->payby
465        && $conf->config('users-allow_comp')                  ) {
466     return "You are not permitted to create complimentary accounts."
467       unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
468   }
469
470   my $oldAutoCommit = $FS::UID::AutoCommit;
471   local $FS::UID::AutoCommit = 0;
472   my $dbh = dbh;
473
474   my $error = $self->SUPER::replace($old);
475
476   if ( $error ) {
477     $dbh->rollback if $oldAutoCommit;
478     return $error;
479   }
480
481   if ( @param ) { # INVOICING_LIST_ARYREF
482     my $invoicing_list = shift @param;
483     $error = $self->check_invoicing_list( $invoicing_list );
484     if ( $error ) {
485       $dbh->rollback if $oldAutoCommit;
486       return $error;
487     }
488     $self->invoicing_list( $invoicing_list );
489   }
490
491   if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
492        grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
493     # card/check/lec info has changed, want to retry realtime_ invoice events
494     my $error = $self->retry_realtime;
495     if ( $error ) {
496       $dbh->rollback if $oldAutoCommit;
497       return $error;
498     }
499   }
500
501   $error = $self->queue_fuzzyfiles_update;
502   if ( $error ) {
503     $dbh->rollback if $oldAutoCommit;
504     return "updating fuzzy search cache: $error";
505   }
506
507   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
508   '';
509
510 }
511
512 =item queue_fuzzyfiles_update
513
514 Used by insert & replace to update the fuzzy search cache
515
516 =cut
517
518 sub queue_fuzzyfiles_update {
519   my $self = shift;
520
521   local $SIG{HUP} = 'IGNORE';
522   local $SIG{INT} = 'IGNORE';
523   local $SIG{QUIT} = 'IGNORE';
524   local $SIG{TERM} = 'IGNORE';
525   local $SIG{TSTP} = 'IGNORE';
526   local $SIG{PIPE} = 'IGNORE';
527
528   my $oldAutoCommit = $FS::UID::AutoCommit;
529   local $FS::UID::AutoCommit = 0;
530   my $dbh = dbh;
531
532   my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
533   my $error = $queue->insert($self->getfield('last'), $self->company);
534   if ( $error ) {
535     $dbh->rollback if $oldAutoCommit;
536     return "queueing job (transaction rolled back): $error";
537   }
538
539   if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
540     $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
541     $error = $queue->insert($self->getfield('ship_last'), $self->ship_company);
542     if ( $error ) {
543       $dbh->rollback if $oldAutoCommit;
544       return "queueing job (transaction rolled back): $error";
545     }
546   }
547
548   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
549   '';
550
551 }
552
553 =item check
554
555 Checks all fields to make sure this is a valid customer record.  If there is
556 an error, returns the error, otherwise returns false.  Called by the insert
557 and repalce methods.
558
559 =cut
560
561 sub check {
562   my $self = shift;
563
564   #warn "BEFORE: \n". $self->_dump;
565
566   my $error =
567     $self->ut_numbern('custnum')
568     || $self->ut_number('agentnum')
569     || $self->ut_number('refnum')
570     || $self->ut_name('last')
571     || $self->ut_name('first')
572     || $self->ut_textn('company')
573     || $self->ut_text('address1')
574     || $self->ut_textn('address2')
575     || $self->ut_text('city')
576     || $self->ut_textn('county')
577     || $self->ut_textn('state')
578     || $self->ut_country('country')
579     || $self->ut_anything('comments')
580     || $self->ut_numbern('referral_custnum')
581   ;
582   #barf.  need message catalogs.  i18n.  etc.
583   $error .= "Please select an advertising source."
584     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
585   return $error if $error;
586
587   return "Unknown agent"
588     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
589
590   return "Unknown refnum"
591     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
592
593   return "Unknown referring custnum ". $self->referral_custnum
594     unless ! $self->referral_custnum 
595            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
596
597   if ( $self->ss eq '' ) {
598     $self->ss('');
599   } else {
600     my $ss = $self->ss;
601     $ss =~ s/\D//g;
602     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
603       or return "Illegal social security number: ". $self->ss;
604     $self->ss("$1-$2-$3");
605   }
606
607
608 # bad idea to disable, causes billing to fail because of no tax rates later
609 #  unless ( $import ) {
610     unless ( qsearch('cust_main_county', {
611       'country' => $self->country,
612       'state'   => '',
613      } ) ) {
614       return "Unknown state/county/country: ".
615         $self->state. "/". $self->county. "/". $self->country
616         unless qsearch('cust_main_county',{
617           'state'   => $self->state,
618           'county'  => $self->county,
619           'country' => $self->country,
620         } );
621     }
622 #  }
623
624   $error =
625     $self->ut_phonen('daytime', $self->country)
626     || $self->ut_phonen('night', $self->country)
627     || $self->ut_phonen('fax', $self->country)
628     || $self->ut_zip('zip', $self->country)
629   ;
630   return $error if $error;
631
632   my @addfields = qw(
633     last first company address1 address2 city county state zip
634     country daytime night fax
635   );
636
637   if ( defined $self->dbdef_table->column('ship_last') ) {
638     if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
639                        @addfields )
640          && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
641        )
642     {
643       my $error =
644         $self->ut_name('ship_last')
645         || $self->ut_name('ship_first')
646         || $self->ut_textn('ship_company')
647         || $self->ut_text('ship_address1')
648         || $self->ut_textn('ship_address2')
649         || $self->ut_text('ship_city')
650         || $self->ut_textn('ship_county')
651         || $self->ut_textn('ship_state')
652         || $self->ut_country('ship_country')
653       ;
654       return $error if $error;
655
656       #false laziness with above
657       unless ( qsearchs('cust_main_county', {
658         'country' => $self->ship_country,
659         'state'   => '',
660        } ) ) {
661         return "Unknown ship_state/ship_county/ship_country: ".
662           $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
663           unless qsearchs('cust_main_county',{
664             'state'   => $self->ship_state,
665             'county'  => $self->ship_county,
666             'country' => $self->ship_country,
667           } );
668       }
669       #eofalse
670
671       $error =
672         $self->ut_phonen('ship_daytime', $self->ship_country)
673         || $self->ut_phonen('ship_night', $self->ship_country)
674         || $self->ut_phonen('ship_fax', $self->ship_country)
675         || $self->ut_zip('ship_zip', $self->ship_country)
676       ;
677       return $error if $error;
678
679     } else { # ship_ info eq billing info, so don't store dup info in database
680       $self->setfield("ship_$_", '')
681         foreach qw( last first company address1 address2 city county state zip
682                     country daytime night fax );
683     }
684   }
685
686   $self->payby =~ /^(CARD|CHEK|LECB|BILL|COMP|PREPAY)$/
687     or return "Illegal payby: ". $self->payby;
688   $self->payby($1);
689
690   if ( $self->payby eq 'CARD' ) {
691
692     my $payinfo = $self->payinfo;
693     $payinfo =~ s/\D//g;
694     $payinfo =~ /^(\d{13,16})$/
695       or return gettext('invalid_card'); # . ": ". $self->payinfo;
696     $payinfo = $1;
697     $self->payinfo($payinfo);
698     validate($payinfo)
699       or return gettext('invalid_card'); # . ": ". $self->payinfo;
700     return gettext('unknown_card_type')
701       if cardtype($self->payinfo) eq "Unknown";
702
703   } elsif ( $self->payby eq 'CHEK' ) {
704
705     my $payinfo = $self->payinfo;
706     $payinfo =~ s/[^\d\@]//g;
707     $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
708     $payinfo = "$1\@$2";
709     $self->payinfo($payinfo);
710
711   } elsif ( $self->payby eq 'LECB' ) {
712
713     my $payinfo = $self->payinfo;
714     $payinfo =~ s/\D//g;
715     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
716     $payinfo = $1;
717     $self->payinfo($payinfo);
718
719   } elsif ( $self->payby eq 'BILL' ) {
720
721     $error = $self->ut_textn('payinfo');
722     return "Illegal P.O. number: ". $self->payinfo if $error;
723
724   } elsif ( $self->payby eq 'COMP' ) {
725
726     if ( !$self->custnum && $conf->config('users-allow_comp') ) {
727       return "You are not permitted to create complimentary accounts."
728         unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
729     }
730
731     $error = $self->ut_textn('payinfo');
732     return "Illegal comp account issuer: ". $self->payinfo if $error;
733
734   } elsif ( $self->payby eq 'PREPAY' ) {
735
736     my $payinfo = $self->payinfo;
737     $payinfo =~ s/\W//g; #anything else would just confuse things
738     $self->payinfo($payinfo);
739     $error = $self->ut_alpha('payinfo');
740     return "Illegal prepayment identifier: ". $self->payinfo if $error;
741     return "Unknown prepayment identifier"
742       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
743
744   }
745
746   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
747     return "Expriation date required"
748       unless $self->payby =~ /^(BILL|PREPAY|CHEK|LECB)$/;
749     $self->paydate('');
750   } else {
751     $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/
752       or return "Illegal expiration date: ". $self->paydate;
753     my $y = length($2) == 4 ? $2 : "20$2";
754     $self->paydate("$y-$1-01");
755     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
756     return gettext('expired_card')
757       if !$import && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
758   }
759
760   if ( $self->payname eq '' && $self->payby ne 'CHEK' &&
761        ( ! $conf->exists('require_cardname') || $self->payby ne 'CARD' ) ) {
762     $self->payname( $self->first. " ". $self->getfield('last') );
763   } else {
764     $self->payname =~ /^([\w \,\.\-\']+)$/
765       or return gettext('illegal_name'). " payname: ". $self->payname;
766     $self->payname($1);
767   }
768
769   $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
770   $self->tax($1);
771
772   $self->otaker(getotaker);
773
774   #warn "AFTER: \n". $self->_dump;
775
776   ''; #no error
777 }
778
779 =item all_pkgs
780
781 Returns all packages (see L<FS::cust_pkg>) for this customer.
782
783 =cut
784
785 sub all_pkgs {
786   my $self = shift;
787   if ( $self->{'_pkgnum'} ) {
788     values %{ $self->{'_pkgnum'}->cache };
789   } else {
790     qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
791   }
792 }
793
794 =item ncancelled_pkgs
795
796 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
797
798 =cut
799
800 sub ncancelled_pkgs {
801   my $self = shift;
802   if ( $self->{'_pkgnum'} ) {
803     grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
804   } else {
805     @{ [ # force list context
806       qsearch( 'cust_pkg', {
807         'custnum' => $self->custnum,
808         'cancel'  => '',
809       }),
810       qsearch( 'cust_pkg', {
811         'custnum' => $self->custnum,
812         'cancel'  => 0,
813       }),
814     ] };
815   }
816 }
817
818 =item suspended_pkgs
819
820 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
821
822 =cut
823
824 sub suspended_pkgs {
825   my $self = shift;
826   grep { $_->susp } $self->ncancelled_pkgs;
827 }
828
829 =item unflagged_suspended_pkgs
830
831 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
832 customer (thouse packages without the `manual_flag' set).
833
834 =cut
835
836 sub unflagged_suspended_pkgs {
837   my $self = shift;
838   return $self->suspended_pkgs
839     unless dbdef->table('cust_pkg')->column('manual_flag');
840   grep { ! $_->manual_flag } $self->suspended_pkgs;
841 }
842
843 =item unsuspended_pkgs
844
845 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
846 this customer.
847
848 =cut
849
850 sub unsuspended_pkgs {
851   my $self = shift;
852   grep { ! $_->susp } $self->ncancelled_pkgs;
853 }
854
855 =item unsuspend
856
857 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
858 and L<FS::cust_pkg>) for this customer.  Always returns a list: an empty list
859 on success or a list of errors.
860
861 =cut
862
863 sub unsuspend {
864   my $self = shift;
865   grep { $_->unsuspend } $self->suspended_pkgs;
866 }
867
868 =item suspend
869
870 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
871 Always returns a list: an empty list on success or a list of errors.
872
873 =cut
874
875 sub suspend {
876   my $self = shift;
877   grep { $_->suspend } $self->unsuspended_pkgs;
878 }
879
880 =item cancel [ OPTION => VALUE ... ]
881
882 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
883
884 Available options are: I<quiet>
885
886 I<quiet> can be set true to supress email cancellation notices.
887
888 Always returns a list: an empty list on success or a list of errors.
889
890 =cut
891
892 sub cancel {
893   my $self = shift;
894   grep { $_->cancel(@_) } $self->ncancelled_pkgs;
895 }
896
897 =item agent
898
899 Returns the agent (see L<FS::agent>) for this customer.
900
901 =cut
902
903 sub agent {
904   my $self = shift;
905   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
906 }
907
908 =item bill OPTIONS
909
910 Generates invoices (see L<FS::cust_bill>) for this customer.  Usually used in
911 conjunction with the collect method.
912
913 Options are passed as name-value pairs.
914
915 The only currently available option is `time', which bills the customer as if
916 it were that time.  It is specified as a UNIX timestamp; see
917 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
918 functions.  For example:
919
920  use Date::Parse;
921  ...
922  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
923
924 If there is an error, returns the error, otherwise returns false.
925
926 =cut
927
928 sub bill {
929   my( $self, %options ) = @_;
930   my $time = $options{'time'} || time;
931
932   my $error;
933
934   #put below somehow?
935   local $SIG{HUP} = 'IGNORE';
936   local $SIG{INT} = 'IGNORE';
937   local $SIG{QUIT} = 'IGNORE';
938   local $SIG{TERM} = 'IGNORE';
939   local $SIG{TSTP} = 'IGNORE';
940   local $SIG{PIPE} = 'IGNORE';
941
942   my $oldAutoCommit = $FS::UID::AutoCommit;
943   local $FS::UID::AutoCommit = 0;
944   my $dbh = dbh;
945
946   # find the packages which are due for billing, find out how much they are
947   # & generate invoice database.
948  
949   my( $total_setup, $total_recur ) = ( 0, 0 );
950   #my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
951   my @cust_bill_pkg = ();
952   #my $tax = 0;##
953   #my $taxable_charged = 0;##
954   #my $charged = 0;##
955
956   my %tax;
957
958   foreach my $cust_pkg (
959     qsearch('cust_pkg', { 'custnum' => $self->custnum } )
960   ) {
961
962     #NO!! next if $cust_pkg->cancel;  
963     next if $cust_pkg->getfield('cancel');  
964
965     #? to avoid use of uninitialized value errors... ?
966     $cust_pkg->setfield('bill', '')
967       unless defined($cust_pkg->bill);
968  
969     my $part_pkg = $cust_pkg->part_pkg;
970
971     #so we don't modify cust_pkg record unnecessarily
972     my $cust_pkg_mod_flag = 0;
973     my %hash = $cust_pkg->hash;
974     my $old_cust_pkg = new FS::cust_pkg \%hash;
975
976     # bill setup
977     my $setup = 0;
978     unless ( $cust_pkg->setup ) {
979       my $setup_prog = $part_pkg->getfield('setup');
980       $setup_prog =~ /^(.*)$/ or do {
981         $dbh->rollback if $oldAutoCommit;
982         return "Illegal setup for pkgpart ". $part_pkg->pkgpart.
983                ": $setup_prog";
984       };
985       $setup_prog = $1;
986       $setup_prog = '0' if $setup_prog =~ /^\s*$/;
987
988         #my $cpt = new Safe;
989         ##$cpt->permit(); #what is necessary?
990         #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
991         #$setup = $cpt->reval($setup_prog);
992       $setup = eval $setup_prog;
993       unless ( defined($setup) ) {
994         $dbh->rollback if $oldAutoCommit;
995         return "Error eval-ing part_pkg->setup pkgpart ". $part_pkg->pkgpart.
996                "(expression $setup_prog): $@";
997       }
998       $cust_pkg->setfield('setup',$time);
999       $cust_pkg_mod_flag=1; 
1000     }
1001
1002     #bill recurring fee
1003     my $recur = 0;
1004     my $sdate;
1005     if ( $part_pkg->getfield('freq') > 0 &&
1006          ! $cust_pkg->getfield('susp') &&
1007          ( $cust_pkg->getfield('bill') || 0 ) <= $time
1008     ) {
1009       my $recur_prog = $part_pkg->getfield('recur');
1010       $recur_prog =~ /^(.*)$/ or do {
1011         $dbh->rollback if $oldAutoCommit;
1012         return "Illegal recur for pkgpart ". $part_pkg->pkgpart.
1013                ": $recur_prog";
1014       };
1015       $recur_prog = $1;
1016       $recur_prog = '0' if $recur_prog =~ /^\s*$/;
1017
1018       # shared with $recur_prog
1019       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1020
1021         #my $cpt = new Safe;
1022         ##$cpt->permit(); #what is necessary?
1023         #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
1024         #$recur = $cpt->reval($recur_prog);
1025       $recur = eval $recur_prog;
1026       unless ( defined($recur) ) {
1027         $dbh->rollback if $oldAutoCommit;
1028         return "Error eval-ing part_pkg->recur pkgpart ".  $part_pkg->pkgpart.
1029                "(expression $recur_prog): $@";
1030       }
1031       #change this bit to use Date::Manip? CAREFUL with timezones (see
1032       # mailing list archive)
1033       my ($sec,$min,$hour,$mday,$mon,$year) =
1034         (localtime($sdate) )[0,1,2,3,4,5];
1035
1036       #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1037       # only for figuring next bill date, nothing else, so, reset $sdate again
1038       # here
1039       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1040       $cust_pkg->last_bill($sdate)
1041         if $cust_pkg->dbdef_table->column('last_bill');
1042
1043       $mon += $part_pkg->freq;
1044       until ( $mon < 12 ) { $mon -= 12; $year++; }
1045       $cust_pkg->setfield('bill',
1046         timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1047       $cust_pkg_mod_flag = 1; 
1048     }
1049
1050     warn "\$setup is undefined" unless defined($setup);
1051     warn "\$recur is undefined" unless defined($recur);
1052     warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1053
1054     if ( $cust_pkg_mod_flag ) {
1055       $error=$cust_pkg->replace($old_cust_pkg);
1056       if ( $error ) { #just in case
1057         $dbh->rollback if $oldAutoCommit;
1058         return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1059       }
1060       $setup = sprintf( "%.2f", $setup );
1061       $recur = sprintf( "%.2f", $recur );
1062       if ( $setup < 0 ) {
1063         $dbh->rollback if $oldAutoCommit;
1064         return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1065       }
1066       if ( $recur < 0 ) {
1067         $dbh->rollback if $oldAutoCommit;
1068         return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1069       }
1070       if ( $setup > 0 || $recur > 0 ) {
1071         my $cust_bill_pkg = new FS::cust_bill_pkg ({
1072           'pkgnum' => $cust_pkg->pkgnum,
1073           'setup'  => $setup,
1074           'recur'  => $recur,
1075           'sdate'  => $sdate,
1076           'edate'  => $cust_pkg->bill,
1077         });
1078         push @cust_bill_pkg, $cust_bill_pkg;
1079         $total_setup += $setup;
1080         $total_recur += $recur;
1081
1082         unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1083
1084           my @taxes =  qsearch( 'cust_main_county', {
1085                                   'state'    => $self->state,
1086                                   'county'   => $self->county,
1087                                   'country'  => $self->country,
1088                                   'taxclass' => $part_pkg->taxclass,
1089                                                                       } )
1090                     || qsearch( 'cust_main_county', {
1091                                   'state'    => $self->state,
1092                                   'county'   => $self->county,
1093                                   'country'  => $self->country,
1094                                   'taxclass' => '',
1095                                                                       } );
1096
1097           # maybe eliminate this entirely, along with all the 0% records
1098           unless ( @taxes ) {
1099             $dbh->rollback if $oldAutoCommit;
1100             return
1101               "fatal: can't find tax rate for state/county/country/taxclass ".
1102               join('/', ( map $self->$_(), qw(state county country) ),
1103                         $part_pkg->taxclass ).  "\n";
1104           }
1105
1106           foreach my $tax ( @taxes ) {
1107
1108             my $taxable_charged = 0;
1109             $taxable_charged += $setup
1110               unless $part_pkg->setuptax =~ /^Y$/i
1111                   || $tax->setuptax =~ /^Y$/i;
1112             $taxable_charged += $recur
1113               unless $part_pkg->recurtax =~ /^Y$/i
1114                   || $tax->recurtax =~ /^Y$/i;
1115             next unless $taxable_charged;
1116
1117             if ( $tax->exempt_amount ) {
1118               my ($mon,$year) = (localtime($sdate) )[4,5];
1119               $mon++;
1120               my $freq = $part_pkg->freq || 1;
1121               my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1122               foreach my $which_month ( 1 .. $freq ) {
1123                 my %hash = (
1124                   'custnum' => $self->custnum,
1125                   'taxnum'  => $tax->taxnum,
1126                   'year'    => 1900+$year,
1127                   'month'   => $mon++,
1128                 );
1129                 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1130                 until ( $mon < 13 ) { $mon -= 12; $year++; }
1131                 my $cust_tax_exempt =
1132                   qsearchs('cust_tax_exempt', \%hash)
1133                   || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1134                 my $remaining_exemption = sprintf("%.2f",
1135                   $tax->exempt_amount - $cust_tax_exempt->amount );
1136                 if ( $remaining_exemption > 0 ) {
1137                   my $addl = $remaining_exemption > $taxable_per_month
1138                     ? $taxable_per_month
1139                     : $remaining_exemption;
1140                   $taxable_charged -= $addl;
1141                   my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1142                     $cust_tax_exempt->hash,
1143                     'amount' =>
1144                       sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1145                   } );
1146                   $error = $new_cust_tax_exempt->exemptnum
1147                     ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1148                     : $new_cust_tax_exempt->insert;
1149                   if ( $error ) {
1150                     $dbh->rollback if $oldAutoCommit;
1151                     return "fatal: can't update cust_tax_exempt: $error";
1152                   }
1153   
1154                 } # if $remaining_exemption > 0
1155   
1156               } #foreach $which_month
1157   
1158             } #if $tax->exempt_amount
1159
1160             $taxable_charged = sprintf( "%.2f", $taxable_charged);
1161
1162             #$tax += $taxable_charged * $cust_main_county->tax / 100
1163             $tax{ $tax->taxname || 'Tax' } +=
1164               $taxable_charged * $tax->tax / 100
1165
1166           } #foreach my $tax ( @taxes )
1167
1168         } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
1169
1170       } #if $setup > 0 || $recur > 0
1171       
1172     } #if $cust_pkg_mod_flag
1173
1174   } #foreach my $cust_pkg
1175
1176   my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1177 #  my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1178
1179   unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1180     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1181     return '';
1182   } 
1183
1184 #  unless ( $self->tax =~ /Y/i
1185 #           || $self->payby eq 'COMP'
1186 #           || $taxable_charged == 0 ) {
1187 #    my $cust_main_county = qsearchs('cust_main_county',{
1188 #        'state'   => $self->state,
1189 #        'county'  => $self->county,
1190 #        'country' => $self->country,
1191 #    } ) or die "fatal: can't find tax rate for state/county/country ".
1192 #               $self->state. "/". $self->county. "/". $self->country. "\n";
1193 #    my $tax = sprintf( "%.2f",
1194 #      $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1195 #    );
1196
1197   if ( dbdef->table('cust_bill_pkg')->column('itemdesc') ) { #1.5 schema
1198
1199     foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
1200       my $tax = sprintf("%.2f", $tax{$taxname} );
1201       $charged = sprintf( "%.2f", $charged+$tax );
1202   
1203       my $cust_bill_pkg = new FS::cust_bill_pkg ({
1204         'pkgnum'   => 0,
1205         'setup'    => $tax,
1206         'recur'    => 0,
1207         'sdate'    => '',
1208         'edate'    => '',
1209         'itemdesc' => $taxname,
1210       });
1211       push @cust_bill_pkg, $cust_bill_pkg;
1212     }
1213   
1214   } else { #1.4 schema
1215
1216     my $tax = 0;
1217     foreach ( values %tax ) { $tax += $_ };
1218     $tax = sprintf("%.2f", $tax);
1219     if ( $tax > 0 ) {
1220       $charged = sprintf( "%.2f", $charged+$tax );
1221
1222       my $cust_bill_pkg = new FS::cust_bill_pkg ({
1223         'pkgnum' => 0,
1224         'setup'  => $tax,
1225         'recur'  => 0,
1226         'sdate'  => '',
1227         'edate'  => '',
1228       });
1229       push @cust_bill_pkg, $cust_bill_pkg;
1230     }
1231
1232   }
1233
1234   my $cust_bill = new FS::cust_bill ( {
1235     'custnum' => $self->custnum,
1236     '_date'   => $time,
1237     'charged' => $charged,
1238   } );
1239   $error = $cust_bill->insert;
1240   if ( $error ) {
1241     $dbh->rollback if $oldAutoCommit;
1242     return "can't create invoice for customer #". $self->custnum. ": $error";
1243   }
1244
1245   my $invnum = $cust_bill->invnum;
1246   my $cust_bill_pkg;
1247   foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1248     #warn $invnum;
1249     $cust_bill_pkg->invnum($invnum);
1250     $error = $cust_bill_pkg->insert;
1251     if ( $error ) {
1252       $dbh->rollback if $oldAutoCommit;
1253       return "can't create invoice line item for customer #". $self->custnum.
1254              ": $error";
1255     }
1256   }
1257   
1258   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1259   ''; #no error
1260 }
1261
1262 =item reexport
1263
1264 document me.  Re-schedules all exports by calling the B<reexport> method
1265 of all associated packages (see L<FS::cust_pkg>).  If there is an error,
1266 returns the error; otherwise returns false.
1267
1268 =cut
1269
1270 sub reexport {
1271   my $self = shift;
1272
1273   local $SIG{HUP} = 'IGNORE';
1274   local $SIG{INT} = 'IGNORE';
1275   local $SIG{QUIT} = 'IGNORE';
1276   local $SIG{TERM} = 'IGNORE';
1277   local $SIG{TSTP} = 'IGNORE';
1278   local $SIG{PIPE} = 'IGNORE';
1279
1280   my $oldAutoCommit = $FS::UID::AutoCommit;
1281   local $FS::UID::AutoCommit = 0;
1282   my $dbh = dbh;
1283
1284   foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1285     my $error = $cust_pkg->reexport;
1286     if ( $error ) {
1287       $dbh->rollback if $oldAutoCommit;
1288       return $error;
1289     }
1290   }
1291
1292   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1293   '';
1294
1295 }
1296
1297 =item collect OPTIONS
1298
1299 (Attempt to) collect money for this customer's outstanding invoices (see
1300 L<FS::cust_bill>).  Usually used after the bill method.
1301
1302 Depending on the value of `payby', this may print an invoice (`BILL'), charge
1303 a credit card (`CARD'), or just add any necessary (pseudo-)payment (`COMP').
1304
1305 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1306 and the invoice events web interface.
1307
1308 If there is an error, returns the error, otherwise returns false.
1309
1310 Options are passed as name-value pairs.
1311
1312 Currently available options are:
1313
1314 invoice_time - Use this time when deciding when to print invoices and
1315 late notices on those invoices.  The default is now.  It is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse>
1316 for conversion functions.
1317
1318 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
1319 events.
1320
1321 retry_card - Deprecated alias for 'retry'
1322
1323 batch_card - This option is deprecated.  See the invoice events web interface
1324 to control whether cards are batched or run against a realtime gateway.
1325
1326 report_badcard - This option is deprecated.
1327
1328 force_print - This option is deprecated; see the invoice events web interface.
1329
1330 quiet - set true to surpress email card/ACH decline notices.
1331
1332 =cut
1333
1334 sub collect {
1335   my( $self, %options ) = @_;
1336   my $invoice_time = $options{'invoice_time'} || time;
1337
1338   #put below somehow?
1339   local $SIG{HUP} = 'IGNORE';
1340   local $SIG{INT} = 'IGNORE';
1341   local $SIG{QUIT} = 'IGNORE';
1342   local $SIG{TERM} = 'IGNORE';
1343   local $SIG{TSTP} = 'IGNORE';
1344   local $SIG{PIPE} = 'IGNORE';
1345
1346   my $oldAutoCommit = $FS::UID::AutoCommit;
1347   local $FS::UID::AutoCommit = 0;
1348   my $dbh = dbh;
1349
1350   my $balance = $self->balance;
1351   warn "collect customer". $self->custnum. ": balance $balance" if $Debug;
1352   unless ( $balance > 0 ) { #redundant?????
1353     $dbh->rollback if $oldAutoCommit; #hmm
1354     return '';
1355   }
1356
1357   if ( exists($options{'retry_card'}) ) {
1358     carp 'retry_card option passed to collect is deprecated; use retry';
1359     $options{'retry'} ||= $options{'retry_card'};
1360   }
1361   if ( exists($options{'retry'}) && $options{'retry'} ) {
1362     my $error = $self->retry_realtime;
1363     if ( $error ) {
1364       $dbh->rollback if $oldAutoCommit;
1365       return $error;
1366     }
1367   }
1368
1369   foreach my $cust_bill ( $self->cust_bill ) {
1370
1371     #this has to be before next's
1372     my $amount = sprintf( "%.2f", $balance < $cust_bill->owed
1373                                   ? $balance
1374                                   : $cust_bill->owed
1375     );
1376     $balance = sprintf( "%.2f", $balance - $amount );
1377
1378     next unless $cust_bill->owed > 0;
1379
1380     # don't try to charge for the same invoice if it's already in a batch
1381     #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1382
1383     warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ", amount $amount, balance $balance)" if $Debug;
1384
1385     next unless $amount > 0;
1386
1387
1388     foreach my $part_bill_event (
1389       sort {    $a->seconds   <=> $b->seconds
1390              || $a->weight    <=> $b->weight
1391              || $a->eventpart <=> $b->eventpart }
1392         grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1393                && ! qsearchs( 'cust_bill_event', {
1394                                 'invnum'    => $cust_bill->invnum,
1395                                 'eventpart' => $_->eventpart,
1396                                 'status'    => 'done',
1397                                                                    } )
1398              }
1399           qsearch('part_bill_event', { 'payby'    => $self->payby,
1400                                        'disabled' => '',           } )
1401     ) {
1402
1403       last unless $cust_bill->owed > 0; #don't run subsequent events if owed=0
1404
1405       warn "calling invoice event (". $part_bill_event->eventcode. ")\n"
1406         if $Debug;
1407       my $cust_main = $self; #for callback
1408
1409       my $error;
1410       {
1411         #supress "used only once" warning
1412         $FS::cust_bill::realtime_bop_decline_quiet += 0;
1413         local $FS::cust_bill::realtime_bop_decline_quiet = 1
1414           if $options{'quiet'};
1415         $error = eval $part_bill_event->eventcode;
1416       }
1417
1418       my $status = '';
1419       my $statustext = '';
1420       if ( $@ ) {
1421         $status = 'failed';
1422         $statustext = $@;
1423       } elsif ( $error ) {
1424         $status = 'done';
1425         $statustext = $error;
1426       } else {
1427         $status = 'done'
1428       }
1429
1430       #add cust_bill_event
1431       my $cust_bill_event = new FS::cust_bill_event {
1432         'invnum'     => $cust_bill->invnum,
1433         'eventpart'  => $part_bill_event->eventpart,
1434         #'_date'      => $invoice_time,
1435         '_date'      => time,
1436         'status'     => $status,
1437         'statustext' => $statustext,
1438       };
1439       $error = $cust_bill_event->insert;
1440       if ( $error ) {
1441         #$dbh->rollback if $oldAutoCommit;
1442         #return "error: $error";
1443
1444         # gah, even with transactions.
1445         $dbh->commit if $oldAutoCommit; #well.
1446         my $e = 'WARNING: Event run but database not updated - '.
1447                 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
1448                 ', eventpart '. $part_bill_event->eventpart.
1449                 ": $error";
1450         warn $e;
1451         return $e;
1452       }
1453
1454
1455     }
1456
1457   }
1458
1459   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1460   '';
1461
1462 }
1463
1464 =item retry_realtime
1465
1466 Schedules realtime credit card / electronic check / LEC billing events for
1467 for retry.  Useful if card information has changed or manual retry is desired.
1468 The 'collect' method must be called to actually retry the transaction.
1469
1470 Implementation details: For each of this customer's open invoices, changes
1471 the status of the first "done" (with statustext error) realtime processing
1472 event to "failed".
1473
1474 =cut
1475
1476 sub retry_realtime {
1477   my $self = shift;
1478
1479   local $SIG{HUP} = 'IGNORE';
1480   local $SIG{INT} = 'IGNORE';
1481   local $SIG{QUIT} = 'IGNORE';
1482   local $SIG{TERM} = 'IGNORE';
1483   local $SIG{TSTP} = 'IGNORE';
1484   local $SIG{PIPE} = 'IGNORE';
1485
1486   my $oldAutoCommit = $FS::UID::AutoCommit;
1487   local $FS::UID::AutoCommit = 0;
1488   my $dbh = dbh;
1489
1490   foreach my $cust_bill (
1491     grep { $_->cust_bill_event }
1492       $self->open_cust_bill
1493   ) {
1494     my @cust_bill_event =
1495       sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
1496         grep {
1497                #$_->part_bill_event->plan eq 'realtime-card'
1498                $_->part_bill_event->eventcode =~
1499                    /\$cust_bill\->realtime_(card|ach|lec)/
1500                  && $_->status eq 'done'
1501                  && $_->statustext
1502              }
1503           $cust_bill->cust_bill_event;
1504     next unless @cust_bill_event;
1505     my $error = $cust_bill_event[0]->retry;
1506     if ( $error ) {
1507       $dbh->rollback if $oldAutoCommit;
1508       return "error scheduling invoice event for retry: $error";
1509     }
1510
1511   }
1512
1513   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1514   '';
1515
1516 }
1517
1518 =item total_owed
1519
1520 Returns the total owed for this customer on all invoices
1521 (see L<FS::cust_bill/owed>).
1522
1523 =cut
1524
1525 sub total_owed {
1526   my $self = shift;
1527   $self->total_owed_date(2145859200); #12/31/2037
1528 }
1529
1530 =item total_owed_date TIME
1531
1532 Returns the total owed for this customer on all invoices with date earlier than
1533 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
1534 see L<Time::Local> and L<Date::Parse> for conversion functions.
1535
1536 =cut
1537
1538 sub total_owed_date {
1539   my $self = shift;
1540   my $time = shift;
1541   my $total_bill = 0;
1542   foreach my $cust_bill (
1543     grep { $_->_date <= $time }
1544       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
1545   ) {
1546     $total_bill += $cust_bill->owed;
1547   }
1548   sprintf( "%.2f", $total_bill );
1549 }
1550
1551 =item apply_credits
1552
1553 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
1554 to outstanding invoice balances in chronological order and returns the value
1555 of any remaining unapplied credits available for refund
1556 (see L<FS::cust_refund>).
1557
1558 =cut
1559
1560 sub apply_credits {
1561   my $self = shift;
1562
1563   return 0 unless $self->total_credited;
1564
1565   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
1566       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
1567
1568   my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1569       qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1570
1571   my $credit;
1572
1573   foreach my $cust_bill ( @invoices ) {
1574     my $amount;
1575
1576     if ( !defined($credit) || $credit->credited == 0) {
1577       $credit = pop @credits or last;
1578     }
1579
1580     if ($cust_bill->owed >= $credit->credited) {
1581       $amount=$credit->credited;
1582     }else{
1583       $amount=$cust_bill->owed;
1584     }
1585     
1586     my $cust_credit_bill = new FS::cust_credit_bill ( {
1587       'crednum' => $credit->crednum,
1588       'invnum'  => $cust_bill->invnum,
1589       'amount'  => $amount,
1590     } );
1591     my $error = $cust_credit_bill->insert;
1592     die $error if $error;
1593     
1594     redo if ($cust_bill->owed > 0);
1595
1596   }
1597
1598   return $self->total_credited;
1599 }
1600
1601 =item apply_payments
1602
1603 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
1604 to outstanding invoice balances in chronological order.
1605
1606  #and returns the value of any remaining unapplied payments.
1607
1608 =cut
1609
1610 sub apply_payments {
1611   my $self = shift;
1612
1613   #return 0 unless
1614
1615   my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
1616       qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
1617
1618   my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1619       qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1620
1621   my $payment;
1622
1623   foreach my $cust_bill ( @invoices ) {
1624     my $amount;
1625
1626     if ( !defined($payment) || $payment->unapplied == 0 ) {
1627       $payment = pop @payments or last;
1628     }
1629
1630     if ( $cust_bill->owed >= $payment->unapplied ) {
1631       $amount = $payment->unapplied;
1632     } else {
1633       $amount = $cust_bill->owed;
1634     }
1635
1636     my $cust_bill_pay = new FS::cust_bill_pay ( {
1637       'paynum' => $payment->paynum,
1638       'invnum' => $cust_bill->invnum,
1639       'amount' => $amount,
1640     } );
1641     my $error = $cust_bill_pay->insert;
1642     die $error if $error;
1643
1644     redo if ( $cust_bill->owed > 0);
1645
1646   }
1647
1648   return $self->total_unapplied_payments;
1649 }
1650
1651 =item total_credited
1652
1653 Returns the total outstanding credit (see L<FS::cust_credit>) for this
1654 customer.  See L<FS::cust_credit/credited>.
1655
1656 =cut
1657
1658 sub total_credited {
1659   my $self = shift;
1660   my $total_credit = 0;
1661   foreach my $cust_credit ( qsearch('cust_credit', {
1662     'custnum' => $self->custnum,
1663   } ) ) {
1664     $total_credit += $cust_credit->credited;
1665   }
1666   sprintf( "%.2f", $total_credit );
1667 }
1668
1669 =item total_unapplied_payments
1670
1671 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
1672 See L<FS::cust_pay/unapplied>.
1673
1674 =cut
1675
1676 sub total_unapplied_payments {
1677   my $self = shift;
1678   my $total_unapplied = 0;
1679   foreach my $cust_pay ( qsearch('cust_pay', {
1680     'custnum' => $self->custnum,
1681   } ) ) {
1682     $total_unapplied += $cust_pay->unapplied;
1683   }
1684   sprintf( "%.2f", $total_unapplied );
1685 }
1686
1687 =item balance
1688
1689 Returns the balance for this customer (total_owed minus total_credited
1690 minus total_unapplied_payments).
1691
1692 =cut
1693
1694 sub balance {
1695   my $self = shift;
1696   sprintf( "%.2f",
1697     $self->total_owed - $self->total_credited - $self->total_unapplied_payments
1698   );
1699 }
1700
1701 =item balance_date TIME
1702
1703 Returns the balance for this customer, only considering invoices with date
1704 earlier than TIME (total_owed_date minus total_credited minus
1705 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
1706 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
1707 functions.
1708
1709 =cut
1710
1711 sub balance_date {
1712   my $self = shift;
1713   my $time = shift;
1714   sprintf( "%.2f",
1715     $self->total_owed_date($time)
1716       - $self->total_credited
1717       - $self->total_unapplied_payments
1718   );
1719 }
1720
1721 =item invoicing_list [ ARRAYREF ]
1722
1723 If an arguement is given, sets these email addresses as invoice recipients
1724 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
1725 (except as warnings), so use check_invoicing_list first.
1726
1727 Returns a list of email addresses (with svcnum entries expanded).
1728
1729 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
1730 check it without disturbing anything by passing nothing.
1731
1732 This interface may change in the future.
1733
1734 =cut
1735
1736 sub invoicing_list {
1737   my( $self, $arrayref ) = @_;
1738   if ( $arrayref ) {
1739     my @cust_main_invoice;
1740     if ( $self->custnum ) {
1741       @cust_main_invoice = 
1742         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1743     } else {
1744       @cust_main_invoice = ();
1745     }
1746     foreach my $cust_main_invoice ( @cust_main_invoice ) {
1747       #warn $cust_main_invoice->destnum;
1748       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
1749         #warn $cust_main_invoice->destnum;
1750         my $error = $cust_main_invoice->delete;
1751         warn $error if $error;
1752       }
1753     }
1754     if ( $self->custnum ) {
1755       @cust_main_invoice = 
1756         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1757     } else {
1758       @cust_main_invoice = ();
1759     }
1760     my %seen = map { $_->address => 1 } @cust_main_invoice;
1761     foreach my $address ( @{$arrayref} ) {
1762       next if exists $seen{$address} && $seen{$address};
1763       $seen{$address} = 1;
1764       my $cust_main_invoice = new FS::cust_main_invoice ( {
1765         'custnum' => $self->custnum,
1766         'dest'    => $address,
1767       } );
1768       my $error = $cust_main_invoice->insert;
1769       warn $error if $error;
1770     }
1771   }
1772   if ( $self->custnum ) {
1773     map { $_->address }
1774       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1775   } else {
1776     ();
1777   }
1778 }
1779
1780 =item check_invoicing_list ARRAYREF
1781
1782 Checks these arguements as valid input for the invoicing_list method.  If there
1783 is an error, returns the error, otherwise returns false.
1784
1785 =cut
1786
1787 sub check_invoicing_list {
1788   my( $self, $arrayref ) = @_;
1789   foreach my $address ( @{$arrayref} ) {
1790     my $cust_main_invoice = new FS::cust_main_invoice ( {
1791       'custnum' => $self->custnum,
1792       'dest'    => $address,
1793     } );
1794     my $error = $self->custnum
1795                 ? $cust_main_invoice->check
1796                 : $cust_main_invoice->checkdest
1797     ;
1798     return $error if $error;
1799   }
1800   '';
1801 }
1802
1803 =item set_default_invoicing_list
1804
1805 Sets the invoicing list to all accounts associated with this customer,
1806 overwriting any previous invoicing list.
1807
1808 =cut
1809
1810 sub set_default_invoicing_list {
1811   my $self = shift;
1812   $self->invoicing_list($self->all_emails);
1813 }
1814
1815 =item all_emails
1816
1817 Returns the email addresses of all accounts provisioned for this customer.
1818
1819 =cut
1820
1821 sub all_emails {
1822   my $self = shift;
1823   my %list;
1824   foreach my $cust_pkg ( $self->all_pkgs ) {
1825     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
1826     my @svc_acct =
1827       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1828         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1829           @cust_svc;
1830     $list{$_}=1 foreach map { $_->email } @svc_acct;
1831   }
1832   keys %list;
1833 }
1834
1835 =item invoicing_list_addpost
1836
1837 Adds postal invoicing to this customer.  If this customer is already configured
1838 to receive postal invoices, does nothing.
1839
1840 =cut
1841
1842 sub invoicing_list_addpost {
1843   my $self = shift;
1844   return if grep { $_ eq 'POST' } $self->invoicing_list;
1845   my @invoicing_list = $self->invoicing_list;
1846   push @invoicing_list, 'POST';
1847   $self->invoicing_list(\@invoicing_list);
1848 }
1849
1850 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
1851
1852 Returns an array of customers referred by this customer (referral_custnum set
1853 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
1854 customers referred by customers referred by this customer and so on, inclusive.
1855 The default behavior is DEPTH 1 (no recursion).
1856
1857 =cut
1858
1859 sub referral_cust_main {
1860   my $self = shift;
1861   my $depth = @_ ? shift : 1;
1862   my $exclude = @_ ? shift : {};
1863
1864   my @cust_main =
1865     map { $exclude->{$_->custnum}++; $_; }
1866       grep { ! $exclude->{ $_->custnum } }
1867         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
1868
1869   if ( $depth > 1 ) {
1870     push @cust_main,
1871       map { $_->referral_cust_main($depth-1, $exclude) }
1872         @cust_main;
1873   }
1874
1875   @cust_main;
1876 }
1877
1878 =item referral_cust_main_ncancelled
1879
1880 Same as referral_cust_main, except only returns customers with uncancelled
1881 packages.
1882
1883 =cut
1884
1885 sub referral_cust_main_ncancelled {
1886   my $self = shift;
1887   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
1888 }
1889
1890 =item referral_cust_pkg [ DEPTH ]
1891
1892 Like referral_cust_main, except returns a flat list of all unsuspended (and
1893 uncancelled) packages for each customer.  The number of items in this list may
1894 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
1895
1896 =cut
1897
1898 sub referral_cust_pkg {
1899   my $self = shift;
1900   my $depth = @_ ? shift : 1;
1901
1902   map { $_->unsuspended_pkgs }
1903     grep { $_->unsuspended_pkgs }
1904       $self->referral_cust_main($depth);
1905 }
1906
1907 =item credit AMOUNT, REASON
1908
1909 Applies a credit to this customer.  If there is an error, returns the error,
1910 otherwise returns false.
1911
1912 =cut
1913
1914 sub credit {
1915   my( $self, $amount, $reason ) = @_;
1916   my $cust_credit = new FS::cust_credit {
1917     'custnum' => $self->custnum,
1918     'amount'  => $amount,
1919     'reason'  => $reason,
1920   };
1921   $cust_credit->insert;
1922 }
1923
1924 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
1925
1926 Creates a one-time charge for this customer.  If there is an error, returns
1927 the error, otherwise returns false.
1928
1929 =cut
1930
1931 sub charge {
1932   my ( $self, $amount ) = ( shift, shift );
1933   my $pkg      = @_ ? shift : 'One-time charge';
1934   my $comment  = @_ ? shift : '$'. sprintf("%.2f",$amount);
1935   my $taxclass = @_ ? shift : '';
1936
1937   local $SIG{HUP} = 'IGNORE';
1938   local $SIG{INT} = 'IGNORE';
1939   local $SIG{QUIT} = 'IGNORE';
1940   local $SIG{TERM} = 'IGNORE';
1941   local $SIG{TSTP} = 'IGNORE';
1942   local $SIG{PIPE} = 'IGNORE';
1943
1944   my $oldAutoCommit = $FS::UID::AutoCommit;
1945   local $FS::UID::AutoCommit = 0;
1946   my $dbh = dbh;
1947
1948   my $part_pkg = new FS::part_pkg ( {
1949     'pkg'      => $pkg,
1950     'comment'  => $comment,
1951     'setup'    => $amount,
1952     'freq'     => 0,
1953     'recur'    => '0',
1954     'disabled' => 'Y',
1955     'taxclass' => $taxclass,
1956   } );
1957
1958   my $error = $part_pkg->insert;
1959   if ( $error ) {
1960     $dbh->rollback if $oldAutoCommit;
1961     return $error;
1962   }
1963
1964   my $pkgpart = $part_pkg->pkgpart;
1965   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
1966   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
1967     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
1968     $error = $type_pkgs->insert;
1969     if ( $error ) {
1970       $dbh->rollback if $oldAutoCommit;
1971       return $error;
1972     }
1973   }
1974
1975   my $cust_pkg = new FS::cust_pkg ( {
1976     'custnum' => $self->custnum,
1977     'pkgpart' => $pkgpart,
1978   } );
1979
1980   $error = $cust_pkg->insert;
1981   if ( $error ) {
1982     $dbh->rollback if $oldAutoCommit;
1983     return $error;
1984   }
1985
1986   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1987   '';
1988
1989 }
1990
1991 =item cust_bill
1992
1993 Returns all the invoices (see L<FS::cust_bill>) for this customer.
1994
1995 =cut
1996
1997 sub cust_bill {
1998   my $self = shift;
1999   sort { $a->_date <=> $b->_date }
2000     qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2001 }
2002
2003 =item open_cust_bill
2004
2005 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
2006 customer.
2007
2008 =cut
2009
2010 sub open_cust_bill {
2011   my $self = shift;
2012   grep { $_->owed > 0 } $self->cust_bill;
2013 }
2014
2015 =back
2016
2017 =head1 SUBROUTINES
2018
2019 =over 4
2020
2021 =item check_and_rebuild_fuzzyfiles
2022
2023 =cut
2024
2025 sub check_and_rebuild_fuzzyfiles {
2026   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2027   -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
2028     or &rebuild_fuzzyfiles;
2029 }
2030
2031 =item rebuild_fuzzyfiles
2032
2033 =cut
2034
2035 sub rebuild_fuzzyfiles {
2036
2037   use Fcntl qw(:flock);
2038
2039   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2040
2041   #last
2042
2043   open(LASTLOCK,">>$dir/cust_main.last")
2044     or die "can't open $dir/cust_main.last: $!";
2045   flock(LASTLOCK,LOCK_EX)
2046     or die "can't lock $dir/cust_main.last: $!";
2047
2048   my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
2049   push @all_last,
2050                  grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
2051     if defined dbdef->table('cust_main')->column('ship_last');
2052
2053   open (LASTCACHE,">$dir/cust_main.last.tmp")
2054     or die "can't open $dir/cust_main.last.tmp: $!";
2055   print LASTCACHE join("\n", @all_last), "\n";
2056   close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
2057
2058   rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
2059   close LASTLOCK;
2060
2061   #company
2062
2063   open(COMPANYLOCK,">>$dir/cust_main.company")
2064     or die "can't open $dir/cust_main.company: $!";
2065   flock(COMPANYLOCK,LOCK_EX)
2066     or die "can't lock $dir/cust_main.company: $!";
2067
2068   my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
2069   push @all_company,
2070        grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
2071     if defined dbdef->table('cust_main')->column('ship_last');
2072
2073   open (COMPANYCACHE,">$dir/cust_main.company.tmp")
2074     or die "can't open $dir/cust_main.company.tmp: $!";
2075   print COMPANYCACHE join("\n", @all_company), "\n";
2076   close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
2077
2078   rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
2079   close COMPANYLOCK;
2080
2081 }
2082
2083 =item all_last
2084
2085 =cut
2086
2087 sub all_last {
2088   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2089   open(LASTCACHE,"<$dir/cust_main.last")
2090     or die "can't open $dir/cust_main.last: $!";
2091   my @array = map { chomp; $_; } <LASTCACHE>;
2092   close LASTCACHE;
2093   \@array;
2094 }
2095
2096 =item all_company
2097
2098 =cut
2099
2100 sub all_company {
2101   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2102   open(COMPANYCACHE,"<$dir/cust_main.company")
2103     or die "can't open $dir/cust_main.last: $!";
2104   my @array = map { chomp; $_; } <COMPANYCACHE>;
2105   close COMPANYCACHE;
2106   \@array;
2107 }
2108
2109 =item append_fuzzyfiles LASTNAME COMPANY
2110
2111 =cut
2112
2113 sub append_fuzzyfiles {
2114   my( $last, $company ) = @_;
2115
2116   &check_and_rebuild_fuzzyfiles;
2117
2118   use Fcntl qw(:flock);
2119
2120   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2121
2122   if ( $last ) {
2123
2124     open(LAST,">>$dir/cust_main.last")
2125       or die "can't open $dir/cust_main.last: $!";
2126     flock(LAST,LOCK_EX)
2127       or die "can't lock $dir/cust_main.last: $!";
2128
2129     print LAST "$last\n";
2130
2131     flock(LAST,LOCK_UN)
2132       or die "can't unlock $dir/cust_main.last: $!";
2133     close LAST;
2134   }
2135
2136   if ( $company ) {
2137
2138     open(COMPANY,">>$dir/cust_main.company")
2139       or die "can't open $dir/cust_main.company: $!";
2140     flock(COMPANY,LOCK_EX)
2141       or die "can't lock $dir/cust_main.company: $!";
2142
2143     print COMPANY "$company\n";
2144
2145     flock(COMPANY,LOCK_UN)
2146       or die "can't unlock $dir/cust_main.company: $!";
2147
2148     close COMPANY;
2149   }
2150
2151   1;
2152 }
2153
2154 =item batch_import
2155
2156 =cut
2157
2158 sub batch_import {
2159   my $param = shift;
2160   #warn join('-',keys %$param);
2161   my $fh = $param->{filehandle};
2162   my $agentnum = $param->{agentnum};
2163   my $refnum = $param->{refnum};
2164   my $pkgpart = $param->{pkgpart};
2165   my @fields = @{$param->{fields}};
2166
2167   eval "use Date::Parse;";
2168   die $@ if $@;
2169   eval "use Text::CSV_XS;";
2170   die $@ if $@;
2171
2172   my $csv = new Text::CSV_XS;
2173   #warn $csv;
2174   #warn $fh;
2175
2176   my $imported = 0;
2177   #my $columns;
2178
2179   local $SIG{HUP} = 'IGNORE';
2180   local $SIG{INT} = 'IGNORE';
2181   local $SIG{QUIT} = 'IGNORE';
2182   local $SIG{TERM} = 'IGNORE';
2183   local $SIG{TSTP} = 'IGNORE';
2184   local $SIG{PIPE} = 'IGNORE';
2185
2186   my $oldAutoCommit = $FS::UID::AutoCommit;
2187   local $FS::UID::AutoCommit = 0;
2188   my $dbh = dbh;
2189   
2190   #while ( $columns = $csv->getline($fh) ) {
2191   my $line;
2192   while ( defined($line=<$fh>) ) {
2193
2194     $csv->parse($line) or do {
2195       $dbh->rollback if $oldAutoCommit;
2196       return "can't parse: ". $csv->error_input();
2197     };
2198
2199     my @columns = $csv->fields();
2200     #warn join('-',@columns);
2201
2202     my %cust_main = (
2203       agentnum => $agentnum,
2204       refnum   => $refnum,
2205       country  => 'US', #default
2206       payby    => 'BILL', #default
2207       paydate  => '12/2037', #default
2208     );
2209     my $billtime = time;
2210     my %cust_pkg = ( pkgpart => $pkgpart );
2211     foreach my $field ( @fields ) {
2212       if ( $field =~ /^cust_pkg\.(setup|bill|susp|expire|cancel)$/ ) {
2213         #$cust_pkg{$1} = str2time( shift @$columns );
2214         if ( $1 eq 'setup' ) {
2215           $billtime = str2time(shift @columns);
2216         } else {
2217           $cust_pkg{$1} = str2time( shift @columns );
2218         }
2219       } else {
2220         #$cust_main{$field} = shift @$columns; 
2221         $cust_main{$field} = shift @columns; 
2222       }
2223     }
2224
2225     my $cust_pkg = new FS::cust_pkg ( \%cust_pkg ) if $pkgpart;
2226     my $cust_main = new FS::cust_main ( \%cust_main );
2227     use Tie::RefHash;
2228     tie my %hash, 'Tie::RefHash'; #this part is important
2229     $hash{$cust_pkg} = [] if $pkgpart;
2230     my $error = $cust_main->insert( \%hash );
2231
2232     if ( $error ) {
2233       $dbh->rollback if $oldAutoCommit;
2234       return "can't insert customer for $line: $error";
2235     }
2236
2237     #false laziness w/bill.cgi
2238     $error = $cust_main->bill( 'time' => $billtime );
2239     if ( $error ) {
2240       $dbh->rollback if $oldAutoCommit;
2241       return "can't bill customer for $line: $error";
2242     }
2243
2244     $cust_main->apply_payments;
2245     $cust_main->apply_credits;
2246
2247     $error = $cust_main->collect();
2248     if ( $error ) {
2249       $dbh->rollback if $oldAutoCommit;
2250       return "can't collect customer for $line: $error";
2251     }
2252
2253     $imported++;
2254   }
2255
2256   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2257
2258   return "Empty file!" unless $imported;
2259
2260   ''; #no error
2261
2262 }
2263
2264 =item batch_charge
2265
2266 =cut
2267
2268 sub batch_charge {
2269   my $param = shift;
2270   #warn join('-',keys %$param);
2271   my $fh = $param->{filehandle};
2272   my @fields = @{$param->{fields}};
2273
2274   eval "use Date::Parse;";
2275   die $@ if $@;
2276   eval "use Text::CSV_XS;";
2277   die $@ if $@;
2278
2279   my $csv = new Text::CSV_XS;
2280   #warn $csv;
2281   #warn $fh;
2282
2283   my $imported = 0;
2284   #my $columns;
2285
2286   local $SIG{HUP} = 'IGNORE';
2287   local $SIG{INT} = 'IGNORE';
2288   local $SIG{QUIT} = 'IGNORE';
2289   local $SIG{TERM} = 'IGNORE';
2290   local $SIG{TSTP} = 'IGNORE';
2291   local $SIG{PIPE} = 'IGNORE';
2292
2293   my $oldAutoCommit = $FS::UID::AutoCommit;
2294   local $FS::UID::AutoCommit = 0;
2295   my $dbh = dbh;
2296   
2297   #while ( $columns = $csv->getline($fh) ) {
2298   my $line;
2299   while ( defined($line=<$fh>) ) {
2300
2301     $csv->parse($line) or do {
2302       $dbh->rollback if $oldAutoCommit;
2303       return "can't parse: ". $csv->error_input();
2304     };
2305
2306     my @columns = $csv->fields();
2307     #warn join('-',@columns);
2308
2309     my %row = ();
2310     foreach my $field ( @fields ) {
2311       $row{$field} = shift @columns;
2312     }
2313
2314     my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
2315     unless ( $cust_main ) {
2316       $dbh->rollback if $oldAutoCommit;
2317       return "unknown custnum $row{'custnum'}";
2318     }
2319
2320     if ( $row{'amount'} > 0 ) {
2321       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
2322       if ( $error ) {
2323         $dbh->rollback if $oldAutoCommit;
2324         return $error;
2325       }
2326       $imported++;
2327     } elsif ( $row{'amount'} < 0 ) {
2328       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
2329                                       $row{'pkg'}                         );
2330       if ( $error ) {
2331         $dbh->rollback if $oldAutoCommit;
2332         return $error;
2333       }
2334       $imported++;
2335     } else {
2336       #hmm?
2337     }
2338
2339   }
2340
2341   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2342
2343   return "Empty file!" unless $imported;
2344
2345   ''; #no error
2346
2347 }
2348
2349 =back
2350
2351 =head1 BUGS
2352
2353 The delete method.
2354
2355 The delete method should possibly take an FS::cust_main object reference
2356 instead of a scalar customer number.
2357
2358 Bill and collect options should probably be passed as references instead of a
2359 list.
2360
2361 There should probably be a configuration file with a list of allowed credit
2362 card types.
2363
2364 No multiple currency support (probably a larger project than just this module).
2365
2366 =head1 SEE ALSO
2367
2368 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
2369 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
2370 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
2371
2372 =cut
2373
2374 1;
2375