4 use vars qw( @ISA $conf $Debug $import );
10 use Business::CreditCard;
11 use FS::UID qw( getotaker dbh );
12 use FS::Record qw( qsearchs qsearch dbdef );
15 use FS::cust_bill_pkg;
18 use FS::part_referral;
19 use FS::cust_main_county;
21 use FS::cust_main_invoice;
22 use FS::cust_credit_bill;
23 use FS::cust_bill_pay;
24 use FS::prepay_credit;
27 use FS::part_bill_event;
28 use FS::cust_bill_event;
29 use FS::cust_tax_exempt;
31 use FS::Msgcat qw(gettext);
33 @ISA = qw( FS::Record );
40 #ask FS::UID to run this stuff for us later
41 $FS::UID::callback{'FS::cust_main'} = sub {
43 #yes, need it for stuff below (prolly should be cached)
48 my ( $hashref, $cache ) = @_;
49 if ( exists $hashref->{'pkgnum'} ) {
50 # #@{ $self->{'_pkgnum'} } = ();
51 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
52 $self->{'_pkgnum'} = $subcache;
53 #push @{ $self->{'_pkgnum'} },
54 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
60 FS::cust_main - Object methods for cust_main records
66 $record = new FS::cust_main \%hash;
67 $record = new FS::cust_main { 'column' => 'value' };
69 $error = $record->insert;
71 $error = $new_record->replace($old_record);
73 $error = $record->delete;
75 $error = $record->check;
77 @cust_pkg = $record->all_pkgs;
79 @cust_pkg = $record->ncancelled_pkgs;
81 @cust_pkg = $record->suspended_pkgs;
83 $error = $record->bill;
84 $error = $record->bill %options;
85 $error = $record->bill 'time' => $time;
87 $error = $record->collect;
88 $error = $record->collect %options;
89 $error = $record->collect 'invoice_time' => $time,
90 'batch_card' => 'yes',
91 'report_badcard' => 'yes',
96 An FS::cust_main object represents a customer. FS::cust_main inherits from
97 FS::Record. The following fields are currently supported:
101 =item custnum - primary key (assigned automatically for new customers)
103 =item agentnum - agent (see L<FS::agent>)
105 =item refnum - Advertising source (see L<FS::part_referral>)
111 =item ss - social security number (optional)
113 =item company - (optional)
117 =item address2 - (optional)
121 =item county - (optional, see L<FS::cust_main_county>)
123 =item state - (see L<FS::cust_main_county>)
127 =item country - (see L<FS::cust_main_county>)
129 =item daytime - phone (optional)
131 =item night - phone (optional)
133 =item fax - phone (optional)
135 =item ship_first - name
137 =item ship_last - name
139 =item ship_company - (optional)
143 =item ship_address2 - (optional)
147 =item ship_county - (optional, see L<FS::cust_main_county>)
149 =item ship_state - (see L<FS::cust_main_county>)
153 =item ship_country - (see L<FS::cust_main_county>)
155 =item ship_daytime - phone (optional)
157 =item ship_night - phone (optional)
159 =item ship_fax - phone (optional)
161 =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)
163 =item payinfo - card number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
165 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
167 =item payname - name on card or billing name
169 =item tax - tax exempt, empty or `Y'
171 =item otaker - order taker (assigned automatically, see L<FS::UID>)
173 =item comments - comments (optional)
183 Creates a new customer. To add the customer to the database, see L<"insert">.
185 Note that this stores the hash reference, not a distinct copy of the hash it
186 points to. You can ask the object for a copy with the I<hash> method.
190 sub table { 'cust_main'; }
192 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] ]
194 Adds this customer to the database. If there is an error, returns the error,
195 otherwise returns false.
197 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
198 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
199 are inserted atomicly, or the transaction is rolled back. Passing an empty
200 hash reference is equivalent to not supplying this parameter. There should be
201 a better explanation of this, but until then, here's an example:
204 tie %hash, 'Tie::RefHash'; #this part is important
206 $cust_pkg => [ $svc_acct ],
209 $cust_main->insert( \%hash );
211 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
212 be set as the invoicing list (see L<"invoicing_list">). Errors return as
213 expected and rollback the entire transaction; it is not necessary to call
214 check_invoicing_list first. The invoicing_list is set after the records in the
215 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
216 invoicing_list destination to the newly-created svc_acct. Here's an example:
218 $cust_main->insert( {}, [ $email, 'POST' ] );
224 my $cust_pkgs = @_ ? shift : {};
225 my $invoicing_list = @_ ? shift : '';
227 local $SIG{HUP} = 'IGNORE';
228 local $SIG{INT} = 'IGNORE';
229 local $SIG{QUIT} = 'IGNORE';
230 local $SIG{TERM} = 'IGNORE';
231 local $SIG{TSTP} = 'IGNORE';
232 local $SIG{PIPE} = 'IGNORE';
234 my $oldAutoCommit = $FS::UID::AutoCommit;
235 local $FS::UID::AutoCommit = 0;
240 if ( $self->payby eq 'PREPAY' ) {
241 $self->payby('BILL');
242 my $prepay_credit = qsearchs(
244 { 'identifier' => $self->payinfo },
248 warn "WARNING: can't find pre-found prepay_credit: ". $self->payinfo
249 unless $prepay_credit;
250 $amount = $prepay_credit->amount;
251 $seconds = $prepay_credit->seconds;
252 my $error = $prepay_credit->delete;
254 $dbh->rollback if $oldAutoCommit;
255 return "removing prepay_credit (transaction rolled back): $error";
259 my $error = $self->SUPER::insert;
261 $dbh->rollback if $oldAutoCommit;
262 #return "inserting cust_main record (transaction rolled back): $error";
267 if ( $invoicing_list ) {
268 $error = $self->check_invoicing_list( $invoicing_list );
270 $dbh->rollback if $oldAutoCommit;
271 return "checking invoicing_list (transaction rolled back): $error";
273 $self->invoicing_list( $invoicing_list );
277 foreach my $cust_pkg ( keys %$cust_pkgs ) {
278 $cust_pkg->custnum( $self->custnum );
279 $error = $cust_pkg->insert;
281 $dbh->rollback if $oldAutoCommit;
282 return "inserting cust_pkg (transaction rolled back): $error";
284 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
285 $svc_something->pkgnum( $cust_pkg->pkgnum );
286 if ( $seconds && $svc_something->isa('FS::svc_acct') ) {
287 $svc_something->seconds( $svc_something->seconds + $seconds );
290 $error = $svc_something->insert;
292 $dbh->rollback if $oldAutoCommit;
293 #return "inserting svc_ (transaction rolled back): $error";
300 $dbh->rollback if $oldAutoCommit;
301 return "No svc_acct record to apply pre-paid time";
305 my $cust_credit = new FS::cust_credit {
306 'custnum' => $self->custnum,
309 $error = $cust_credit->insert;
311 $dbh->rollback if $oldAutoCommit;
312 return "inserting credit (transaction rolled back): $error";
316 #false laziness with sub replace
317 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
318 $error = $queue->insert($self->getfield('last'), $self->company);
320 $dbh->rollback if $oldAutoCommit;
321 return "queueing job (transaction rolled back): $error";
324 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
325 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
326 $error = $queue->insert($self->getfield('last'), $self->company);
328 $dbh->rollback if $oldAutoCommit;
329 return "queueing job (transaction rolled back): $error";
334 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
339 =item delete NEW_CUSTNUM
341 This deletes the customer. If there is an error, returns the error, otherwise
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<FS::cust_pkg/cancel>).
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>?
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>).
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';
369 my $oldAutoCommit = $FS::UID::AutoCommit;
370 local $FS::UID::AutoCommit = 0;
373 if ( qsearch( 'cust_bill', { 'custnum' => $self->custnum } ) ) {
374 $dbh->rollback if $oldAutoCommit;
375 return "Can't delete a customer with invoices";
377 if ( qsearch( 'cust_credit', { 'custnum' => $self->custnum } ) ) {
378 $dbh->rollback if $oldAutoCommit;
379 return "Can't delete a customer with credits";
381 if ( qsearch( 'cust_pay', { 'custnum' => $self->custnum } ) ) {
382 $dbh->rollback if $oldAutoCommit;
383 return "Can't delete a customer with payments";
385 if ( qsearch( 'cust_refund', { 'custnum' => $self->custnum } ) ) {
386 $dbh->rollback if $oldAutoCommit;
387 return "Can't delete a customer with refunds";
390 my @cust_pkg = $self->ncancelled_pkgs;
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";
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);
403 $dbh->rollback if $oldAutoCommit;
408 my @cancelled_cust_pkg = $self->all_pkgs;
409 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
410 my $error = $cust_pkg->delete;
412 $dbh->rollback if $oldAutoCommit;
417 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
418 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
420 my $error = $cust_main_invoice->delete;
422 $dbh->rollback if $oldAutoCommit;
427 my $error = $self->SUPER::delete;
429 $dbh->rollback if $oldAutoCommit;
433 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
438 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
440 Replaces the OLD_RECORD with this one in the database. If there is an error,
441 returns the error, otherwise returns false.
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:
448 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
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';
464 my $oldAutoCommit = $FS::UID::AutoCommit;
465 local $FS::UID::AutoCommit = 0;
468 my $error = $self->SUPER::replace($old);
471 $dbh->rollback if $oldAutoCommit;
475 if ( @param ) { # INVOICING_LIST_ARYREF
476 my $invoicing_list = shift @param;
477 $error = $self->check_invoicing_list( $invoicing_list );
479 $dbh->rollback if $oldAutoCommit;
482 $self->invoicing_list( $invoicing_list );
485 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
486 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
487 # card info has changed, want to retry realtime_card invoice events
488 #false laziness w/collect
489 foreach my $cust_bill_event (
491 #$_->part_bill_event->plan eq 'realtime-card'
492 $_->part_bill_event->eventcode =~
493 /^\$cust_bill\->realtime_(card|ach|lec)\(\);$/
494 && $_->status eq 'done'
497 map { $_->cust_bill_event }
498 grep { $_->cust_bill_event }
499 $self->open_cust_bill
502 my $error = $cust_bill_event->retry;
504 $dbh->rollback if $oldAutoCommit;
505 return "error scheduling invoice events for retry: $error";
512 #false laziness with sub insert
513 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
514 $error = $queue->insert($self->getfield('last'), $self->company);
516 $dbh->rollback if $oldAutoCommit;
517 return "queueing job (transaction rolled back): $error";
520 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
521 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
522 $error = $queue->insert($self->getfield('last'), $self->company);
524 $dbh->rollback if $oldAutoCommit;
525 return "queueing job (transaction rolled back): $error";
530 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
537 Checks all fields to make sure this is a valid customer record. If there is
538 an error, returns the error, otherwise returns false. Called by the insert
546 #warn "BEFORE: \n". $self->_dump;
549 $self->ut_numbern('custnum')
550 || $self->ut_number('agentnum')
551 || $self->ut_number('refnum')
552 || $self->ut_name('last')
553 || $self->ut_name('first')
554 || $self->ut_textn('company')
555 || $self->ut_text('address1')
556 || $self->ut_textn('address2')
557 || $self->ut_text('city')
558 || $self->ut_textn('county')
559 || $self->ut_textn('state')
560 || $self->ut_country('country')
561 || $self->ut_anything('comments')
562 || $self->ut_numbern('referral_custnum')
564 #barf. need message catalogs. i18n. etc.
565 $error .= "Please select a advertising source."
566 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
567 return $error if $error;
569 return "Unknown agent"
570 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
572 return "Unknown refnum"
573 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
575 return "Unknown referring custnum ". $self->referral_custnum
576 unless ! $self->referral_custnum
577 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
579 if ( $self->ss eq '' ) {
584 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
585 or return "Illegal social security number: ". $self->ss;
586 $self->ss("$1-$2-$3");
590 # bad idea to disable, causes billing to fail because of no tax rates later
591 # unless ( $import ) {
592 unless ( qsearch('cust_main_county', {
593 'country' => $self->country,
596 return "Unknown state/county/country: ".
597 $self->state. "/". $self->county. "/". $self->country
598 unless qsearch('cust_main_county',{
599 'state' => $self->state,
600 'county' => $self->county,
601 'country' => $self->country,
607 $self->ut_phonen('daytime', $self->country)
608 || $self->ut_phonen('night', $self->country)
609 || $self->ut_phonen('fax', $self->country)
610 || $self->ut_zip('zip', $self->country)
612 return $error if $error;
615 last first company address1 address2 city county state zip
616 country daytime night fax
619 if ( defined $self->dbdef_table->column('ship_last') ) {
620 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
622 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
626 $self->ut_name('ship_last')
627 || $self->ut_name('ship_first')
628 || $self->ut_textn('ship_company')
629 || $self->ut_text('ship_address1')
630 || $self->ut_textn('ship_address2')
631 || $self->ut_text('ship_city')
632 || $self->ut_textn('ship_county')
633 || $self->ut_textn('ship_state')
634 || $self->ut_country('ship_country')
636 return $error if $error;
638 #false laziness with above
639 unless ( qsearchs('cust_main_county', {
640 'country' => $self->ship_country,
643 return "Unknown ship_state/ship_county/ship_country: ".
644 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
645 unless qsearchs('cust_main_county',{
646 'state' => $self->ship_state,
647 'county' => $self->ship_county,
648 'country' => $self->ship_country,
654 $self->ut_phonen('ship_daytime', $self->ship_country)
655 || $self->ut_phonen('ship_night', $self->ship_country)
656 || $self->ut_phonen('ship_fax', $self->ship_country)
657 || $self->ut_zip('ship_zip', $self->ship_country)
659 return $error if $error;
661 } else { # ship_ info eq billing info, so don't store dup info in database
662 $self->setfield("ship_$_", '')
663 foreach qw( last first company address1 address2 city county state zip
664 country daytime night fax );
668 $self->payby =~ /^(CARD|CHEK|LECB|BILL|COMP|PREPAY)$/
669 or return "Illegal payby: ". $self->payby;
672 if ( $self->payby eq 'CARD' ) {
674 my $payinfo = $self->payinfo;
676 $payinfo =~ /^(\d{13,16})$/
677 or return gettext('invalid_card'); # . ": ". $self->payinfo;
679 $self->payinfo($payinfo);
681 or return gettext('invalid_card'); # . ": ". $self->payinfo;
682 return gettext('unknown_card_type')
683 if cardtype($self->payinfo) eq "Unknown";
685 } elsif ( $self->payby eq 'CHEK' ) {
687 my $payinfo = $self->payinfo;
688 $payinfo =~ s/[^\d\@]//g;
689 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
691 $self->payinfo($payinfo);
693 } elsif ( $self->payby eq 'LECB' ) {
695 my $payinfo = $self->payinfo;
697 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
699 $self->payinfo($payinfo);
701 } elsif ( $self->payby eq 'BILL' ) {
703 $error = $self->ut_textn('payinfo');
704 return "Illegal P.O. number: ". $self->payinfo if $error;
706 } elsif ( $self->payby eq 'COMP' ) {
708 $error = $self->ut_textn('payinfo');
709 return "Illegal comp account issuer: ". $self->payinfo if $error;
711 } elsif ( $self->payby eq 'PREPAY' ) {
713 my $payinfo = $self->payinfo;
714 $payinfo =~ s/\W//g; #anything else would just confuse things
715 $self->payinfo($payinfo);
716 $error = $self->ut_alpha('payinfo');
717 return "Illegal prepayment identifier: ". $self->payinfo if $error;
718 return "Unknown prepayment identifier"
719 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
723 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
724 return "Expriation date required"
725 unless $self->payby =~ /^(BILL|PREPAY|CHEK|LECB)$/;
728 $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/
729 or return "Illegal expiration date: ". $self->paydate;
730 my $y = length($2) == 4 ? $2 : "20$2";
731 $self->paydate("$y-$1-01");
732 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
733 return gettext('expired_card')
734 if !$import && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
737 if ( $self->payname eq '' && $self->payby ne 'CHEK' &&
738 ( ! $conf->exists('require_cardname') || $self->payby ne 'CARD' ) ) {
739 $self->payname( $self->first. " ". $self->getfield('last') );
741 $self->payname =~ /^([\w \,\.\-\']+)$/
742 or return gettext('illegal_name'). " payname: ". $self->payname;
746 $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
749 $self->otaker(getotaker);
751 #warn "AFTER: \n". $self->_dump;
758 Returns all packages (see L<FS::cust_pkg>) for this customer.
764 if ( $self->{'_pkgnum'} ) {
765 values %{ $self->{'_pkgnum'}->cache };
767 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
771 =item ncancelled_pkgs
773 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
777 sub ncancelled_pkgs {
779 if ( $self->{'_pkgnum'} ) {
780 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
782 @{ [ # force list context
783 qsearch( 'cust_pkg', {
784 'custnum' => $self->custnum,
787 qsearch( 'cust_pkg', {
788 'custnum' => $self->custnum,
797 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
803 grep { $_->susp } $self->ncancelled_pkgs;
806 =item unflagged_suspended_pkgs
808 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
809 customer (thouse packages without the `manual_flag' set).
813 sub unflagged_suspended_pkgs {
815 return $self->suspended_pkgs
816 unless dbdef->table('cust_pkg')->column('manual_flag');
817 grep { ! $_->manual_flag } $self->suspended_pkgs;
820 =item unsuspended_pkgs
822 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
827 sub unsuspended_pkgs {
829 grep { ! $_->susp } $self->ncancelled_pkgs;
834 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
835 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
836 on success or a list of errors.
842 grep { $_->unsuspend } $self->suspended_pkgs;
847 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
848 Always returns a list: an empty list on success or a list of errors.
854 grep { $_->suspend } $self->unsuspended_pkgs;
859 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
860 Always returns a list: an empty list on success or a list of errors.
866 grep { $_->cancel } $self->ncancelled_pkgs;
871 Returns the agent (see L<FS::agent>) for this customer.
877 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
882 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
883 conjunction with the collect method.
885 Options are passed as name-value pairs.
887 The only currently available option is `time', which bills the customer as if
888 it were that time. It is specified as a UNIX timestamp; see
889 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
890 functions. For example:
894 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
896 If there is an error, returns the error, otherwise returns false.
901 my( $self, %options ) = @_;
902 my $time = $options{'time'} || time;
907 local $SIG{HUP} = 'IGNORE';
908 local $SIG{INT} = 'IGNORE';
909 local $SIG{QUIT} = 'IGNORE';
910 local $SIG{TERM} = 'IGNORE';
911 local $SIG{TSTP} = 'IGNORE';
912 local $SIG{PIPE} = 'IGNORE';
914 my $oldAutoCommit = $FS::UID::AutoCommit;
915 local $FS::UID::AutoCommit = 0;
918 # find the packages which are due for billing, find out how much they are
919 # & generate invoice database.
921 my( $total_setup, $total_recur ) = ( 0, 0 );
922 #my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
923 my @cust_bill_pkg = ();
925 #my $taxable_charged = 0;##
928 foreach my $cust_pkg (
929 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
932 #NO!! next if $cust_pkg->cancel;
933 next if $cust_pkg->getfield('cancel');
935 #? to avoid use of uninitialized value errors... ?
936 $cust_pkg->setfield('bill', '')
937 unless defined($cust_pkg->bill);
939 my $part_pkg = $cust_pkg->part_pkg;
941 #so we don't modify cust_pkg record unnecessarily
942 my $cust_pkg_mod_flag = 0;
943 my %hash = $cust_pkg->hash;
944 my $old_cust_pkg = new FS::cust_pkg \%hash;
948 unless ( $cust_pkg->setup ) {
949 my $setup_prog = $part_pkg->getfield('setup');
950 $setup_prog =~ /^(.*)$/ or do {
951 $dbh->rollback if $oldAutoCommit;
952 return "Illegal setup for pkgpart ". $part_pkg->pkgpart.
958 ##$cpt->permit(); #what is necessary?
959 #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
960 #$setup = $cpt->reval($setup_prog);
961 $setup = eval $setup_prog;
962 unless ( defined($setup) ) {
963 $dbh->rollback if $oldAutoCommit;
964 return "Error eval-ing part_pkg->setup pkgpart ". $part_pkg->pkgpart.
965 "(expression $setup_prog): $@";
967 $cust_pkg->setfield('setup',$time);
968 $cust_pkg_mod_flag=1;
974 if ( $part_pkg->getfield('freq') > 0 &&
975 ! $cust_pkg->getfield('susp') &&
976 ( $cust_pkg->getfield('bill') || 0 ) <= $time
978 my $recur_prog = $part_pkg->getfield('recur');
979 $recur_prog =~ /^(.*)$/ or do {
980 $dbh->rollback if $oldAutoCommit;
981 return "Illegal recur for pkgpart ". $part_pkg->pkgpart.
986 # shared with $recur_prog
987 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
990 ##$cpt->permit(); #what is necessary?
991 #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
992 #$recur = $cpt->reval($recur_prog);
993 $recur = eval $recur_prog;
994 unless ( defined($recur) ) {
995 $dbh->rollback if $oldAutoCommit;
996 return "Error eval-ing part_pkg->recur pkgpart ". $part_pkg->pkgpart.
997 "(expression $recur_prog): $@";
999 #change this bit to use Date::Manip? CAREFUL with timezones (see
1000 # mailing list archive)
1001 my ($sec,$min,$hour,$mday,$mon,$year) =
1002 (localtime($sdate) )[0,1,2,3,4,5];
1004 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1005 # only for figuring next bill date, nothing else, so, reset $sdate again
1007 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1008 $cust_pkg->last_bill($sdate)
1009 if $cust_pkg->dbdef_table->column('last_bill');
1011 $mon += $part_pkg->freq;
1012 until ( $mon < 12 ) { $mon -= 12; $year++; }
1013 $cust_pkg->setfield('bill',
1014 timelocal($sec,$min,$hour,$mday,$mon,$year));
1015 $cust_pkg_mod_flag = 1;
1018 warn "\$setup is undefined" unless defined($setup);
1019 warn "\$recur is undefined" unless defined($recur);
1020 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1022 my $taxable_charged = 0;
1023 if ( $cust_pkg_mod_flag ) {
1024 $error=$cust_pkg->replace($old_cust_pkg);
1025 if ( $error ) { #just in case
1026 $dbh->rollback if $oldAutoCommit;
1027 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1029 $setup = sprintf( "%.2f", $setup );
1030 $recur = sprintf( "%.2f", $recur );
1032 $dbh->rollback if $oldAutoCommit;
1033 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1036 $dbh->rollback if $oldAutoCommit;
1037 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1039 if ( $setup > 0 || $recur > 0 ) {
1040 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1041 'pkgnum' => $cust_pkg->pkgnum,
1045 'edate' => $cust_pkg->bill,
1047 push @cust_bill_pkg, $cust_bill_pkg;
1048 $total_setup += $setup;
1049 $total_recur += $recur;
1050 $taxable_charged += $setup
1051 unless $part_pkg->setuptax =~ /^Y$/i;
1052 $taxable_charged += $recur
1053 unless $part_pkg->recurtax =~ /^Y$/i;
1055 unless ( $self->tax =~ /Y/i
1056 || $self->payby eq 'COMP'
1057 || $taxable_charged == 0 ) {
1059 my $cust_main_county = qsearchs('cust_main_county',{
1060 'state' => $self->state,
1061 'county' => $self->county,
1062 'country' => $self->country,
1063 'taxclass' => $part_pkg->taxclass,
1065 $cust_main_county ||= qsearchs('cust_main_county',{
1066 'state' => $self->state,
1067 'county' => $self->county,
1068 'country' => $self->country,
1071 unless ( $cust_main_county ) {
1072 $dbh->rollback if $oldAutoCommit;
1074 "fatal: can't find tax rate for state/county/country/taxclass ".
1075 join('/', ( map $self->$_(), qw(state county country) ),
1076 $part_pkg->taxclass ). "\n";
1079 if ( $cust_main_county->exempt_amount ) {
1080 my ($mon,$year) = (localtime($sdate) )[4,5];
1082 my $freq = $part_pkg->freq || 1;
1083 my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1084 foreach my $which_month ( 1 .. $freq ) {
1086 'custnum' => $self->custnum,
1087 'taxnum' => $cust_main_county->taxnum,
1088 'year' => 1900+$year,
1091 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1092 until ( $mon < 13 ) { $mon -= 12; $year++; }
1093 my $cust_tax_exempt =
1094 qsearchs('cust_tax_exempt', \%hash)
1095 || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1096 my $remaining_exemption = sprintf("%.2f",
1097 $cust_main_county->exempt_amount - $cust_tax_exempt->amount );
1098 if ( $remaining_exemption > 0 ) {
1099 my $addl = $remaining_exemption > $taxable_per_month
1100 ? $taxable_per_month
1101 : $remaining_exemption;
1102 $taxable_charged -= $addl;
1103 my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1104 $cust_tax_exempt->hash,
1105 'amount' => sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1107 $error = $new_cust_tax_exempt->exemptnum
1108 ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1109 : $new_cust_tax_exempt->insert;
1111 $dbh->rollback if $oldAutoCommit;
1112 return "fatal: can't update cust_tax_exempt: $error";
1115 } # if $remaining_exemption > 0
1117 } #foreach $which_month
1119 } #if $cust_main_county->exempt_amount
1121 $taxable_charged = sprintf( "%.2f", $taxable_charged);
1122 $tax += $taxable_charged * $cust_main_county->tax / 100
1124 } #unless $self->tax =~ /Y/i
1125 # || $self->payby eq 'COMP'
1126 # || $taxable_charged == 0
1128 } #if $setup > 0 || $recur > 0
1130 } #if $cust_pkg_mod_flag
1132 } #foreach my $cust_pkg
1134 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1135 # my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1137 unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1138 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1142 # unless ( $self->tax =~ /Y/i
1143 # || $self->payby eq 'COMP'
1144 # || $taxable_charged == 0 ) {
1145 # my $cust_main_county = qsearchs('cust_main_county',{
1146 # 'state' => $self->state,
1147 # 'county' => $self->county,
1148 # 'country' => $self->country,
1149 # } ) or die "fatal: can't find tax rate for state/county/country ".
1150 # $self->state. "/". $self->county. "/". $self->country. "\n";
1151 # my $tax = sprintf( "%.2f",
1152 # $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1155 $tax = sprintf("%.2f", $tax);
1157 $charged = sprintf( "%.2f", $charged+$tax );
1159 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1166 push @cust_bill_pkg, $cust_bill_pkg;
1170 my $cust_bill = new FS::cust_bill ( {
1171 'custnum' => $self->custnum,
1173 'charged' => $charged,
1175 $error = $cust_bill->insert;
1177 $dbh->rollback if $oldAutoCommit;
1178 return "can't create invoice for customer #". $self->custnum. ": $error";
1181 my $invnum = $cust_bill->invnum;
1183 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1185 $cust_bill_pkg->invnum($invnum);
1186 $error = $cust_bill_pkg->insert;
1188 $dbh->rollback if $oldAutoCommit;
1189 return "can't create invoice line item for customer #". $self->custnum.
1194 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1198 =item collect OPTIONS
1200 (Attempt to) collect money for this customer's outstanding invoices (see
1201 L<FS::cust_bill>). Usually used after the bill method.
1203 Depending on the value of `payby', this may print an invoice (`BILL'), charge
1204 a credit card (`CARD'), or just add any necessary (pseudo-)payment (`COMP').
1206 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1207 and the invoice events web interface.
1209 If there is an error, returns the error, otherwise returns false.
1211 Options are passed as name-value pairs.
1213 Currently available options are:
1215 invoice_time - Use this time when deciding when to print invoices and
1216 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>
1217 for conversion functions.
1219 retry_card - Retry cards even when not scheduled by invoice events.
1221 batch_card - This option is deprecated. See the invoice events web interface
1222 to control whether cards are batched or run against a realtime gateway.
1224 report_badcard - This option is deprecated.
1226 force_print - This option is deprecated; see the invoice events web interface.
1231 my( $self, %options ) = @_;
1232 my $invoice_time = $options{'invoice_time'} || time;
1235 local $SIG{HUP} = 'IGNORE';
1236 local $SIG{INT} = 'IGNORE';
1237 local $SIG{QUIT} = 'IGNORE';
1238 local $SIG{TERM} = 'IGNORE';
1239 local $SIG{TSTP} = 'IGNORE';
1240 local $SIG{PIPE} = 'IGNORE';
1242 my $oldAutoCommit = $FS::UID::AutoCommit;
1243 local $FS::UID::AutoCommit = 0;
1246 my $balance = $self->balance;
1247 warn "collect customer". $self->custnum. ": balance $balance" if $Debug;
1248 unless ( $balance > 0 ) { #redundant?????
1249 $dbh->rollback if $oldAutoCommit; #hmm
1253 if ( exists($options{'retry_card'}) && $options{'retry_card'} ) {
1254 #false laziness w/replace
1255 foreach my $cust_bill_event (
1257 #$_->part_bill_event->plan eq 'realtime-card'
1258 $_->part_bill_event->eventcode eq '$cust_bill->realtime_card();'
1259 && $_->status eq 'done'
1262 map { $_->cust_bill_event }
1263 grep { $_->cust_bill_event }
1264 $self->open_cust_bill
1266 my $error = $cust_bill_event->retry;
1268 $dbh->rollback if $oldAutoCommit;
1269 return "error scheduling invoice events for retry: $error";
1275 foreach my $cust_bill ( $self->cust_bill ) {
1277 #this has to be before next's
1278 my $amount = sprintf( "%.2f", $balance < $cust_bill->owed
1282 $balance = sprintf( "%.2f", $balance - $amount );
1284 next unless $cust_bill->owed > 0;
1286 # don't try to charge for the same invoice if it's already in a batch
1287 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1289 warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ", amount $amount, balance $balance)" if $Debug;
1291 next unless $amount > 0;
1294 foreach my $part_bill_event (
1295 sort { $a->seconds <=> $b->seconds
1296 || $a->weight <=> $b->weight
1297 || $a->eventpart <=> $b->eventpart }
1298 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1299 && ! qsearchs( 'cust_bill_event', {
1300 'invnum' => $cust_bill->invnum,
1301 'eventpart' => $_->eventpart,
1305 qsearch('part_bill_event', { 'payby' => $self->payby,
1306 'disabled' => '', } )
1309 last unless $cust_bill->owed > 0; #don't run subsequent events if owed=0
1311 warn "calling invoice event (". $part_bill_event->eventcode. ")\n"
1313 my $cust_main = $self; #for callback
1314 my $error = eval $part_bill_event->eventcode;
1317 my $statustext = '';
1321 } elsif ( $error ) {
1323 $statustext = $error;
1328 #add cust_bill_event
1329 my $cust_bill_event = new FS::cust_bill_event {
1330 'invnum' => $cust_bill->invnum,
1331 'eventpart' => $part_bill_event->eventpart,
1332 #'_date' => $invoice_time,
1334 'status' => $status,
1335 'statustext' => $statustext,
1337 $error = $cust_bill_event->insert;
1339 #$dbh->rollback if $oldAutoCommit;
1340 #return "error: $error";
1342 # gah, even with transactions.
1343 $dbh->commit if $oldAutoCommit; #well.
1344 my $e = 'WARNING: Event run but database not updated - '.
1345 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
1346 ', eventpart '. $part_bill_event->eventpart.
1357 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1364 Returns the total owed for this customer on all invoices
1365 (see L<FS::cust_bill/owed>).
1371 $self->total_owed_date(2145859200); #12/31/2037
1374 =item total_owed_date TIME
1376 Returns the total owed for this customer on all invoices with date earlier than
1377 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
1378 see L<Time::Local> and L<Date::Parse> for conversion functions.
1382 sub total_owed_date {
1386 foreach my $cust_bill (
1387 grep { $_->_date <= $time }
1388 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
1390 $total_bill += $cust_bill->owed;
1392 sprintf( "%.2f", $total_bill );
1397 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
1398 to outstanding invoice balances in chronological order and returns the value
1399 of any remaining unapplied credits available for refund
1400 (see L<FS::cust_refund>).
1407 return 0 unless $self->total_credited;
1409 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
1410 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
1412 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1413 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1417 foreach my $cust_bill ( @invoices ) {
1420 if ( !defined($credit) || $credit->credited == 0) {
1421 $credit = pop @credits or last;
1424 if ($cust_bill->owed >= $credit->credited) {
1425 $amount=$credit->credited;
1427 $amount=$cust_bill->owed;
1430 my $cust_credit_bill = new FS::cust_credit_bill ( {
1431 'crednum' => $credit->crednum,
1432 'invnum' => $cust_bill->invnum,
1433 'amount' => $amount,
1435 my $error = $cust_credit_bill->insert;
1436 die $error if $error;
1438 redo if ($cust_bill->owed > 0);
1442 return $self->total_credited;
1445 =item apply_payments
1447 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
1448 to outstanding invoice balances in chronological order.
1450 #and returns the value of any remaining unapplied payments.
1454 sub apply_payments {
1459 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
1460 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
1462 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1463 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1467 foreach my $cust_bill ( @invoices ) {
1470 if ( !defined($payment) || $payment->unapplied == 0 ) {
1471 $payment = pop @payments or last;
1474 if ( $cust_bill->owed >= $payment->unapplied ) {
1475 $amount = $payment->unapplied;
1477 $amount = $cust_bill->owed;
1480 my $cust_bill_pay = new FS::cust_bill_pay ( {
1481 'paynum' => $payment->paynum,
1482 'invnum' => $cust_bill->invnum,
1483 'amount' => $amount,
1485 my $error = $cust_bill_pay->insert;
1486 die $error if $error;
1488 redo if ( $cust_bill->owed > 0);
1492 return $self->total_unapplied_payments;
1495 =item total_credited
1497 Returns the total outstanding credit (see L<FS::cust_credit>) for this
1498 customer. See L<FS::cust_credit/credited>.
1502 sub total_credited {
1504 my $total_credit = 0;
1505 foreach my $cust_credit ( qsearch('cust_credit', {
1506 'custnum' => $self->custnum,
1508 $total_credit += $cust_credit->credited;
1510 sprintf( "%.2f", $total_credit );
1513 =item total_unapplied_payments
1515 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
1516 See L<FS::cust_pay/unapplied>.
1520 sub total_unapplied_payments {
1522 my $total_unapplied = 0;
1523 foreach my $cust_pay ( qsearch('cust_pay', {
1524 'custnum' => $self->custnum,
1526 $total_unapplied += $cust_pay->unapplied;
1528 sprintf( "%.2f", $total_unapplied );
1533 Returns the balance for this customer (total_owed minus total_credited
1534 minus total_unapplied_payments).
1541 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
1545 =item balance_date TIME
1547 Returns the balance for this customer, only considering invoices with date
1548 earlier than TIME (total_owed_date minus total_credited minus
1549 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
1550 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
1559 $self->total_owed_date($time)
1560 - $self->total_credited
1561 - $self->total_unapplied_payments
1565 =item invoicing_list [ ARRAYREF ]
1567 If an arguement is given, sets these email addresses as invoice recipients
1568 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
1569 (except as warnings), so use check_invoicing_list first.
1571 Returns a list of email addresses (with svcnum entries expanded).
1573 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
1574 check it without disturbing anything by passing nothing.
1576 This interface may change in the future.
1580 sub invoicing_list {
1581 my( $self, $arrayref ) = @_;
1583 my @cust_main_invoice;
1584 if ( $self->custnum ) {
1585 @cust_main_invoice =
1586 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1588 @cust_main_invoice = ();
1590 foreach my $cust_main_invoice ( @cust_main_invoice ) {
1591 #warn $cust_main_invoice->destnum;
1592 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
1593 #warn $cust_main_invoice->destnum;
1594 my $error = $cust_main_invoice->delete;
1595 warn $error if $error;
1598 if ( $self->custnum ) {
1599 @cust_main_invoice =
1600 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1602 @cust_main_invoice = ();
1604 my %seen = map { $_->address => 1 } @cust_main_invoice;
1605 foreach my $address ( @{$arrayref} ) {
1606 next if exists $seen{$address} && $seen{$address};
1607 $seen{$address} = 1;
1608 my $cust_main_invoice = new FS::cust_main_invoice ( {
1609 'custnum' => $self->custnum,
1612 my $error = $cust_main_invoice->insert;
1613 warn $error if $error;
1616 if ( $self->custnum ) {
1618 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1624 =item check_invoicing_list ARRAYREF
1626 Checks these arguements as valid input for the invoicing_list method. If there
1627 is an error, returns the error, otherwise returns false.
1631 sub check_invoicing_list {
1632 my( $self, $arrayref ) = @_;
1633 foreach my $address ( @{$arrayref} ) {
1634 my $cust_main_invoice = new FS::cust_main_invoice ( {
1635 'custnum' => $self->custnum,
1638 my $error = $self->custnum
1639 ? $cust_main_invoice->check
1640 : $cust_main_invoice->checkdest
1642 return $error if $error;
1647 =item set_default_invoicing_list
1649 Sets the invoicing list to all accounts associated with this customer,
1650 overwriting any previous invoicing list.
1654 sub set_default_invoicing_list {
1656 $self->invoicing_list($self->all_emails);
1661 Returns the email addresses of all accounts provisioned for this customer.
1668 foreach my $cust_pkg ( $self->all_pkgs ) {
1669 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
1671 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1672 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1674 $list{$_}=1 foreach map { $_->email } @svc_acct;
1679 =item invoicing_list_addpost
1681 Adds postal invoicing to this customer. If this customer is already configured
1682 to receive postal invoices, does nothing.
1686 sub invoicing_list_addpost {
1688 return if grep { $_ eq 'POST' } $self->invoicing_list;
1689 my @invoicing_list = $self->invoicing_list;
1690 push @invoicing_list, 'POST';
1691 $self->invoicing_list(\@invoicing_list);
1694 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
1696 Returns an array of customers referred by this customer (referral_custnum set
1697 to this custnum). If DEPTH is given, recurses up to the given depth, returning
1698 customers referred by customers referred by this customer and so on, inclusive.
1699 The default behavior is DEPTH 1 (no recursion).
1703 sub referral_cust_main {
1705 my $depth = @_ ? shift : 1;
1706 my $exclude = @_ ? shift : {};
1709 map { $exclude->{$_->custnum}++; $_; }
1710 grep { ! $exclude->{ $_->custnum } }
1711 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
1715 map { $_->referral_cust_main($depth-1, $exclude) }
1722 =item referral_cust_main_ncancelled
1724 Same as referral_cust_main, except only returns customers with uncancelled
1729 sub referral_cust_main_ncancelled {
1731 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
1734 =item referral_cust_pkg [ DEPTH ]
1736 Like referral_cust_main, except returns a flat list of all unsuspended (and
1737 uncancelled) packages for each customer. The number of items in this list may
1738 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
1742 sub referral_cust_pkg {
1744 my $depth = @_ ? shift : 1;
1746 map { $_->unsuspended_pkgs }
1747 grep { $_->unsuspended_pkgs }
1748 $self->referral_cust_main($depth);
1751 =item credit AMOUNT, REASON
1753 Applies a credit to this customer. If there is an error, returns the error,
1754 otherwise returns false.
1759 my( $self, $amount, $reason ) = @_;
1760 my $cust_credit = new FS::cust_credit {
1761 'custnum' => $self->custnum,
1762 'amount' => $amount,
1763 'reason' => $reason,
1765 $cust_credit->insert;
1768 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
1770 Creates a one-time charge for this customer. If there is an error, returns
1771 the error, otherwise returns false.
1776 my ( $self, $amount ) = ( shift, shift );
1777 my $pkg = @_ ? shift : 'One-time charge';
1778 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
1779 my $taxclass = @_ ? shift : '';
1781 local $SIG{HUP} = 'IGNORE';
1782 local $SIG{INT} = 'IGNORE';
1783 local $SIG{QUIT} = 'IGNORE';
1784 local $SIG{TERM} = 'IGNORE';
1785 local $SIG{TSTP} = 'IGNORE';
1786 local $SIG{PIPE} = 'IGNORE';
1788 my $oldAutoCommit = $FS::UID::AutoCommit;
1789 local $FS::UID::AutoCommit = 0;
1792 my $part_pkg = new FS::part_pkg ( {
1794 'comment' => $comment,
1799 'taxclass' => $taxclass,
1802 my $error = $part_pkg->insert;
1804 $dbh->rollback if $oldAutoCommit;
1808 my $pkgpart = $part_pkg->pkgpart;
1809 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
1810 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
1811 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
1812 $error = $type_pkgs->insert;
1814 $dbh->rollback if $oldAutoCommit;
1819 my $cust_pkg = new FS::cust_pkg ( {
1820 'custnum' => $self->custnum,
1821 'pkgpart' => $pkgpart,
1824 $error = $cust_pkg->insert;
1826 $dbh->rollback if $oldAutoCommit;
1830 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1837 Returns all the invoices (see L<FS::cust_bill>) for this customer.
1843 sort { $a->_date <=> $b->_date }
1844 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
1847 =item open_cust_bill
1849 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
1854 sub open_cust_bill {
1856 grep { $_->owed > 0 } $self->cust_bill;
1865 =item check_and_rebuild_fuzzyfiles
1869 sub check_and_rebuild_fuzzyfiles {
1870 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1871 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
1872 or &rebuild_fuzzyfiles;
1875 =item rebuild_fuzzyfiles
1879 sub rebuild_fuzzyfiles {
1881 use Fcntl qw(:flock);
1883 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1887 open(LASTLOCK,">>$dir/cust_main.last")
1888 or die "can't open $dir/cust_main.last: $!";
1889 flock(LASTLOCK,LOCK_EX)
1890 or die "can't lock $dir/cust_main.last: $!";
1892 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
1894 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
1895 if defined dbdef->table('cust_main')->column('ship_last');
1897 open (LASTCACHE,">$dir/cust_main.last.tmp")
1898 or die "can't open $dir/cust_main.last.tmp: $!";
1899 print LASTCACHE join("\n", @all_last), "\n";
1900 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
1902 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
1907 open(COMPANYLOCK,">>$dir/cust_main.company")
1908 or die "can't open $dir/cust_main.company: $!";
1909 flock(COMPANYLOCK,LOCK_EX)
1910 or die "can't lock $dir/cust_main.company: $!";
1912 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
1914 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
1915 if defined dbdef->table('cust_main')->column('ship_last');
1917 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
1918 or die "can't open $dir/cust_main.company.tmp: $!";
1919 print COMPANYCACHE join("\n", @all_company), "\n";
1920 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
1922 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
1932 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1933 open(LASTCACHE,"<$dir/cust_main.last")
1934 or die "can't open $dir/cust_main.last: $!";
1935 my @array = map { chomp; $_; } <LASTCACHE>;
1945 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1946 open(COMPANYCACHE,"<$dir/cust_main.company")
1947 or die "can't open $dir/cust_main.last: $!";
1948 my @array = map { chomp; $_; } <COMPANYCACHE>;
1953 =item append_fuzzyfiles LASTNAME COMPANY
1957 sub append_fuzzyfiles {
1958 my( $last, $company ) = @_;
1960 &check_and_rebuild_fuzzyfiles;
1962 use Fcntl qw(:flock);
1964 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1968 open(LAST,">>$dir/cust_main.last")
1969 or die "can't open $dir/cust_main.last: $!";
1971 or die "can't lock $dir/cust_main.last: $!";
1973 print LAST "$last\n";
1976 or die "can't unlock $dir/cust_main.last: $!";
1982 open(COMPANY,">>$dir/cust_main.company")
1983 or die "can't open $dir/cust_main.company: $!";
1984 flock(COMPANY,LOCK_EX)
1985 or die "can't lock $dir/cust_main.company: $!";
1987 print COMPANY "$company\n";
1989 flock(COMPANY,LOCK_UN)
1990 or die "can't unlock $dir/cust_main.company: $!";
2004 #warn join('-',keys %$param);
2005 my $fh = $param->{filehandle};
2006 my $agentnum = $param->{agentnum};
2007 my $refnum = $param->{refnum};
2008 my $pkgpart = $param->{pkgpart};
2009 my @fields = @{$param->{fields}};
2011 eval "use Date::Parse;";
2013 eval "use Text::CSV_XS;";
2016 my $csv = new Text::CSV_XS;
2023 local $SIG{HUP} = 'IGNORE';
2024 local $SIG{INT} = 'IGNORE';
2025 local $SIG{QUIT} = 'IGNORE';
2026 local $SIG{TERM} = 'IGNORE';
2027 local $SIG{TSTP} = 'IGNORE';
2028 local $SIG{PIPE} = 'IGNORE';
2030 my $oldAutoCommit = $FS::UID::AutoCommit;
2031 local $FS::UID::AutoCommit = 0;
2034 #while ( $columns = $csv->getline($fh) ) {
2036 while ( defined($line=<$fh>) ) {
2038 $csv->parse($line) or do {
2039 $dbh->rollback if $oldAutoCommit;
2040 return "can't parse: ". $csv->error_input();
2043 my @columns = $csv->fields();
2044 #warn join('-',@columns);
2047 agentnum => $agentnum,
2049 country => 'US', #default
2050 payby => 'BILL', #default
2051 paydate => '12/2037', #default
2053 my $billtime = time;
2054 my %cust_pkg = ( pkgpart => $pkgpart );
2055 foreach my $field ( @fields ) {
2056 if ( $field =~ /^cust_pkg\.(setup|bill|susp|expire|cancel)$/ ) {
2057 #$cust_pkg{$1} = str2time( shift @$columns );
2058 if ( $1 eq 'setup' ) {
2059 $billtime = str2time(shift @columns);
2061 $cust_pkg{$1} = str2time( shift @columns );
2064 #$cust_main{$field} = shift @$columns;
2065 $cust_main{$field} = shift @columns;
2069 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg ) if $pkgpart;
2070 my $cust_main = new FS::cust_main ( \%cust_main );
2072 tie my %hash, 'Tie::RefHash'; #this part is important
2073 $hash{$cust_pkg} = [] if $pkgpart;
2074 my $error = $cust_main->insert( \%hash );
2077 $dbh->rollback if $oldAutoCommit;
2078 return "can't insert customer for $line: $error";
2081 #false laziness w/bill.cgi
2082 $error = $cust_main->bill( 'time' => $billtime );
2084 $dbh->rollback if $oldAutoCommit;
2085 return "can't bill customer for $line: $error";
2088 $cust_main->apply_payments;
2089 $cust_main->apply_credits;
2091 $error = $cust_main->collect();
2093 $dbh->rollback if $oldAutoCommit;
2094 return "can't collect customer for $line: $error";
2100 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2102 return "Empty file!" unless $imported;
2114 #warn join('-',keys %$param);
2115 my $fh = $param->{filehandle};
2116 my @fields = @{$param->{fields}};
2118 eval "use Date::Parse;";
2120 eval "use Text::CSV_XS;";
2123 my $csv = new Text::CSV_XS;
2130 local $SIG{HUP} = 'IGNORE';
2131 local $SIG{INT} = 'IGNORE';
2132 local $SIG{QUIT} = 'IGNORE';
2133 local $SIG{TERM} = 'IGNORE';
2134 local $SIG{TSTP} = 'IGNORE';
2135 local $SIG{PIPE} = 'IGNORE';
2137 my $oldAutoCommit = $FS::UID::AutoCommit;
2138 local $FS::UID::AutoCommit = 0;
2141 #while ( $columns = $csv->getline($fh) ) {
2143 while ( defined($line=<$fh>) ) {
2145 $csv->parse($line) or do {
2146 $dbh->rollback if $oldAutoCommit;
2147 return "can't parse: ". $csv->error_input();
2150 my @columns = $csv->fields();
2151 #warn join('-',@columns);
2154 foreach my $field ( @fields ) {
2155 $row{$field} = shift @columns;
2158 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
2159 unless ( $cust_main ) {
2160 $dbh->rollback if $oldAutoCommit;
2161 return "unknown custnum $row{'custnum'}";
2164 if ( $row{'amount'} > 0 ) {
2165 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
2167 $dbh->rollback if $oldAutoCommit;
2171 } elsif ( $row{'amount'} < 0 ) {
2172 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
2175 $dbh->rollback if $oldAutoCommit;
2185 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2187 return "Empty file!" unless $imported;
2199 The delete method should possibly take an FS::cust_main object reference
2200 instead of a scalar customer number.
2202 Bill and collect options should probably be passed as references instead of a
2205 There should probably be a configuration file with a list of allowed credit
2208 No multiple currency support (probably a larger project than just this module).
2212 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
2213 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
2214 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.