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;
30 use FS::Msgcat qw(gettext);
32 @ISA = qw( FS::Record );
39 #ask FS::UID to run this stuff for us later
40 $FS::UID::callback{'FS::cust_main'} = sub {
42 #yes, need it for stuff below (prolly should be cached)
47 my ( $hashref, $cache ) = @_;
48 if ( exists $hashref->{'pkgnum'} ) {
49 # #@{ $self->{'_pkgnum'} } = ();
50 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
51 $self->{'_pkgnum'} = $subcache;
52 #push @{ $self->{'_pkgnum'} },
53 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
59 FS::cust_main - Object methods for cust_main records
65 $record = new FS::cust_main \%hash;
66 $record = new FS::cust_main { 'column' => 'value' };
68 $error = $record->insert;
70 $error = $new_record->replace($old_record);
72 $error = $record->delete;
74 $error = $record->check;
76 @cust_pkg = $record->all_pkgs;
78 @cust_pkg = $record->ncancelled_pkgs;
80 @cust_pkg = $record->suspended_pkgs;
82 $error = $record->bill;
83 $error = $record->bill %options;
84 $error = $record->bill 'time' => $time;
86 $error = $record->collect;
87 $error = $record->collect %options;
88 $error = $record->collect 'invoice_time' => $time,
89 'batch_card' => 'yes',
90 'report_badcard' => 'yes',
95 An FS::cust_main object represents a customer. FS::cust_main inherits from
96 FS::Record. The following fields are currently supported:
100 =item custnum - primary key (assigned automatically for new customers)
102 =item agentnum - agent (see L<FS::agent>)
104 =item refnum - Advertising source (see L<FS::part_referral>)
110 =item ss - social security number (optional)
112 =item company - (optional)
116 =item address2 - (optional)
120 =item county - (optional, see L<FS::cust_main_county>)
122 =item state - (see L<FS::cust_main_county>)
126 =item country - (see L<FS::cust_main_county>)
128 =item daytime - phone (optional)
130 =item night - phone (optional)
132 =item fax - phone (optional)
134 =item ship_first - name
136 =item ship_last - name
138 =item ship_company - (optional)
142 =item ship_address2 - (optional)
146 =item ship_county - (optional, see L<FS::cust_main_county>)
148 =item ship_state - (see L<FS::cust_main_county>)
152 =item ship_country - (see L<FS::cust_main_county>)
154 =item ship_daytime - phone (optional)
156 =item ship_night - phone (optional)
158 =item ship_fax - phone (optional)
160 =item payby - `CARD' (credit cards), `BILL' (billing), `COMP' (free), or `PREPAY' (special billing type: applies a credit - see L<FS::prepay_credit> and sets billing type to BILL)
162 =item payinfo - card number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
164 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
166 =item payname - name on card or billing name
168 =item tax - tax exempt, empty or `Y'
170 =item otaker - order taker (assigned automatically, see L<FS::UID>)
172 =item comments - comments (optional)
182 Creates a new customer. To add the customer to the database, see L<"insert">.
184 Note that this stores the hash reference, not a distinct copy of the hash it
185 points to. You can ask the object for a copy with the I<hash> method.
189 sub table { 'cust_main'; }
191 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] ]
193 Adds this customer to the database. If there is an error, returns the error,
194 otherwise returns false.
196 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
197 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
198 are inserted atomicly, or the transaction is rolled back. Passing an empty
199 hash reference is equivalent to not supplying this parameter. There should be
200 a better explanation of this, but until then, here's an example:
203 tie %hash, 'Tie::RefHash'; #this part is important
205 $cust_pkg => [ $svc_acct ],
208 $cust_main->insert( \%hash );
210 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
211 be set as the invoicing list (see L<"invoicing_list">). Errors return as
212 expected and rollback the entire transaction; it is not necessary to call
213 check_invoicing_list first. The invoicing_list is set after the records in the
214 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
215 invoicing_list destination to the newly-created svc_acct. Here's an example:
217 $cust_main->insert( {}, [ $email, 'POST' ] );
225 local $SIG{HUP} = 'IGNORE';
226 local $SIG{INT} = 'IGNORE';
227 local $SIG{QUIT} = 'IGNORE';
228 local $SIG{TERM} = 'IGNORE';
229 local $SIG{TSTP} = 'IGNORE';
230 local $SIG{PIPE} = 'IGNORE';
232 my $oldAutoCommit = $FS::UID::AutoCommit;
233 local $FS::UID::AutoCommit = 0;
238 if ( $self->payby eq 'PREPAY' ) {
239 $self->payby('BILL');
240 my $prepay_credit = qsearchs(
242 { 'identifier' => $self->payinfo },
246 warn "WARNING: can't find pre-found prepay_credit: ". $self->payinfo
247 unless $prepay_credit;
248 $amount = $prepay_credit->amount;
249 $seconds = $prepay_credit->seconds;
250 my $error = $prepay_credit->delete;
252 $dbh->rollback if $oldAutoCommit;
253 return "removing prepay_credit (transaction rolled back): $error";
257 my $error = $self->SUPER::insert;
259 $dbh->rollback if $oldAutoCommit;
260 #return "inserting cust_main record (transaction rolled back): $error";
264 if ( @param ) { # CUST_PKG_HASHREF
265 my $cust_pkgs = shift @param;
266 foreach my $cust_pkg ( keys %$cust_pkgs ) {
267 $cust_pkg->custnum( $self->custnum );
268 $error = $cust_pkg->insert;
270 $dbh->rollback if $oldAutoCommit;
271 return "inserting cust_pkg (transaction rolled back): $error";
273 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
274 $svc_something->pkgnum( $cust_pkg->pkgnum );
275 if ( $seconds && $svc_something->isa('FS::svc_acct') ) {
276 $svc_something->seconds( $svc_something->seconds + $seconds );
279 $error = $svc_something->insert;
281 $dbh->rollback if $oldAutoCommit;
282 #return "inserting svc_ (transaction rolled back): $error";
290 $dbh->rollback if $oldAutoCommit;
291 return "No svc_acct record to apply pre-paid time";
294 if ( @param ) { # INVOICING_LIST_ARYREF
295 my $invoicing_list = shift @param;
296 $error = $self->check_invoicing_list( $invoicing_list );
298 $dbh->rollback if $oldAutoCommit;
299 return "checking invoicing_list (transaction rolled back): $error";
301 $self->invoicing_list( $invoicing_list );
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 eq 'CARD' &&
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 eq '$cust_bill->realtime_card();'
493 && $_->status eq 'done'
496 $self->open_cust_bill->cust_bill_event
498 my $error = $cust_bill_event->retry;
500 $dbh->rollback if $oldAutoCommit;
501 return "error scheduling invoice events for retry: $error";
508 #false laziness with sub insert
509 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
510 $error = $queue->insert($self->getfield('last'), $self->company);
512 $dbh->rollback if $oldAutoCommit;
513 return "queueing job (transaction rolled back): $error";
516 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
517 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
518 $error = $queue->insert($self->getfield('last'), $self->company);
520 $dbh->rollback if $oldAutoCommit;
521 return "queueing job (transaction rolled back): $error";
526 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
533 Checks all fields to make sure this is a valid customer record. If there is
534 an error, returns the error, otherwise returns false. Called by the insert
542 #warn "BEFORE: \n". $self->_dump;
545 $self->ut_numbern('custnum')
546 || $self->ut_number('agentnum')
547 || $self->ut_number('refnum')
548 || $self->ut_name('last')
549 || $self->ut_name('first')
550 || $self->ut_textn('company')
551 || $self->ut_text('address1')
552 || $self->ut_textn('address2')
553 || $self->ut_text('city')
554 || $self->ut_textn('county')
555 || $self->ut_textn('state')
556 || $self->ut_country('country')
557 || $self->ut_anything('comments')
558 || $self->ut_numbern('referral_custnum')
560 #barf. need message catalogs. i18n. etc.
561 $error .= "Please select a advertising source."
562 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
563 return $error if $error;
565 return "Unknown agent"
566 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
568 return "Unknown refnum"
569 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
571 return "Unknown referring custnum ". $self->referral_custnum
572 unless ! $self->referral_custnum
573 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
575 if ( $self->ss eq '' ) {
580 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
581 or return "Illegal social security number: ". $self->ss;
582 $self->ss("$1-$2-$3");
586 # bad idea to disable, causes billing to fail because of no tax rates later
587 # unless ( $import ) {
588 unless ( qsearchs('cust_main_county', {
589 'country' => $self->country,
592 return "Unknown state/county/country: ".
593 $self->state. "/". $self->county. "/". $self->country
594 unless qsearchs('cust_main_county',{
595 'state' => $self->state,
596 'county' => $self->county,
597 'country' => $self->country,
603 $self->ut_phonen('daytime', $self->country)
604 || $self->ut_phonen('night', $self->country)
605 || $self->ut_phonen('fax', $self->country)
606 || $self->ut_zip('zip', $self->country)
608 return $error if $error;
611 last first company address1 address2 city county state zip
612 country daytime night fax
615 if ( defined $self->dbdef_table->column('ship_last') ) {
616 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
618 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
622 $self->ut_name('ship_last')
623 || $self->ut_name('ship_first')
624 || $self->ut_textn('ship_company')
625 || $self->ut_text('ship_address1')
626 || $self->ut_textn('ship_address2')
627 || $self->ut_text('ship_city')
628 || $self->ut_textn('ship_county')
629 || $self->ut_textn('ship_state')
630 || $self->ut_country('ship_country')
632 return $error if $error;
634 #false laziness with above
635 unless ( qsearchs('cust_main_county', {
636 'country' => $self->ship_country,
639 return "Unknown ship_state/ship_county/ship_country: ".
640 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
641 unless qsearchs('cust_main_county',{
642 'state' => $self->ship_state,
643 'county' => $self->ship_county,
644 'country' => $self->ship_country,
650 $self->ut_phonen('ship_daytime', $self->ship_country)
651 || $self->ut_phonen('ship_night', $self->ship_country)
652 || $self->ut_phonen('ship_fax', $self->ship_country)
653 || $self->ut_zip('ship_zip', $self->ship_country)
655 return $error if $error;
657 } else { # ship_ info eq billing info, so don't store dup info in database
658 $self->setfield("ship_$_", '')
659 foreach qw( last first company address1 address2 city county state zip
660 country daytime night fax );
664 $self->payby =~ /^(CARD|BILL|COMP|PREPAY)$/
665 or return "Illegal payby: ". $self->payby;
668 if ( $self->payby eq 'CARD' ) {
670 my $payinfo = $self->payinfo;
672 $payinfo =~ /^(\d{13,16})$/
673 or return gettext('invalid_card'); # . ": ". $self->payinfo;
675 $self->payinfo($payinfo);
677 or return gettext('invalid_card'); # . ": ". $self->payinfo;
678 return gettext('unknown_card_type')
679 if cardtype($self->payinfo) eq "Unknown";
681 } elsif ( $self->payby eq 'BILL' ) {
683 $error = $self->ut_textn('payinfo');
684 return "Illegal P.O. number: ". $self->payinfo if $error;
686 } elsif ( $self->payby eq 'COMP' ) {
688 $error = $self->ut_textn('payinfo');
689 return "Illegal comp account issuer: ". $self->payinfo if $error;
691 } elsif ( $self->payby eq 'PREPAY' ) {
693 my $payinfo = $self->payinfo;
694 $payinfo =~ s/\W//g; #anything else would just confuse things
695 $self->payinfo($payinfo);
696 $error = $self->ut_alpha('payinfo');
697 return "Illegal prepayment identifier: ". $self->payinfo if $error;
698 return "Unknown prepayment identifier"
699 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
703 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
704 return "Expriation date required"
705 unless $self->payby eq 'BILL' || $self->payby eq 'PREPAY';
708 $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/
709 or return "Illegal expiration date: ". $self->paydate;
710 my $y = length($2) == 4 ? $2 : "20$2";
711 $self->paydate("$y-$1-01");
712 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
713 return gettext('expired_card') if $y<$nowy || ( $y==$nowy && $1<$nowm );
716 if ( $self->payname eq '' &&
717 ( ! $conf->exists('require_cardname') || $self->payby ne 'CARD' ) ) {
718 $self->payname( $self->first. " ". $self->getfield('last') );
720 $self->payname =~ /^([\w \,\.\-\']+)$/
721 or return gettext('illegal_name'). " payname: ". $self->payname;
725 $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
728 $self->otaker(getotaker);
730 #warn "AFTER: \n". $self->_dump;
737 Returns all packages (see L<FS::cust_pkg>) for this customer.
743 if ( $self->{'_pkgnum'} ) {
744 values %{ $self->{'_pkgnum'}->cache };
746 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
750 =item ncancelled_pkgs
752 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
756 sub ncancelled_pkgs {
758 if ( $self->{'_pkgnum'} ) {
759 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
761 @{ [ # force list context
762 qsearch( 'cust_pkg', {
763 'custnum' => $self->custnum,
766 qsearch( 'cust_pkg', {
767 'custnum' => $self->custnum,
776 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
782 grep { $_->susp } $self->ncancelled_pkgs;
785 =item unflagged_suspended_pkgs
787 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
788 customer (thouse packages without the `manual_flag' set).
792 sub unflagged_suspended_pkgs {
794 return $self->suspended_pkgs
795 unless dbdef->table('cust_pkg')->column('manual_flag');
796 grep { ! $_->manual_flag } $self->suspended_pkgs;
799 =item unsuspended_pkgs
801 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
806 sub unsuspended_pkgs {
808 grep { ! $_->susp } $self->ncancelled_pkgs;
813 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
814 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
815 on success or a list of errors.
821 grep { $_->unsuspend } $self->suspended_pkgs;
826 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
827 Always returns a list: an empty list on success or a list of errors.
833 grep { $_->suspend } $self->unsuspended_pkgs;
838 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
839 Always returns a list: an empty list on success or a list of errors.
845 grep { $_->cancel } $self->ncancelled_pkgs;
850 Returns the agent (see L<FS::agent>) for this customer.
856 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
861 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
862 conjunction with the collect method.
864 Options are passed as name-value pairs.
866 The only currently available option is `time', which bills the customer as if
867 it were that time. It is specified as a UNIX timestamp; see
868 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
869 functions. For example:
873 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
875 If there is an error, returns the error, otherwise returns false.
880 my( $self, %options ) = @_;
881 my $time = $options{'time'} || time;
886 local $SIG{HUP} = 'IGNORE';
887 local $SIG{INT} = 'IGNORE';
888 local $SIG{QUIT} = 'IGNORE';
889 local $SIG{TERM} = 'IGNORE';
890 local $SIG{TSTP} = 'IGNORE';
891 local $SIG{PIPE} = 'IGNORE';
893 my $oldAutoCommit = $FS::UID::AutoCommit;
894 local $FS::UID::AutoCommit = 0;
897 # find the packages which are due for billing, find out how much they are
898 # & generate invoice database.
900 my( $total_setup, $total_recur ) = ( 0, 0 );
901 #my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
902 my @cust_bill_pkg = ();
904 #my $taxable_charged = 0;##
907 foreach my $cust_pkg (
908 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
911 #NO!! next if $cust_pkg->cancel;
912 next if $cust_pkg->getfield('cancel');
914 #? to avoid use of uninitialized value errors... ?
915 $cust_pkg->setfield('bill', '')
916 unless defined($cust_pkg->bill);
918 my $part_pkg = $cust_pkg->part_pkg;
920 #so we don't modify cust_pkg record unnecessarily
921 my $cust_pkg_mod_flag = 0;
922 my %hash = $cust_pkg->hash;
923 my $old_cust_pkg = new FS::cust_pkg \%hash;
927 unless ( $cust_pkg->setup ) {
928 my $setup_prog = $part_pkg->getfield('setup');
929 $setup_prog =~ /^(.*)$/ or do {
930 $dbh->rollback if $oldAutoCommit;
931 return "Illegal setup for pkgpart ". $part_pkg->pkgpart.
937 ##$cpt->permit(); #what is necessary?
938 #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
939 #$setup = $cpt->reval($setup_prog);
940 $setup = eval $setup_prog;
941 unless ( defined($setup) ) {
942 $dbh->rollback if $oldAutoCommit;
943 return "Error eval-ing part_pkg->setup pkgpart ". $part_pkg->pkgpart.
944 "(expression $setup_prog): $@";
946 $cust_pkg->setfield('setup',$time);
947 $cust_pkg_mod_flag=1;
953 if ( $part_pkg->getfield('freq') > 0 &&
954 ! $cust_pkg->getfield('susp') &&
955 ( $cust_pkg->getfield('bill') || 0 ) < $time
957 my $recur_prog = $part_pkg->getfield('recur');
958 $recur_prog =~ /^(.*)$/ or do {
959 $dbh->rollback if $oldAutoCommit;
960 return "Illegal recur for pkgpart ". $part_pkg->pkgpart.
965 # shared with $recur_prog
966 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
969 ##$cpt->permit(); #what is necessary?
970 #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
971 #$recur = $cpt->reval($recur_prog);
972 $recur = eval $recur_prog;
973 unless ( defined($recur) ) {
974 $dbh->rollback if $oldAutoCommit;
975 return "Error eval-ing part_pkg->recur pkgpart ". $part_pkg->pkgpart.
976 "(expression $recur_prog): $@";
978 #change this bit to use Date::Manip? CAREFUL with timezones (see
979 # mailing list archive)
980 my ($sec,$min,$hour,$mday,$mon,$year) =
981 (localtime($sdate) )[0,1,2,3,4,5];
983 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
984 # only for figuring next bill date, nothing else, so, reset $sdate again
986 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
988 $mon += $part_pkg->freq;
989 until ( $mon < 12 ) { $mon -= 12; $year++; }
990 $cust_pkg->setfield('bill',
991 timelocal($sec,$min,$hour,$mday,$mon,$year));
992 $cust_pkg_mod_flag = 1;
995 warn "\$setup is undefined" unless defined($setup);
996 warn "\$recur is undefined" unless defined($recur);
997 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
999 my $taxable_charged = 0;
1000 if ( $cust_pkg_mod_flag ) {
1001 $error=$cust_pkg->replace($old_cust_pkg);
1002 if ( $error ) { #just in case
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1006 $setup = sprintf( "%.2f", $setup );
1007 $recur = sprintf( "%.2f", $recur );
1009 $dbh->rollback if $oldAutoCommit;
1010 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1013 $dbh->rollback if $oldAutoCommit;
1014 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1016 if ( $setup > 0 || $recur > 0 ) {
1017 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1018 'pkgnum' => $cust_pkg->pkgnum,
1022 'edate' => $cust_pkg->bill,
1024 push @cust_bill_pkg, $cust_bill_pkg;
1025 $total_setup += $setup;
1026 $total_recur += $recur;
1027 $taxable_charged += $setup
1028 unless $part_pkg->setuptax =~ /^Y$/i;
1029 $taxable_charged += $recur
1030 unless $part_pkg->recurtax =~ /^Y$/i;
1032 unless ( $self->tax =~ /Y/i
1033 || $self->payby eq 'COMP'
1034 || $taxable_charged == 0 ) {
1036 my $cust_main_county =
1037 qsearchs('cust_main_county',{
1038 'state' => $self->state,
1039 'county' => $self->county,
1040 'country' => $self->country,
1041 'taxclass' => $part_pkg->taxclass,
1043 or qsearchs('cust_main_county',{
1044 'state' => $self->state,
1045 'county' => $self->county,
1046 'country' => $self->country,
1050 $dbh->rollback if $oldAutoCommit;
1052 "fatal: can't find tax rate for state/county/country/taxclass ".
1053 join('/', map $self->$_(), qw(state county country taxclass) ).
1057 if ( $cust_main_county->exempt_amount ) {
1058 my ($mon,$year) = (localtime($sdate) )[4,5];
1060 my $freq = $part_pkg->freq || 1;
1061 my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1062 foreach my $which_month ( 1 .. $freq ) {
1064 'custnum' => $self->custnum,
1065 'taxnum' => $cust_main_county->taxnum,
1066 'year' => 1900+$year,
1069 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1070 until ( $mon < 13 ) { $mon -= 12; $year++; }
1071 my $cust_tax_exempt =
1072 qsearchs('cust_tax_exempt', \%hash)
1073 || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1074 my $remaining_exemption = sprintf("%.2f",
1075 $cust_main_county->exempt_amount - $cust_tax_exempt->amount );
1076 if ( $remaining_exemption > 0 ) {
1077 my $addl = $remaining_exemption > $taxable_per_month
1078 ? $taxable_per_month
1079 : $remaining_exemption;
1080 $taxable_charged -= $addl;
1081 my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1082 $cust_tax_exempt->hash,
1083 'amount' => sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1085 $error = $new_cust_tax_exempt->exemptnum
1086 ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1087 : $new_cust_tax_exempt->insert;
1089 $dbh->rollback if $oldAutoCommit;
1090 return "fatal: can't update cust_tax_exempt: $error";
1093 } # if $remaining_exemption > 0
1095 } #foreach $which_month
1097 } #if $cust_main_county->exempt_amount
1099 $taxable_charged = sprintf( "%.2f", $taxable_charged);
1100 $tax += $taxable_charged * $cust_main_county->tax / 100
1102 } #unless $self->tax =~ /Y/i
1103 # || $self->payby eq 'COMP'
1104 # || $taxable_charged == 0
1106 } #if $setup > 0 || $recur > 0
1108 } #if $cust_pkg_mod_flag
1110 } #foreach my $cust_pkg
1112 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1113 # my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1115 unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1116 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1120 # unless ( $self->tax =~ /Y/i
1121 # || $self->payby eq 'COMP'
1122 # || $taxable_charged == 0 ) {
1123 # my $cust_main_county = qsearchs('cust_main_county',{
1124 # 'state' => $self->state,
1125 # 'county' => $self->county,
1126 # 'country' => $self->country,
1127 # } ) or die "fatal: can't find tax rate for state/county/country ".
1128 # $self->state. "/". $self->county. "/". $self->country. "\n";
1129 # my $tax = sprintf( "%.2f",
1130 # $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1133 $tax = sprintf("%.2f", $tax);
1135 $charged = sprintf( "%.2f", $charged+$tax );
1137 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1144 push @cust_bill_pkg, $cust_bill_pkg;
1148 my $cust_bill = new FS::cust_bill ( {
1149 'custnum' => $self->custnum,
1151 'charged' => $charged,
1153 $error = $cust_bill->insert;
1155 $dbh->rollback if $oldAutoCommit;
1156 return "can't create invoice for customer #". $self->custnum. ": $error";
1159 my $invnum = $cust_bill->invnum;
1161 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1163 $cust_bill_pkg->invnum($invnum);
1164 $error = $cust_bill_pkg->insert;
1166 $dbh->rollback if $oldAutoCommit;
1167 return "can't create invoice line item for customer #". $self->custnum.
1172 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1176 =item collect OPTIONS
1178 (Attempt to) collect money for this customer's outstanding invoices (see
1179 L<FS::cust_bill>). Usually used after the bill method.
1181 Depending on the value of `payby', this may print an invoice (`BILL'), charge
1182 a credit card (`CARD'), or just add any necessary (pseudo-)payment (`COMP').
1184 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1185 and the invoice events web interface.
1187 If there is an error, returns the error, otherwise returns false.
1189 Options are passed as name-value pairs.
1191 Currently available options are:
1193 invoice_time - Use this time when deciding when to print invoices and
1194 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>
1195 for conversion functions.
1197 retry_card - Retry cards even when not scheduled by invoice events.
1199 batch_card - This option is deprecated. See the invoice events web interface
1200 to control whether cards are batched or run against a realtime gateway.
1202 report_badcard - This option is deprecated.
1204 force_print - This option is deprecated; see the invoice events web interface.
1209 my( $self, %options ) = @_;
1210 my $invoice_time = $options{'invoice_time'} || time;
1213 local $SIG{HUP} = 'IGNORE';
1214 local $SIG{INT} = 'IGNORE';
1215 local $SIG{QUIT} = 'IGNORE';
1216 local $SIG{TERM} = 'IGNORE';
1217 local $SIG{TSTP} = 'IGNORE';
1218 local $SIG{PIPE} = 'IGNORE';
1220 my $oldAutoCommit = $FS::UID::AutoCommit;
1221 local $FS::UID::AutoCommit = 0;
1224 my $balance = $self->balance;
1225 warn "collect customer". $self->custnum. ": balance $balance" if $Debug;
1226 unless ( $balance > 0 ) { #redundant?????
1227 $dbh->rollback if $oldAutoCommit; #hmm
1231 if ( exists($options{'retry_card'}) && $options{'retry_card'} ) {
1232 #false laziness w/replace
1233 foreach my $cust_bill_event (
1235 #$_->part_bill_event->plan eq 'realtime-card'
1236 $_->part_bill_event->eventcode eq '$cust_bill->realtime_card();'
1237 && $_->status eq 'done'
1240 $self->open_cust_bill->cust_bill_event
1242 my $error = $cust_bill_event->retry;
1244 $dbh->rollback if $oldAutoCommit;
1245 return "error scheduling invoice events for retry: $error";
1251 foreach my $cust_bill ( $self->cust_bill ) {
1253 #this has to be before next's
1254 my $amount = sprintf( "%.2f", $balance < $cust_bill->owed
1258 $balance = sprintf( "%.2f", $balance - $amount );
1260 next unless $cust_bill->owed > 0;
1262 # don't try to charge for the same invoice if it's already in a batch
1263 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1265 warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ", amount $amount, balance $balance)" if $Debug;
1267 next unless $amount > 0;
1270 foreach my $part_bill_event (
1271 sort { $a->seconds <=> $b->seconds
1272 || $a->weight <=> $b->weight
1273 || $a->eventpart <=> $b->eventpart }
1274 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1275 && ! qsearchs( 'cust_bill_event', {
1276 'invnum' => $cust_bill->invnum,
1277 'eventpart' => $_->eventpart,
1281 qsearch('part_bill_event', { 'payby' => $self->payby,
1282 'disabled' => '', } )
1285 last unless $cust_bill->owed > 0; #don't run subsequent events if owed=0
1287 warn "calling invoice event (". $part_bill_event->eventcode. ")\n"
1289 my $cust_main = $self; #for callback
1290 my $error = eval $part_bill_event->eventcode;
1293 my $statustext = '';
1297 } elsif ( $error ) {
1299 $statustext = $error;
1304 #add cust_bill_event
1305 my $cust_bill_event = new FS::cust_bill_event {
1306 'invnum' => $cust_bill->invnum,
1307 'eventpart' => $part_bill_event->eventpart,
1308 '_date' => $invoice_time,
1309 'status' => $status,
1310 'statustext' => $statustext,
1312 $error = $cust_bill_event->insert;
1314 #$dbh->rollback if $oldAutoCommit;
1315 #return "error: $error";
1317 # gah, even with transactions.
1318 $dbh->commit if $oldAutoCommit; #well.
1319 my $e = 'WARNING: Event run but database not updated - '.
1320 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
1321 ', eventpart '. $part_bill_event->eventpart.
1332 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1339 Returns the total owed for this customer on all invoices
1340 (see L<FS::cust_bill/owed>).
1346 $self->total_owed_date(2145859200); #12/31/2037
1349 =item total_owed_date TIME
1351 Returns the total owed for this customer on all invoices with date earlier than
1352 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
1353 see L<Time::Local> and L<Date::Parse> for conversion functions.
1357 sub total_owed_date {
1361 foreach my $cust_bill (
1362 grep { $_->_date <= $time }
1363 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
1365 $total_bill += $cust_bill->owed;
1367 sprintf( "%.2f", $total_bill );
1372 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
1373 to outstanding invoice balances in chronological order and returns the value
1374 of any remaining unapplied credits available for refund
1375 (see L<FS::cust_refund>).
1382 return 0 unless $self->total_credited;
1384 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
1385 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
1387 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1388 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1392 foreach my $cust_bill ( @invoices ) {
1395 if ( !defined($credit) || $credit->credited == 0) {
1396 $credit = pop @credits or last;
1399 if ($cust_bill->owed >= $credit->credited) {
1400 $amount=$credit->credited;
1402 $amount=$cust_bill->owed;
1405 my $cust_credit_bill = new FS::cust_credit_bill ( {
1406 'crednum' => $credit->crednum,
1407 'invnum' => $cust_bill->invnum,
1408 'amount' => $amount,
1410 my $error = $cust_credit_bill->insert;
1411 die $error if $error;
1413 redo if ($cust_bill->owed > 0);
1417 return $self->total_credited;
1420 =item apply_payments
1422 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
1423 to outstanding invoice balances in chronological order.
1425 #and returns the value of any remaining unapplied payments.
1429 sub apply_payments {
1434 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
1435 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
1437 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1438 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1442 foreach my $cust_bill ( @invoices ) {
1445 if ( !defined($payment) || $payment->unapplied == 0 ) {
1446 $payment = pop @payments or last;
1449 if ( $cust_bill->owed >= $payment->unapplied ) {
1450 $amount = $payment->unapplied;
1452 $amount = $cust_bill->owed;
1455 my $cust_bill_pay = new FS::cust_bill_pay ( {
1456 'paynum' => $payment->paynum,
1457 'invnum' => $cust_bill->invnum,
1458 'amount' => $amount,
1460 my $error = $cust_bill_pay->insert;
1461 die $error if $error;
1463 redo if ( $cust_bill->owed > 0);
1467 return $self->total_unapplied_payments;
1470 =item total_credited
1472 Returns the total outstanding credit (see L<FS::cust_credit>) for this
1473 customer. See L<FS::cust_credit/credited>.
1477 sub total_credited {
1479 my $total_credit = 0;
1480 foreach my $cust_credit ( qsearch('cust_credit', {
1481 'custnum' => $self->custnum,
1483 $total_credit += $cust_credit->credited;
1485 sprintf( "%.2f", $total_credit );
1488 =item total_unapplied_payments
1490 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
1491 See L<FS::cust_pay/unapplied>.
1495 sub total_unapplied_payments {
1497 my $total_unapplied = 0;
1498 foreach my $cust_pay ( qsearch('cust_pay', {
1499 'custnum' => $self->custnum,
1501 $total_unapplied += $cust_pay->unapplied;
1503 sprintf( "%.2f", $total_unapplied );
1508 Returns the balance for this customer (total_owed minus total_credited
1509 minus total_unapplied_payments).
1516 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
1520 =item balance_date TIME
1522 Returns the balance for this customer, only considering invoices with date
1523 earlier than TIME (total_owed_date minus total_credited minus
1524 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
1525 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
1534 $self->total_owed_date($time)
1535 - $self->total_credited
1536 - $self->total_unapplied_payments
1540 =item invoicing_list [ ARRAYREF ]
1542 If an arguement is given, sets these email addresses as invoice recipients
1543 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
1544 (except as warnings), so use check_invoicing_list first.
1546 Returns a list of email addresses (with svcnum entries expanded).
1548 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
1549 check it without disturbing anything by passing nothing.
1551 This interface may change in the future.
1555 sub invoicing_list {
1556 my( $self, $arrayref ) = @_;
1558 my @cust_main_invoice;
1559 if ( $self->custnum ) {
1560 @cust_main_invoice =
1561 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1563 @cust_main_invoice = ();
1565 foreach my $cust_main_invoice ( @cust_main_invoice ) {
1566 #warn $cust_main_invoice->destnum;
1567 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
1568 #warn $cust_main_invoice->destnum;
1569 my $error = $cust_main_invoice->delete;
1570 warn $error if $error;
1573 if ( $self->custnum ) {
1574 @cust_main_invoice =
1575 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1577 @cust_main_invoice = ();
1579 my %seen = map { $_->address => 1 } @cust_main_invoice;
1580 foreach my $address ( @{$arrayref} ) {
1581 #unless ( grep { $address eq $_->address } @cust_main_invoice ) {
1582 next if exists $seen{$address} && $seen{$address};
1583 $seen{$address} = 1;
1584 my $cust_main_invoice = new FS::cust_main_invoice ( {
1585 'custnum' => $self->custnum,
1588 my $error = $cust_main_invoice->insert;
1589 warn $error if $error;
1592 if ( $self->custnum ) {
1594 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1600 =item check_invoicing_list ARRAYREF
1602 Checks these arguements as valid input for the invoicing_list method. If there
1603 is an error, returns the error, otherwise returns false.
1607 sub check_invoicing_list {
1608 my( $self, $arrayref ) = @_;
1609 foreach my $address ( @{$arrayref} ) {
1610 my $cust_main_invoice = new FS::cust_main_invoice ( {
1611 'custnum' => $self->custnum,
1614 my $error = $self->custnum
1615 ? $cust_main_invoice->check
1616 : $cust_main_invoice->checkdest
1618 return $error if $error;
1623 =item default_invoicing_list
1625 Sets the invoicing list to all accounts associated with this customer.
1629 sub default_invoicing_list {
1632 foreach my $cust_pkg ( $self->all_pkgs ) {
1633 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
1635 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1636 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1638 push @list, map { $_->email } @svc_acct;
1640 $self->invoicing_list(\@list);
1643 =item invoicing_list_addpost
1645 Adds postal invoicing to this customer. If this customer is already configured
1646 to receive postal invoices, does nothing.
1650 sub invoicing_list_addpost {
1652 return if grep { $_ eq 'POST' } $self->invoicing_list;
1653 my @invoicing_list = $self->invoicing_list;
1654 push @invoicing_list, 'POST';
1655 $self->invoicing_list(\@invoicing_list);
1658 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
1660 Returns an array of customers referred by this customer (referral_custnum set
1661 to this custnum). If DEPTH is given, recurses up to the given depth, returning
1662 customers referred by customers referred by this customer and so on, inclusive.
1663 The default behavior is DEPTH 1 (no recursion).
1667 sub referral_cust_main {
1669 my $depth = @_ ? shift : 1;
1670 my $exclude = @_ ? shift : {};
1673 map { $exclude->{$_->custnum}++; $_; }
1674 grep { ! $exclude->{ $_->custnum } }
1675 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
1679 map { $_->referral_cust_main($depth-1, $exclude) }
1686 =item referral_cust_main_ncancelled
1688 Same as referral_cust_main, except only returns customers with uncancelled
1693 sub referral_cust_main_ncancelled {
1695 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
1698 =item referral_cust_pkg [ DEPTH ]
1700 Like referral_cust_main, except returns a flat list of all unsuspended (and
1701 uncancelled) packages for each customer. The number of items in this list may
1702 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
1706 sub referral_cust_pkg {
1708 my $depth = @_ ? shift : 1;
1710 map { $_->unsuspended_pkgs }
1711 grep { $_->unsuspended_pkgs }
1712 $self->referral_cust_main($depth);
1715 =item credit AMOUNT, REASON
1717 Applies a credit to this customer. If there is an error, returns the error,
1718 otherwise returns false.
1723 my( $self, $amount, $reason ) = @_;
1724 my $cust_credit = new FS::cust_credit {
1725 'custnum' => $self->custnum,
1726 'amount' => $amount,
1727 'reason' => $reason,
1729 $cust_credit->insert;
1732 =item charge AMOUNT PKG COMMENT
1734 Creates a one-time charge for this customer. If there is an error, returns
1735 the error, otherwise returns false.
1740 my ( $self, $amount, $pkg, $comment ) = @_;
1742 my $part_pkg = new FS::part_pkg ( {
1743 'pkg' => $pkg || 'One-time charge',
1744 'comment' => $comment || '$'. sprintf("%.2f".$amount),
1757 Returns all the invoices (see L<FS::cust_bill>) for this customer.
1763 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
1766 =item open_cust_bill
1768 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
1773 sub open_cust_bill {
1775 grep { $_->owed > 0 } $self->cust_bill;
1784 =item check_and_rebuild_fuzzyfiles
1788 sub check_and_rebuild_fuzzyfiles {
1789 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1790 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
1791 or &rebuild_fuzzyfiles;
1794 =item rebuild_fuzzyfiles
1798 sub rebuild_fuzzyfiles {
1800 use Fcntl qw(:flock);
1802 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1806 open(LASTLOCK,">>$dir/cust_main.last")
1807 or die "can't open $dir/cust_main.last: $!";
1808 flock(LASTLOCK,LOCK_EX)
1809 or die "can't lock $dir/cust_main.last: $!";
1811 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
1813 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
1814 if defined dbdef->table('cust_main')->column('ship_last');
1816 open (LASTCACHE,">$dir/cust_main.last.tmp")
1817 or die "can't open $dir/cust_main.last.tmp: $!";
1818 print LASTCACHE join("\n", @all_last), "\n";
1819 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
1821 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
1826 open(COMPANYLOCK,">>$dir/cust_main.company")
1827 or die "can't open $dir/cust_main.company: $!";
1828 flock(COMPANYLOCK,LOCK_EX)
1829 or die "can't lock $dir/cust_main.company: $!";
1831 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
1833 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
1834 if defined dbdef->table('cust_main')->column('ship_last');
1836 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
1837 or die "can't open $dir/cust_main.company.tmp: $!";
1838 print COMPANYCACHE join("\n", @all_company), "\n";
1839 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
1841 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
1851 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1852 open(LASTCACHE,"<$dir/cust_main.last")
1853 or die "can't open $dir/cust_main.last: $!";
1854 my @array = map { chomp; $_; } <LASTCACHE>;
1864 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1865 open(COMPANYCACHE,"<$dir/cust_main.company")
1866 or die "can't open $dir/cust_main.last: $!";
1867 my @array = map { chomp; $_; } <COMPANYCACHE>;
1872 =item append_fuzzyfiles LASTNAME COMPANY
1876 sub append_fuzzyfiles {
1877 my( $last, $company ) = @_;
1879 &check_and_rebuild_fuzzyfiles;
1881 use Fcntl qw(:flock);
1883 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1887 open(LAST,">>$dir/cust_main.last")
1888 or die "can't open $dir/cust_main.last: $!";
1890 or die "can't lock $dir/cust_main.last: $!";
1892 print LAST "$last\n";
1895 or die "can't unlock $dir/cust_main.last: $!";
1901 open(COMPANY,">>$dir/cust_main.company")
1902 or die "can't open $dir/cust_main.company: $!";
1903 flock(COMPANY,LOCK_EX)
1904 or die "can't lock $dir/cust_main.company: $!";
1906 print COMPANY "$company\n";
1908 flock(COMPANY,LOCK_UN)
1909 or die "can't unlock $dir/cust_main.company: $!";
1923 The delete method should possibly take an FS::cust_main object reference
1924 instead of a scalar customer number.
1926 Bill and collect options should probably be passed as references instead of a
1929 There should probably be a configuration file with a list of allowed credit
1932 No multiple currency support (probably a larger project than just this module).
1936 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
1937 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
1938 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.