2 use base qw( FS::cust_main::Packages
4 FS::cust_main::NationalID
6 FS::cust_main::Billing_Realtime
7 FS::cust_main::Billing_Batch
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
14 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
15 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
23 use Scalar::Util qw( blessed );
24 use Time::Local qw(timelocal);
29 use File::Temp; #qw( tempfile );
30 use Business::CreditCard 0.28;
31 use List::Util qw(min);
32 use FS::UID qw( dbh driver_name );
33 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
35 use FS::Misc qw( generate_ps do_print money_pretty card_types );
36 use FS::Msgcat qw(gettext);
43 use FS::cust_bill_void;
44 use FS::legacy_cust_bill;
46 use FS::cust_pay_pending;
47 use FS::cust_pay_void;
48 use FS::cust_pay_batch;
51 use FS::part_referral;
52 use FS::cust_main_county;
53 use FS::cust_location;
56 use FS::cust_main_exemption;
57 use FS::cust_tax_adjustment;
58 use FS::cust_tax_location;
59 use FS::agent_currency;
60 use FS::cust_main_invoice;
62 use FS::prepay_credit;
68 use FS::payment_gateway;
69 use FS::agent_payment_gateway;
71 use FS::cust_main_note;
72 use FS::cust_attachment;
75 use FS::upgrade_journal;
81 # 1 is mostly method/subroutine entry and options
82 # 2 traces progress of some operations
83 # 3 is even more information including possibly sensitive data
85 our $me = '[FS::cust_main]';
88 our $ignore_expired_card = 0;
89 our $ignore_banned_card = 0;
90 our $ignore_invalid_card = 0;
92 our $skip_fuzzyfiles = 0;
94 our $ucfirst_nowarn = 0;
96 #this info is in cust_payby as of 4.x
97 #this and the fields themselves can be removed in 5.x
98 our @encrypted_fields = ('payinfo', 'paycvv');
99 sub nohistory_fields { ('payinfo', 'paycvv'); }
102 our $default_agent_custid;
103 our $custnum_display_length;
104 #ask FS::UID to run this stuff for us later
105 #$FS::UID::callback{'FS::cust_main'} = sub {
106 install_callback FS::UID sub {
107 $conf = new FS::Conf;
108 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
109 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
110 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
115 my ( $hashref, $cache ) = @_;
116 if ( exists $hashref->{'pkgnum'} ) {
117 #@{ $self->{'_pkgnum'} } = ();
118 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
119 $self->{'_pkgnum'} = $subcache;
120 #push @{ $self->{'_pkgnum'} },
121 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
127 FS::cust_main - Object methods for cust_main records
133 $record = new FS::cust_main \%hash;
134 $record = new FS::cust_main { 'column' => 'value' };
136 $error = $record->insert;
138 $error = $new_record->replace($old_record);
140 $error = $record->delete;
142 $error = $record->check;
144 @cust_pkg = $record->all_pkgs;
146 @cust_pkg = $record->ncancelled_pkgs;
148 @cust_pkg = $record->suspended_pkgs;
150 $error = $record->bill;
151 $error = $record->bill %options;
152 $error = $record->bill 'time' => $time;
154 $error = $record->collect;
155 $error = $record->collect %options;
156 $error = $record->collect 'invoice_time' => $time,
161 An FS::cust_main object represents a customer. FS::cust_main inherits from
162 FS::Record. The following fields are currently supported:
168 Primary key (assigned automatically for new customers)
172 Agent (see L<FS::agent>)
176 Advertising source (see L<FS::part_referral>)
188 Cocial security number (optional)
212 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
216 Payment Information (See L<FS::payinfo_Mixin> for data format)
220 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
224 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
228 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
232 Start date month (maestro/solo cards only)
236 Start date year (maestro/solo cards only)
240 Issue number (maestro/solo cards only)
244 Name on card or billing name
248 IP address from which payment information was received
252 Tax exempt, empty or `Y'
256 Order taker (see L<FS::access_user>)
262 =item referral_custnum
264 Referring customer number
268 Enable individual CDR spooling, empty or `Y'
272 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
276 Discourage individual CDR printing, empty or `Y'
280 Allow self-service editing of ticket subjects, empty or 'Y'
282 =item calling_list_exempt
284 Do not call, empty or 'Y'
286 =item invoice_ship_address
288 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
298 Creates a new customer. To add the customer to the database, see L<"insert">.
300 Note that this stores the hash reference, not a distinct copy of the hash it
301 points to. You can ask the object for a copy with the I<hash> method.
305 sub table { 'cust_main'; }
307 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
309 Adds this customer to the database. If there is an error, returns the error,
310 otherwise returns false.
312 Usually the customer's location will not yet exist in the database, and
313 the C<bill_location> and C<ship_location> pseudo-fields must be set to
314 uninserted L<FS::cust_location> objects. These will be inserted and linked
315 (in both directions) to the new customer record. If they're references
316 to the same object, they will become the same location.
318 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
319 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
320 are inserted atomicly, or the transaction is rolled back. Passing an empty
321 hash reference is equivalent to not supplying this parameter. There should be
322 a better explanation of this, but until then, here's an example:
325 tie %hash, 'Tie::RefHash'; #this part is important
327 $cust_pkg => [ $svc_acct ],
330 $cust_main->insert( \%hash );
332 INVOICING_LIST_ARYREF: No longer supported.
334 Currently available options are: I<depend_jobnum>, I<noexport>,
335 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
337 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
338 on the supplied jobnum (they will not run until the specific job completes).
339 This can be used to defer provisioning until some action completes (such
340 as running the customer's credit card successfully).
342 The I<noexport> option is deprecated. If I<noexport> is set true, no
343 provisioning jobs (exports) are scheduled. (You can schedule them later with
344 the B<reexport> method.)
346 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
347 of tax names and exemption numbers. FS::cust_main_exemption records will be
348 created and inserted.
350 If I<prospectnum> is set, moves contacts and locations from that prospect.
352 If I<contact> is set to an arrayref of FS::contact objects, those will be
355 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
356 unset), inserts those new contacts with this new customer. Handles CGI
357 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
359 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
360 new stored payment records with this new customer. Handles CGI parameters
361 for an "m2" multiple entry field as passed by edit/cust_main.cgi
367 my $cust_pkgs = @_ ? shift : {};
369 if ( $_[0] and ref($_[0]) eq 'ARRAY' ) {
370 warn "cust_main::insert using deprecated invoicing list argument";
371 $invoicing_list = shift;
374 warn "$me insert called with options ".
375 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
378 local $SIG{HUP} = 'IGNORE';
379 local $SIG{INT} = 'IGNORE';
380 local $SIG{QUIT} = 'IGNORE';
381 local $SIG{TERM} = 'IGNORE';
382 local $SIG{TSTP} = 'IGNORE';
383 local $SIG{PIPE} = 'IGNORE';
385 my $oldAutoCommit = $FS::UID::AutoCommit;
386 local $FS::UID::AutoCommit = 0;
389 my $prepay_identifier = '';
390 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
392 if ( $self->payby eq 'PREPAY' ) {
394 $self->payby(''); #'BILL');
395 $prepay_identifier = $self->payinfo;
398 warn " looking up prepaid card $prepay_identifier\n"
401 my $error = $self->get_prepay( $prepay_identifier,
402 'amount_ref' => \$amount,
403 'seconds_ref' => \$seconds,
404 'upbytes_ref' => \$upbytes,
405 'downbytes_ref' => \$downbytes,
406 'totalbytes_ref' => \$totalbytes,
409 $dbh->rollback if $oldAutoCommit;
410 #return "error applying prepaid card (transaction rolled back): $error";
414 $payby = 'PREP' if $amount;
416 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
419 $self->payby(''); #'BILL');
420 $amount = $self->paid;
425 foreach my $l (qw(bill_location ship_location)) {
427 my $loc = delete $self->hashref->{$l} or next;
429 if ( !$loc->locationnum ) {
430 # warn the location that we're going to insert it with no custnum
431 $loc->set(custnum_pending => 1);
432 warn " inserting $l\n"
434 my $error = $loc->insert;
436 $dbh->rollback if $oldAutoCommit;
437 my $label = $l eq 'ship_location' ? 'service' : 'billing';
438 return "$error (in $label location)";
441 } elsif ( $loc->prospectnum ) {
443 $loc->prospectnum('');
444 $loc->set(custnum_pending => 1);
445 my $error = $loc->replace;
447 $dbh->rollback if $oldAutoCommit;
448 my $label = $l eq 'ship_location' ? 'service' : 'billing';
449 return "$error (moving $label location)";
452 } elsif ( ($loc->custnum || 0) > 0 ) {
453 # then it somehow belongs to another customer--shouldn't happen
454 $dbh->rollback if $oldAutoCommit;
455 return "$l belongs to customer ".$loc->custnum;
457 # else it already belongs to this customer
458 # (happens when ship_location is identical to bill_location)
460 $self->set($l.'num', $loc->locationnum);
462 if ( $self->get($l.'num') eq '' ) {
463 $dbh->rollback if $oldAutoCommit;
468 warn " inserting $self\n"
471 $self->signupdate(time) unless $self->signupdate;
473 $self->auto_agent_custid()
474 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
476 my $error = $self->check_payinfo_cardtype
477 || $self->SUPER::insert;
479 $dbh->rollback if $oldAutoCommit;
480 #return "inserting cust_main record (transaction rolled back): $error";
484 # now set cust_location.custnum
485 foreach my $l (qw(bill_location ship_location)) {
486 warn " setting $l.custnum\n"
488 my $loc = $self->$l or next;
489 unless ( $loc->custnum ) {
490 $loc->set(custnum => $self->custnum);
491 $error ||= $loc->replace;
495 $dbh->rollback if $oldAutoCommit;
496 return "error setting $l custnum: $error";
500 warn " setting customer tags\n"
503 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
504 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
505 'custnum' => $self->custnum };
506 my $error = $cust_tag->insert;
508 $dbh->rollback if $oldAutoCommit;
513 my $prospectnum = delete $options{'prospectnum'};
514 if ( $prospectnum ) {
516 warn " moving contacts and locations from prospect $prospectnum\n"
520 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
521 unless ( $prospect_main ) {
522 $dbh->rollback if $oldAutoCommit;
523 return "Unknown prospectnum $prospectnum";
525 $prospect_main->custnum($self->custnum);
526 $prospect_main->disabled('Y');
527 my $error = $prospect_main->replace;
529 $dbh->rollback if $oldAutoCommit;
533 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
534 my $cust_contact = new FS::cust_contact {
535 'custnum' => $self->custnum,
536 'invoice_dest' => 'Y', # invoice_dest currently not set for prospect contacts
537 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
539 my $error = $cust_contact->insert
540 || $prospect_contact->delete;
542 $dbh->rollback if $oldAutoCommit;
547 my @cust_location = $prospect_main->cust_location;
548 my @qual = $prospect_main->qual;
550 foreach my $r ( @cust_location, @qual ) {
552 $r->custnum($self->custnum);
553 my $error = $r->replace;
555 $dbh->rollback if $oldAutoCommit;
559 # since we set invoice_dest on all migrated prospect contacts (for now),
560 # don't process invoicing_list.
561 delete $options{'invoicing_list'};
562 $invoicing_list = undef;
565 warn " setting contacts\n"
568 $invoicing_list ||= $options{'invoicing_list'};
569 if ( $invoicing_list ) {
571 $invoicing_list = [ $invoicing_list ] if !ref($invoicing_list);
574 foreach my $dest (@$invoicing_list ) {
575 if ($dest eq 'POST') {
576 $self->set('postal_invoice', 'Y');
579 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
580 if ( $contact_email ) {
581 my $cust_contact = FS::cust_contact->new({
582 contactnum => $contact_email->contactnum,
583 custnum => $self->custnum,
585 $cust_contact->set('invoice_dest', 'Y');
586 my $error = $cust_contact->insert;
588 $dbh->rollback if $oldAutoCommit;
589 return "$error (linking to email address $dest)";
593 # this email address is not yet linked to any contact
594 $email .= ',' if length($email);
602 my $contact = FS::contact->new({
603 'custnum' => $self->get('custnum'),
604 'last' => $self->get('last'),
605 'first' => $self->get('first'),
606 'emailaddress' => $email,
607 'invoice_dest' => 'Y', # yes, you can set this via the contact
609 my $error = $contact->insert;
611 $dbh->rollback if $oldAutoCommit;
619 if ( my $contact = delete $options{'contact'} ) {
621 foreach my $c ( @$contact ) {
622 $c->custnum($self->custnum);
623 my $error = $c->insert;
625 $dbh->rollback if $oldAutoCommit;
631 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
633 my $error = $self->process_o2m( 'table' => 'contact',
634 'fields' => FS::contact->cgi_contact_fields,
635 'params' => $contact_params,
638 $dbh->rollback if $oldAutoCommit;
643 warn " setting cust_payby\n"
646 if ( $options{cust_payby} ) {
648 foreach my $cust_payby ( @{ $options{cust_payby} } ) {
649 $cust_payby->custnum($self->custnum);
650 my $error = $cust_payby->insert;
652 $dbh->rollback if $oldAutoCommit;
657 } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
659 my $error = $self->process_o2m(
660 'table' => 'cust_payby',
661 'fields' => FS::cust_payby->cgi_cust_payby_fields,
662 'params' => $cust_payby_params,
663 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
666 $dbh->rollback if $oldAutoCommit;
672 warn " setting cust_main_exemption\n"
675 my $tax_exemption = delete $options{'tax_exemption'};
676 if ( $tax_exemption ) {
678 $tax_exemption = { map { $_ => '' } @$tax_exemption }
679 if ref($tax_exemption) eq 'ARRAY';
681 foreach my $taxname ( keys %$tax_exemption ) {
682 my $cust_main_exemption = new FS::cust_main_exemption {
683 'custnum' => $self->custnum,
684 'taxname' => $taxname,
685 'exempt_number' => $tax_exemption->{$taxname},
687 my $error = $cust_main_exemption->insert;
689 $dbh->rollback if $oldAutoCommit;
690 return "inserting cust_main_exemption (transaction rolled back): $error";
695 warn " ordering packages\n"
698 $error = $self->order_pkgs( $cust_pkgs,
700 'seconds_ref' => \$seconds,
701 'upbytes_ref' => \$upbytes,
702 'downbytes_ref' => \$downbytes,
703 'totalbytes_ref' => \$totalbytes,
706 $dbh->rollback if $oldAutoCommit;
711 $dbh->rollback if $oldAutoCommit;
712 return "No svc_acct record to apply pre-paid time";
714 if ( $upbytes || $downbytes || $totalbytes ) {
715 $dbh->rollback if $oldAutoCommit;
716 return "No svc_acct record to apply pre-paid data";
720 warn " inserting initial $payby payment of $amount\n"
722 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
724 $dbh->rollback if $oldAutoCommit;
725 return "inserting payment (transaction rolled back): $error";
729 unless ( $import || $skip_fuzzyfiles ) {
730 warn " queueing fuzzyfiles update\n"
732 $error = $self->queue_fuzzyfiles_update;
734 $dbh->rollback if $oldAutoCommit;
735 return "updating fuzzy search cache: $error";
739 # FS::geocode_Mixin::after_insert or something?
740 if ( $conf->config('tax_district_method') and !$import ) {
741 # if anything non-empty, try to look it up
742 my $queue = new FS::queue {
743 'job' => 'FS::geocode_Mixin::process_district_update',
744 'custnum' => $self->custnum,
746 my $error = $queue->insert( ref($self), $self->custnum );
748 $dbh->rollback if $oldAutoCommit;
749 return "queueing tax district update: $error";
754 warn " exporting\n" if $DEBUG > 1;
756 my $export_args = $options{'export_args'} || [];
759 map qsearch( 'part_export', {exportnum=>$_} ),
760 $conf->config('cust_main-exports'); #, $agentnum
762 foreach my $part_export ( @part_export ) {
763 my $error = $part_export->export_insert($self, @$export_args);
765 $dbh->rollback if $oldAutoCommit;
766 return "exporting to ". $part_export->exporttype.
767 " (transaction rolled back): $error";
771 #foreach my $depend_jobnum ( @$depend_jobnums ) {
772 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
774 # foreach my $jobnum ( @jobnums ) {
775 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
776 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
778 # my $error = $queue->depend_insert($depend_jobnum);
780 # $dbh->rollback if $oldAutoCommit;
781 # return "error queuing job dependancy: $error";
788 #if ( exists $options{'jobnums'} ) {
789 # push @{ $options{'jobnums'} }, @jobnums;
792 warn " insert complete; committing transaction\n"
795 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
800 use File::CounterFile;
801 sub auto_agent_custid {
804 my $format = $conf->config('cust_main-auto_agent_custid');
806 if ( $format eq '1YMMXXXXXXXX' ) {
808 my $counter = new File::CounterFile 'cust_main.agent_custid';
811 my $ym = 100000000000 + time2str('%y%m00000000', time);
812 if ( $ym > $counter->value ) {
813 $counter->{'value'} = $agent_custid = $ym;
814 $counter->{'updated'} = 1;
816 $agent_custid = $counter->inc;
822 die "Unknown cust_main-auto_agent_custid format: $format";
825 $self->agent_custid($agent_custid);
829 =item PACKAGE METHODS
831 Documentation on customer package methods has been moved to
832 L<FS::cust_main::Packages>.
834 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
836 Recharges this (existing) customer with the specified prepaid card (see
837 L<FS::prepay_credit>), specified either by I<identifier> or as an
838 FS::prepay_credit object. If there is an error, returns the error, otherwise
841 Optionally, five scalar references can be passed as well. They will have their
842 values filled in with the amount, number of seconds, and number of upload,
843 download, and total bytes applied by this prepaid card.
847 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
848 #the only place that uses these args
849 sub recharge_prepay {
850 my( $self, $prepay_credit, $amountref, $secondsref,
851 $upbytesref, $downbytesref, $totalbytesref ) = @_;
853 local $SIG{HUP} = 'IGNORE';
854 local $SIG{INT} = 'IGNORE';
855 local $SIG{QUIT} = 'IGNORE';
856 local $SIG{TERM} = 'IGNORE';
857 local $SIG{TSTP} = 'IGNORE';
858 local $SIG{PIPE} = 'IGNORE';
860 my $oldAutoCommit = $FS::UID::AutoCommit;
861 local $FS::UID::AutoCommit = 0;
864 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
866 my $error = $self->get_prepay( $prepay_credit,
867 'amount_ref' => \$amount,
868 'seconds_ref' => \$seconds,
869 'upbytes_ref' => \$upbytes,
870 'downbytes_ref' => \$downbytes,
871 'totalbytes_ref' => \$totalbytes,
873 || $self->increment_seconds($seconds)
874 || $self->increment_upbytes($upbytes)
875 || $self->increment_downbytes($downbytes)
876 || $self->increment_totalbytes($totalbytes)
877 || $self->insert_cust_pay_prepay( $amount,
879 ? $prepay_credit->identifier
884 $dbh->rollback if $oldAutoCommit;
888 if ( defined($amountref) ) { $$amountref = $amount; }
889 if ( defined($secondsref) ) { $$secondsref = $seconds; }
890 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
891 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
892 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
894 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
899 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
901 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
902 specified either by I<identifier> or as an FS::prepay_credit object.
904 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>. The scalars (provided by references) will be
905 incremented by the values of the prepaid card.
907 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
908 check or set this customer's I<agentnum>.
910 If there is an error, returns the error, otherwise returns false.
916 my( $self, $prepay_credit, %opt ) = @_;
918 local $SIG{HUP} = 'IGNORE';
919 local $SIG{INT} = 'IGNORE';
920 local $SIG{QUIT} = 'IGNORE';
921 local $SIG{TERM} = 'IGNORE';
922 local $SIG{TSTP} = 'IGNORE';
923 local $SIG{PIPE} = 'IGNORE';
925 my $oldAutoCommit = $FS::UID::AutoCommit;
926 local $FS::UID::AutoCommit = 0;
929 unless ( ref($prepay_credit) ) {
931 my $identifier = $prepay_credit;
933 $prepay_credit = qsearchs(
935 { 'identifier' => $identifier },
940 unless ( $prepay_credit ) {
941 $dbh->rollback if $oldAutoCommit;
942 return "Invalid prepaid card: ". $identifier;
947 if ( $prepay_credit->agentnum ) {
948 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
949 $dbh->rollback if $oldAutoCommit;
950 return "prepaid card not valid for agent ". $self->agentnum;
952 $self->agentnum($prepay_credit->agentnum);
955 my $error = $prepay_credit->delete;
957 $dbh->rollback if $oldAutoCommit;
958 return "removing prepay_credit (transaction rolled back): $error";
961 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
962 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
964 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
969 =item increment_upbytes SECONDS
971 Updates this customer's single or primary account (see L<FS::svc_acct>) by
972 the specified number of upbytes. If there is an error, returns the error,
973 otherwise returns false.
977 sub increment_upbytes {
978 _increment_column( shift, 'upbytes', @_);
981 =item increment_downbytes SECONDS
983 Updates this customer's single or primary account (see L<FS::svc_acct>) by
984 the specified number of downbytes. If there is an error, returns the error,
985 otherwise returns false.
989 sub increment_downbytes {
990 _increment_column( shift, 'downbytes', @_);
993 =item increment_totalbytes SECONDS
995 Updates this customer's single or primary account (see L<FS::svc_acct>) by
996 the specified number of totalbytes. If there is an error, returns the error,
997 otherwise returns false.
1001 sub increment_totalbytes {
1002 _increment_column( shift, 'totalbytes', @_);
1005 =item increment_seconds SECONDS
1007 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1008 the specified number of seconds. If there is an error, returns the error,
1009 otherwise returns false.
1013 sub increment_seconds {
1014 _increment_column( shift, 'seconds', @_);
1017 =item _increment_column AMOUNT
1019 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1020 the specified number of seconds or bytes. If there is an error, returns
1021 the error, otherwise returns false.
1025 sub _increment_column {
1026 my( $self, $column, $amount ) = @_;
1027 warn "$me increment_column called: $column, $amount\n"
1030 return '' unless $amount;
1032 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1033 $self->ncancelled_pkgs;
1035 if ( ! @cust_pkg ) {
1036 return 'No packages with primary or single services found'.
1037 ' to apply pre-paid time';
1038 } elsif ( scalar(@cust_pkg) > 1 ) {
1039 #maybe have a way to specify the package/account?
1040 return 'Multiple packages found to apply pre-paid time';
1043 my $cust_pkg = $cust_pkg[0];
1044 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1048 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1050 if ( ! @cust_svc ) {
1051 return 'No account found to apply pre-paid time';
1052 } elsif ( scalar(@cust_svc) > 1 ) {
1053 return 'Multiple accounts found to apply pre-paid time';
1056 my $svc_acct = $cust_svc[0]->svc_x;
1057 warn " found service svcnum ". $svc_acct->pkgnum.
1058 ' ('. $svc_acct->email. ")\n"
1061 $column = "increment_$column";
1062 $svc_acct->$column($amount);
1066 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1068 Inserts a prepayment in the specified amount for this customer. An optional
1069 second argument can specify the prepayment identifier for tracking purposes.
1070 If there is an error, returns the error, otherwise returns false.
1074 sub insert_cust_pay_prepay {
1075 shift->insert_cust_pay('PREP', @_);
1078 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1080 Inserts a cash payment in the specified amount for this customer. An optional
1081 second argument can specify the payment identifier for tracking purposes.
1082 If there is an error, returns the error, otherwise returns false.
1086 sub insert_cust_pay_cash {
1087 shift->insert_cust_pay('CASH', @_);
1090 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1092 Inserts a Western Union payment in the specified amount for this customer. An
1093 optional second argument can specify the prepayment identifier for tracking
1094 purposes. If there is an error, returns the error, otherwise returns false.
1098 sub insert_cust_pay_west {
1099 shift->insert_cust_pay('WEST', @_);
1102 sub insert_cust_pay {
1103 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1104 my $payinfo = scalar(@_) ? shift : '';
1106 my $cust_pay = new FS::cust_pay {
1107 'custnum' => $self->custnum,
1108 'paid' => sprintf('%.2f', $amount),
1109 #'_date' => #date the prepaid card was purchased???
1111 'payinfo' => $payinfo,
1117 =item delete [ OPTION => VALUE ... ]
1119 This deletes the customer. If there is an error, returns the error, otherwise
1122 This will completely remove all traces of the customer record. This is not
1123 what you want when a customer cancels service; for that, cancel all of the
1124 customer's packages (see L</cancel>).
1126 If the customer has any uncancelled packages, you need to pass a new (valid)
1127 customer number for those packages to be transferred to, as the "new_customer"
1128 option. Cancelled packages will be deleted. Did I mention that this is NOT
1129 what you want when a customer cancels service and that you really should be
1130 looking at L<FS::cust_pkg/cancel>?
1132 You can't delete a customer with invoices (see L<FS::cust_bill>),
1133 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1134 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1135 set the "delete_financials" option to a true value.
1140 my( $self, %opt ) = @_;
1142 local $SIG{HUP} = 'IGNORE';
1143 local $SIG{INT} = 'IGNORE';
1144 local $SIG{QUIT} = 'IGNORE';
1145 local $SIG{TERM} = 'IGNORE';
1146 local $SIG{TSTP} = 'IGNORE';
1147 local $SIG{PIPE} = 'IGNORE';
1149 my $oldAutoCommit = $FS::UID::AutoCommit;
1150 local $FS::UID::AutoCommit = 0;
1153 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1154 $dbh->rollback if $oldAutoCommit;
1155 return "Can't delete a master agent customer";
1158 #use FS::access_user
1159 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1160 $dbh->rollback if $oldAutoCommit;
1161 return "Can't delete a master employee customer";
1164 tie my %financial_tables, 'Tie::IxHash',
1165 'cust_bill' => 'invoices',
1166 'cust_statement' => 'statements',
1167 'cust_credit' => 'credits',
1168 'cust_pay' => 'payments',
1169 'cust_refund' => 'refunds',
1172 foreach my $table ( keys %financial_tables ) {
1174 my @records = $self->$table();
1176 if ( @records && ! $opt{'delete_financials'} ) {
1177 $dbh->rollback if $oldAutoCommit;
1178 return "Can't delete a customer with ". $financial_tables{$table};
1181 foreach my $record ( @records ) {
1182 my $error = $record->delete;
1184 $dbh->rollback if $oldAutoCommit;
1185 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1191 my @cust_pkg = $self->ncancelled_pkgs;
1193 my $new_custnum = $opt{'new_custnum'};
1194 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1195 $dbh->rollback if $oldAutoCommit;
1196 return "Invalid new customer number: $new_custnum";
1198 foreach my $cust_pkg ( @cust_pkg ) {
1199 my %hash = $cust_pkg->hash;
1200 $hash{'custnum'} = $new_custnum;
1201 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1202 my $error = $new_cust_pkg->replace($cust_pkg,
1203 options => { $cust_pkg->options },
1206 $dbh->rollback if $oldAutoCommit;
1211 my @cancelled_cust_pkg = $self->all_pkgs;
1212 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1213 my $error = $cust_pkg->delete;
1215 $dbh->rollback if $oldAutoCommit;
1220 #cust_tax_adjustment in financials?
1221 #cust_pay_pending? ouch
1222 foreach my $table (qw(
1223 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1224 cust_payby cust_location cust_main_note cust_tax_adjustment
1225 cust_pay_void cust_pay_batch queue cust_tax_exempt
1227 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1228 my $error = $record->delete;
1230 $dbh->rollback if $oldAutoCommit;
1236 my $sth = $dbh->prepare(
1237 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1239 my $errstr = $dbh->errstr;
1240 $dbh->rollback if $oldAutoCommit;
1243 $sth->execute($self->custnum) or do {
1244 my $errstr = $sth->errstr;
1245 $dbh->rollback if $oldAutoCommit;
1251 my $ticket_dbh = '';
1252 if ($conf->config('ticket_system') eq 'RT_Internal') {
1254 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1255 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1256 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1257 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1260 if ( $ticket_dbh ) {
1262 my $ticket_sth = $ticket_dbh->prepare(
1263 'DELETE FROM Links WHERE Target = ?'
1265 my $errstr = $ticket_dbh->errstr;
1266 $dbh->rollback if $oldAutoCommit;
1269 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1271 my $errstr = $ticket_sth->errstr;
1272 $dbh->rollback if $oldAutoCommit;
1276 #check and see if the customer is the only link on the ticket, and
1277 #if so, set the ticket to deleted status in RT?
1278 #maybe someday, for now this will at least fix tickets not displaying
1282 #delete the customer record
1284 my $error = $self->SUPER::delete;
1286 $dbh->rollback if $oldAutoCommit;
1290 # cust_main exports!
1292 #my $export_args = $options{'export_args'} || [];
1295 map qsearch( 'part_export', {exportnum=>$_} ),
1296 $conf->config('cust_main-exports'); #, $agentnum
1298 foreach my $part_export ( @part_export ) {
1299 my $error = $part_export->export_delete( $self ); #, @$export_args);
1301 $dbh->rollback if $oldAutoCommit;
1302 return "exporting to ". $part_export->exporttype.
1303 " (transaction rolled back): $error";
1307 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1312 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1314 Replaces the OLD_RECORD with this one in the database. If there is an error,
1315 returns the error, otherwise returns false.
1317 To change the customer's address, set the pseudo-fields C<bill_location> and
1318 C<ship_location>. The address will still only change if at least one of the
1319 address fields differs from the existing values.
1321 INVOICING_LIST_ARYREF: If you pass an arrayref to this method, it will be
1322 set as the contact email address for a default contact with the same name as
1325 Currently available options are: I<tax_exemption>, I<cust_payby_params>,
1326 I<contact_params>, I<invoicing_list>.
1328 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1329 of tax names and exemption numbers. FS::cust_main_exemption records will be
1330 deleted and inserted as appropriate.
1332 I<cust_payby_params> and I<contact_params> can be hashrefs of named parameter
1333 groups (describing the customer's payment methods and contacts, respectively)
1334 in the style supported by L<FS::o2m_Common/process_o2m>. See L<FS::cust_payby>
1335 and L<FS::contact> for the fields these can contain.
1337 I<invoicing_list> is a synonym for the INVOICING_LIST_ARYREF parameter, and
1338 should be used instead if possible.
1345 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1347 : $self->replace_old;
1351 warn "$me replace called\n"
1354 my $curuser = $FS::CurrentUser::CurrentUser;
1355 return "You are not permitted to create complimentary accounts."
1356 if $self->complimentary eq 'Y'
1357 && $self->complimentary ne $old->complimentary
1358 && ! $curuser->access_right('Complimentary customer');
1360 local($ignore_expired_card) = 1
1361 if $old->payby =~ /^(CARD|DCRD)$/
1362 && $self->payby =~ /^(CARD|DCRD)$/
1363 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1365 local($ignore_banned_card) = 1
1366 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1367 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1368 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1370 if ( $self->payby =~ /^(CARD|DCRD)$/
1371 && $old->payinfo ne $self->payinfo
1372 && $old->paymask ne $self->paymask )
1374 my $error = $self->check_payinfo_cardtype;
1375 return $error if $error;
1378 return "Invoicing locale is required"
1381 && $conf->exists('cust_main-require_locale');
1383 local $SIG{HUP} = 'IGNORE';
1384 local $SIG{INT} = 'IGNORE';
1385 local $SIG{QUIT} = 'IGNORE';
1386 local $SIG{TERM} = 'IGNORE';
1387 local $SIG{TSTP} = 'IGNORE';
1388 local $SIG{PIPE} = 'IGNORE';
1390 my $oldAutoCommit = $FS::UID::AutoCommit;
1391 local $FS::UID::AutoCommit = 0;
1394 for my $l (qw(bill_location ship_location)) {
1395 #my $old_loc = $old->$l;
1396 my $new_loc = $self->$l or next;
1398 # find the existing location if there is one
1399 $new_loc->set('custnum' => $self->custnum);
1400 my $error = $new_loc->find_or_insert;
1402 $dbh->rollback if $oldAutoCommit;
1405 $self->set($l.'num', $new_loc->locationnum);
1409 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1410 warn "cust_main::replace: using deprecated invoicing list argument";
1411 $invoicing_list = shift @param;
1414 my %options = @param;
1416 $invoicing_list ||= $options{invoicing_list};
1418 my @contacts = map { $_->contact } $self->cust_contact;
1419 # find a contact that matches the customer's name
1420 my ($implicit_contact) = grep { $_->first eq $old->get('first')
1421 and $_->last eq $old->get('last') }
1423 $implicit_contact ||= FS::contact->new({
1424 'custnum' => $self->custnum,
1425 'locationnum' => $self->get('bill_locationnum'),
1428 # for any of these that are already contact emails, link to the existing
1430 if ( $invoicing_list ) {
1433 # kind of like process_m2m on these, except:
1434 # - the other side is two tables in a join
1435 # - and we might have to create new contact_emails
1436 # - and possibly a new contact
1438 # Find existing invoice emails that aren't on the implicit contact.
1439 # Any of these that are not on the new invoicing list will be removed.
1440 my %old_email_cust_contact;
1441 foreach my $cust_contact ($self->cust_contact) {
1442 next if !$cust_contact->invoice_dest;
1443 next if $cust_contact->contactnum == ($implicit_contact->contactnum || 0);
1445 foreach my $contact_email ($cust_contact->contact->contact_email) {
1446 $old_email_cust_contact{ $contact_email->emailaddress } = $cust_contact;
1450 foreach my $dest (@$invoicing_list) {
1452 if ($dest eq 'POST') {
1454 $self->set('postal_invoice', 'Y');
1456 } elsif ( exists($old_email_cust_contact{$dest}) ) {
1458 delete $old_email_cust_contact{$dest}; # don't need to remove it, then
1462 # See if it belongs to some other contact; if so, link it.
1463 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
1465 and $contact_email->contactnum != ($implicit_contact->contactnum || 0) ) {
1466 my $cust_contact = qsearchs('cust_contact', {
1467 contactnum => $contact_email->contactnum,
1468 custnum => $self->custnum,
1469 }) || FS::cust_contact->new({
1470 contactnum => $contact_email->contactnum,
1471 custnum => $self->custnum,
1473 $cust_contact->set('invoice_dest', 'Y');
1474 my $error = $cust_contact->custcontactnum ?
1475 $cust_contact->replace : $cust_contact->insert;
1477 $dbh->rollback if $oldAutoCommit;
1478 return "$error (linking to email address $dest)";
1482 # This email address is not yet linked to any contact, so it will
1483 # be added to the implicit contact.
1484 $email .= ',' if length($email);
1490 foreach my $remove_dest (keys %old_email_cust_contact) {
1491 my $cust_contact = $old_email_cust_contact{$remove_dest};
1492 # These were not in the list of requested destinations, so take them off.
1493 $cust_contact->set('invoice_dest', '');
1494 my $error = $cust_contact->replace;
1496 $dbh->rollback if $oldAutoCommit;
1497 return "$error (unlinking email address $remove_dest)";
1501 # make sure it keeps up with the changed customer name, if any
1502 $implicit_contact->set('last', $self->get('last'));
1503 $implicit_contact->set('first', $self->get('first'));
1504 $implicit_contact->set('emailaddress', $email);
1505 $implicit_contact->set('invoice_dest', 'Y');
1506 $implicit_contact->set('custnum', $self->custnum);
1509 if ( $implicit_contact->contactnum ) {
1510 $error = $implicit_contact->replace;
1511 } elsif ( length($email) ) { # don't create a new contact if not needed
1512 $error = $implicit_contact->insert;
1516 $dbh->rollback if $oldAutoCommit;
1517 return "$error (adding email address $email)";
1522 # replace the customer record
1523 my $error = $self->SUPER::replace($old);
1526 $dbh->rollback if $oldAutoCommit;
1530 # now move packages to the new service location
1531 $self->set('ship_location', ''); #flush cache
1532 if ( $old->ship_locationnum and # should only be null during upgrade...
1533 $old->ship_locationnum != $self->ship_locationnum ) {
1534 $error = $old->ship_location->move_to($self->ship_location);
1536 $dbh->rollback if $oldAutoCommit;
1540 # don't move packages based on the billing location, but
1541 # disable it if it's no longer in use
1542 if ( $old->bill_locationnum and
1543 $old->bill_locationnum != $self->bill_locationnum ) {
1544 $error = $old->bill_location->disable_if_unused;
1546 $dbh->rollback if $oldAutoCommit;
1551 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1553 #this could be more efficient than deleting and re-inserting, if it matters
1554 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1555 my $error = $cust_tag->delete;
1557 $dbh->rollback if $oldAutoCommit;
1561 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1562 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1563 'custnum' => $self->custnum };
1564 my $error = $cust_tag->insert;
1566 $dbh->rollback if $oldAutoCommit;
1573 my $tax_exemption = delete $options{'tax_exemption'};
1574 if ( $tax_exemption ) {
1576 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1577 if ref($tax_exemption) eq 'ARRAY';
1579 my %cust_main_exemption =
1580 map { $_->taxname => $_ }
1581 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1583 foreach my $taxname ( keys %$tax_exemption ) {
1585 if ( $cust_main_exemption{$taxname} &&
1586 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1589 delete $cust_main_exemption{$taxname};
1593 my $cust_main_exemption = new FS::cust_main_exemption {
1594 'custnum' => $self->custnum,
1595 'taxname' => $taxname,
1596 'exempt_number' => $tax_exemption->{$taxname},
1598 my $error = $cust_main_exemption->insert;
1600 $dbh->rollback if $oldAutoCommit;
1601 return "inserting cust_main_exemption (transaction rolled back): $error";
1605 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1606 my $error = $cust_main_exemption->delete;
1608 $dbh->rollback if $oldAutoCommit;
1609 return "deleting cust_main_exemption (transaction rolled back): $error";
1615 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1617 my $error = $self->process_o2m(
1618 'table' => 'cust_payby',
1619 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1620 'params' => $cust_payby_params,
1621 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1624 $dbh->rollback if $oldAutoCommit;
1630 if ( my $contact_params = delete $options{'contact_params'} ) {
1632 # this can potentially replace contacts that were created by the
1633 # invoicing list argument, but the UI shouldn't allow both of them
1636 my $error = $self->process_o2m(
1637 'table' => 'contact',
1638 'fields' => FS::contact->cgi_contact_fields,
1639 'params' => $contact_params,
1642 $dbh->rollback if $oldAutoCommit;
1648 unless ( $import || $skip_fuzzyfiles ) {
1649 $error = $self->queue_fuzzyfiles_update;
1651 $dbh->rollback if $oldAutoCommit;
1652 return "updating fuzzy search cache: $error";
1656 # tax district update in cust_location
1658 # cust_main exports!
1660 my $export_args = $options{'export_args'} || [];
1663 map qsearch( 'part_export', {exportnum=>$_} ),
1664 $conf->config('cust_main-exports'); #, $agentnum
1666 foreach my $part_export ( @part_export ) {
1667 my $error = $part_export->export_replace( $self, $old, @$export_args);
1669 $dbh->rollback if $oldAutoCommit;
1670 return "exporting to ". $part_export->exporttype.
1671 " (transaction rolled back): $error";
1675 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1680 =item queue_fuzzyfiles_update
1682 Used by insert & replace to update the fuzzy search cache
1686 use FS::cust_main::Search;
1687 sub queue_fuzzyfiles_update {
1690 local $SIG{HUP} = 'IGNORE';
1691 local $SIG{INT} = 'IGNORE';
1692 local $SIG{QUIT} = 'IGNORE';
1693 local $SIG{TERM} = 'IGNORE';
1694 local $SIG{TSTP} = 'IGNORE';
1695 local $SIG{PIPE} = 'IGNORE';
1697 my $oldAutoCommit = $FS::UID::AutoCommit;
1698 local $FS::UID::AutoCommit = 0;
1701 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1702 my $queue = new FS::queue {
1703 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1705 my @args = "cust_main.$field", $self->get($field);
1706 my $error = $queue->insert( @args );
1708 $dbh->rollback if $oldAutoCommit;
1709 return "queueing job (transaction rolled back): $error";
1714 push @locations, $self->bill_location if $self->bill_locationnum;
1715 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1716 foreach my $location (@locations) {
1717 my $queue = new FS::queue {
1718 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1720 my @args = 'cust_location.address1', $location->address1;
1721 my $error = $queue->insert( @args );
1723 $dbh->rollback if $oldAutoCommit;
1724 return "queueing job (transaction rolled back): $error";
1728 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1735 Checks all fields to make sure this is a valid customer record. If there is
1736 an error, returns the error, otherwise returns false. Called by the insert
1737 and replace methods.
1744 warn "$me check BEFORE: \n". $self->_dump
1748 $self->ut_numbern('custnum')
1749 || $self->ut_number('agentnum')
1750 || $self->ut_textn('agent_custid')
1751 || $self->ut_number('refnum')
1752 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1753 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1754 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1755 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1756 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1757 || $self->ut_textn('custbatch')
1758 || $self->ut_name('last')
1759 || $self->ut_name('first')
1760 || $self->ut_snumbern('signupdate')
1761 || $self->ut_snumbern('birthdate')
1762 || $self->ut_namen('spouse_last')
1763 || $self->ut_namen('spouse_first')
1764 || $self->ut_snumbern('spouse_birthdate')
1765 || $self->ut_snumbern('anniversary_date')
1766 || $self->ut_textn('company')
1767 || $self->ut_textn('ship_company')
1768 || $self->ut_anything('comments')
1769 || $self->ut_numbern('referral_custnum')
1770 || $self->ut_textn('stateid')
1771 || $self->ut_textn('stateid_state')
1772 || $self->ut_textn('invoice_terms')
1773 || $self->ut_floatn('cdr_termination_percentage')
1774 || $self->ut_floatn('credit_limit')
1775 || $self->ut_numbern('billday')
1776 || $self->ut_numbern('prorate_day')
1777 || $self->ut_flag('edit_subject')
1778 || $self->ut_flag('calling_list_exempt')
1779 || $self->ut_flag('invoice_noemail')
1780 || $self->ut_flag('message_noemail')
1781 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1782 || $self->ut_currencyn('currency')
1783 || $self->ut_textn('po_number')
1784 || $self->ut_enum('complimentary', [ '', 'Y' ])
1785 || $self->ut_flag('invoice_ship_address')
1786 || $self->ut_flag('invoice_dest')
1789 foreach (qw(company ship_company)) {
1790 my $company = $self->get($_);
1791 $company =~ s/^\s+//;
1792 $company =~ s/\s+$//;
1793 $company =~ s/\s+/ /g;
1794 $self->set($_, $company);
1797 #barf. need message catalogs. i18n. etc.
1798 $error .= "Please select an advertising source."
1799 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1800 return $error if $error;
1802 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1803 or return "Unknown agent";
1805 if ( $self->currency ) {
1806 my $agent_currency = qsearchs( 'agent_currency', {
1807 'agentnum' => $agent->agentnum,
1808 'currency' => $self->currency,
1810 or return "Agent ". $agent->agent.
1811 " not permitted to offer ". $self->currency. " invoicing";
1814 return "Unknown refnum"
1815 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1817 return "Unknown referring custnum: ". $self->referral_custnum
1818 unless ! $self->referral_custnum
1819 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1821 if ( $self->ss eq '' ) {
1826 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1827 or return "Illegal social security number: ". $self->ss;
1828 $self->ss("$1-$2-$3");
1831 #turn off invoice_ship_address if ship & bill are the same
1832 if ($self->bill_locationnum eq $self->ship_locationnum) {
1833 $self->invoice_ship_address('');
1836 # cust_main_county verification now handled by cust_location check
1839 $self->ut_phonen('daytime', $self->country)
1840 || $self->ut_phonen('night', $self->country)
1841 || $self->ut_phonen('fax', $self->country)
1842 || $self->ut_phonen('mobile', $self->country)
1844 return $error if $error;
1846 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1848 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1851 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1853 : FS::Msgcat::_gettext('daytime');
1854 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1856 : FS::Msgcat::_gettext('night');
1858 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1860 : FS::Msgcat::_gettext('mobile');
1862 return "$daytime_label, $night_label or $mobile_label is required"
1866 ### start of stuff moved to cust_payby
1867 # then mostly kept here to support upgrades (can remove in 5.x)
1868 # but modified to allow everything to be empty
1870 if ( $self->payby ) {
1871 FS::payby->can_payby($self->table, $self->payby)
1872 or return "Illegal payby: ". $self->payby;
1877 $error = $self->ut_numbern('paystart_month')
1878 || $self->ut_numbern('paystart_year')
1879 || $self->ut_numbern('payissue')
1880 || $self->ut_textn('paytype')
1882 return $error if $error;
1884 if ( $self->payip eq '' ) {
1887 $error = $self->ut_ip('payip');
1888 return $error if $error;
1891 # If it is encrypted and the private key is not availaible then we can't
1892 # check the credit card.
1893 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1895 # Need some kind of global flag to accept invalid cards, for testing
1897 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1898 $self->payby =~ /^(CARD|DCRD)$/ ) {
1900 my $payinfo = $self->payinfo;
1901 $payinfo =~ s/\D//g;
1902 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1903 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1905 $self->payinfo($payinfo);
1907 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1909 return gettext('unknown_card_type')
1910 if $self->payinfo !~ /^99\d{14}$/ #token
1911 && cardtype($self->payinfo) eq "Unknown";
1913 unless ( $ignore_banned_card ) {
1914 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1916 if ( $ban->bantype eq 'warn' ) {
1917 #or others depending on value of $ban->reason ?
1918 return '_duplicate_card'.
1919 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1920 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1921 ' (ban# '. $ban->bannum. ')'
1922 unless $self->override_ban_warn;
1924 return 'Banned credit card: banned on '.
1925 time2str('%a %h %o at %r', $ban->_date).
1926 ' by '. $ban->otaker.
1927 ' (ban# '. $ban->bannum. ')';
1932 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1933 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1934 $self->paycvv =~ /^(\d{4})$/
1935 or return "CVV2 (CID) for American Express cards is four digits.";
1938 $self->paycvv =~ /^(\d{3})$/
1939 or return "CVV2 (CVC2/CID) is three digits.";
1946 my $cardtype = cardtype($payinfo);
1947 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1949 return "Start date or issue number is required for $cardtype cards"
1950 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1952 return "Start month must be between 1 and 12"
1953 if $self->paystart_month
1954 and $self->paystart_month < 1 || $self->paystart_month > 12;
1956 return "Start year must be 1990 or later"
1957 if $self->paystart_year
1958 and $self->paystart_year < 1990;
1960 return "Issue number must be beween 1 and 99"
1962 and $self->payissue < 1 || $self->payissue > 99;
1965 $self->paystart_month('');
1966 $self->paystart_year('');
1967 $self->payissue('');
1970 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1971 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1973 my $payinfo = $self->payinfo;
1974 $payinfo =~ s/[^\d\@\.]//g;
1975 if ( $conf->config('echeck-country') eq 'CA' ) {
1976 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1977 or return 'invalid echeck account@branch.bank';
1978 $payinfo = "$1\@$2.$3";
1979 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1980 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1981 $payinfo = "$1\@$2";
1983 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1984 $payinfo = "$1\@$2";
1986 $self->payinfo($payinfo);
1989 unless ( $ignore_banned_card ) {
1990 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1992 if ( $ban->bantype eq 'warn' ) {
1993 #or others depending on value of $ban->reason ?
1994 return '_duplicate_ach' unless $self->override_ban_warn;
1996 return 'Banned ACH account: banned on '.
1997 time2str('%a %h %o at %r', $ban->_date).
1998 ' by '. $ban->otaker.
1999 ' (ban# '. $ban->bannum. ')';
2004 } elsif ( $self->payby eq 'LECB' ) {
2006 my $payinfo = $self->payinfo;
2007 $payinfo =~ s/\D//g;
2008 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2010 $self->payinfo($payinfo);
2013 } elsif ( $self->payby eq 'BILL' ) {
2015 $error = $self->ut_textn('payinfo');
2016 return "Illegal P.O. number: ". $self->payinfo if $error;
2019 } elsif ( $self->payby eq 'COMP' ) {
2021 my $curuser = $FS::CurrentUser::CurrentUser;
2022 if ( ! $self->custnum
2023 && ! $curuser->access_right('Complimentary customer')
2026 return "You are not permitted to create complimentary accounts."
2029 $error = $self->ut_textn('payinfo');
2030 return "Illegal comp account issuer: ". $self->payinfo if $error;
2033 } elsif ( $self->payby eq 'PREPAY' ) {
2035 my $payinfo = $self->payinfo;
2036 $payinfo =~ s/\W//g; #anything else would just confuse things
2037 $self->payinfo($payinfo);
2038 $error = $self->ut_alpha('payinfo');
2039 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2040 return "Unknown prepayment identifier"
2041 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2046 return "You are not permitted to create complimentary accounts."
2048 && $self->complimentary eq 'Y'
2049 && ! $FS::CurrentUser::CurrentUser->access_right('Complimentary customer');
2051 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2052 return "Expiration date required"
2053 # shouldn't payinfo_check do this?
2054 unless ! $self->payby
2055 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2059 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2060 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2061 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2062 ( $m, $y ) = ( $2, "19$1" );
2063 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2064 ( $m, $y ) = ( $3, "20$2" );
2066 return "Illegal expiration date: ". $self->paydate;
2068 $m = sprintf('%02d',$m);
2069 $self->paydate("$y-$m-01");
2070 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2071 return gettext('expired_card')
2073 && !$ignore_expired_card
2074 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2077 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2078 ( ! $conf->exists('require_cardname')
2079 || $self->payby !~ /^(CARD|DCRD)$/ )
2081 $self->payname( $self->first. " ". $self->getfield('last') );
2084 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2085 $self->payname =~ /^([\w \,\.\-\']*)$/
2086 or return gettext('illegal_name'). " payname: ". $self->payname;
2089 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2090 or return gettext('illegal_name'). " payname: ". $self->payname;
2096 ### end of stuff moved to cust_payby
2098 return "Please select an invoicing locale"
2101 && $conf->exists('cust_main-require_locale');
2103 return "Please select a customer class"
2104 if ! $self->classnum
2105 && $conf->exists('cust_main-require_classnum');
2107 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2108 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2112 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2114 warn "$me check AFTER: \n". $self->_dump
2117 $self->SUPER::check;
2120 sub check_payinfo_cardtype {
2123 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
2125 my $payinfo = $self->payinfo;
2126 $payinfo =~ s/\D//g;
2128 return '' if $payinfo =~ /^99\d{14}$/; #token
2130 my %bop_card_types = map { $_=>1 } values %{ card_types() };
2131 my $cardtype = cardtype($payinfo);
2133 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
2141 Additional checks for replace only.
2146 my ($new,$old) = @_;
2147 #preserve old value if global config is set
2148 if ($old && $conf->exists('invoice-ship_address')) {
2149 $new->invoice_ship_address($old->invoice_ship_address);
2156 Returns a list of fields which have ship_ duplicates.
2161 qw( last first company
2163 address1 address2 city county state zip country
2165 daytime night fax mobile
2169 =item has_ship_address
2171 Returns true if this customer record has a separate shipping address.
2175 sub has_ship_address {
2177 $self->bill_locationnum != $self->ship_locationnum;
2182 Returns a list of key/value pairs, with the following keys: address1,
2183 adddress2, city, county, state, zip, country, district, and geocode. The
2184 shipping address is used if present.
2190 $self->ship_location->location_hash;
2195 Returns all locations (see L<FS::cust_location>) for this customer.
2202 'table' => 'cust_location',
2203 'hashref' => { 'custnum' => $self->custnum,
2204 'prospectnum' => '',
2206 'order_by' => 'ORDER BY country, LOWER(state), LOWER(city), LOWER(county), LOWER(address1), LOWER(address2)',
2212 Returns all contact associations (see L<FS::cust_contact>) for this customer.
2218 qsearch('cust_contact', { 'custnum' => $self->custnum } );
2221 =item cust_payby PAYBY
2223 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2225 If one or more PAYBY are specified, returns only payment methods for specified PAYBY.
2226 Does not validate PAYBY.
2234 'table' => 'cust_payby',
2235 'hashref' => { 'custnum' => $self->custnum },
2236 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
2238 $search->{'extra_sql'} = ' AND payby IN ( '.
2239 join(',', map dbh->quote($_), @payby).
2246 =item has_cust_payby_auto
2248 Returns true if customer has an automatic payment method ('CARD' or 'CHEK')
2252 sub has_cust_payby_auto {
2255 'table' => 'cust_payby',
2256 'hashref' => { 'custnum' => $self->custnum, },
2257 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2258 'order_by' => 'LIMIT 1',
2265 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2266 and L<FS::cust_pkg>) for this customer, except those on hold.
2268 Returns a list: an empty list on success or a list of errors.
2274 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2279 Unsuspends all suspended packages in the on-hold state (those without setup
2280 dates) for this customer.
2286 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2291 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2293 Returns a list: an empty list on success or a list of errors.
2299 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2302 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2304 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2305 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2306 of a list of pkgparts; the hashref has the following keys:
2310 =item pkgparts - listref of pkgparts
2312 =item (other options are passed to the suspend method)
2317 Returns a list: an empty list on success or a list of errors.
2321 sub suspend_if_pkgpart {
2323 my (@pkgparts, %opt);
2324 if (ref($_[0]) eq 'HASH'){
2325 @pkgparts = @{$_[0]{pkgparts}};
2330 grep { $_->suspend(%opt) }
2331 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2332 $self->unsuspended_pkgs;
2335 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2337 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2338 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2339 instead of a list of pkgparts; the hashref has the following keys:
2343 =item pkgparts - listref of pkgparts
2345 =item (other options are passed to the suspend method)
2349 Returns a list: an empty list on success or a list of errors.
2353 sub suspend_unless_pkgpart {
2355 my (@pkgparts, %opt);
2356 if (ref($_[0]) eq 'HASH'){
2357 @pkgparts = @{$_[0]{pkgparts}};
2362 grep { $_->suspend(%opt) }
2363 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2364 $self->unsuspended_pkgs;
2367 =item cancel [ OPTION => VALUE ... ]
2369 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2370 The cancellation time will be now.
2374 Always returns a list: an empty list on success or a list of errors.
2381 warn "$me cancel called on customer ". $self->custnum. " with options ".
2382 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2384 my @pkgs = $self->ncancelled_pkgs;
2386 $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2389 =item cancel_pkgs OPTIONS
2391 Cancels a specified list of packages. OPTIONS can include:
2395 =item cust_pkg - an arrayref of the packages. Required.
2397 =item time - the cancellation time, used to calculate final bills and
2398 unused-time credits if any. Will be passed through to the bill() and
2399 FS::cust_pkg::cancel() methods.
2401 =item quiet - can be set true to supress email cancellation notices.
2403 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a
2404 reasonnum of an existing reason, or passing a hashref will create a new reason.
2405 The hashref should have the following keys:
2406 typenum - Reason type (see L<FS::reason_type>)
2407 reason - Text of the new reason.
2409 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2410 for the individual packages, parallel to the C<cust_pkg> argument. The
2411 reason and reason_otaker arguments will be taken from those objects.
2413 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2415 =item nobill - can be set true to skip billing if it might otherwise be done.
2420 my( $self, %opt ) = @_;
2422 # we're going to cancel services, which is not reversible
2423 die "cancel_pkgs cannot be run inside a transaction"
2424 if $FS::UID::AutoCommit == 0;
2426 local $FS::UID::AutoCommit = 0;
2428 return ( 'access denied' )
2429 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2431 if ( $opt{'ban'} ) {
2433 foreach my $cust_payby ( $self->cust_payby ) {
2435 #well, if they didn't get decrypted on search, then we don't have to
2436 # try again... queue a job for the server that does have decryption
2437 # capability if we're in a paranoid multi-server implementation?
2438 return ( "Can't (yet) ban encrypted credit cards" )
2439 if $cust_payby->is_encrypted($cust_payby->payinfo);
2441 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2442 my $error = $ban->insert;
2452 my @pkgs = @{ delete $opt{'cust_pkg'} };
2453 my $cancel_time = $opt{'time'} || time;
2455 # bill all packages first, so we don't lose usage, service counts for
2456 # bulk billing, etc.
2457 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2459 my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2461 'time' => $cancel_time );
2463 warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2465 return ( "Error billing during cancellation: $error" );
2470 $FS::UID::AutoCommit = 1;
2472 # now cancel all services, the same way we would for individual packages.
2473 # if any of them fail, cancel the rest anyway.
2474 my @cust_svc = map { $_->cust_svc } @pkgs;
2475 my @sorted_cust_svc =
2477 sort { $a->[1] <=> $b->[1] }
2478 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2480 warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2483 foreach my $cust_svc (@sorted_cust_svc) {
2484 my $part_svc = $cust_svc->part_svc;
2485 next if ( defined($part_svc) and $part_svc->preserve );
2486 my $error = $cust_svc->cancel; # immediate cancel, no date option
2487 push @errors, $error if $error;
2493 warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2494 $self->custnum. "\n"
2498 if ($opt{'cust_pkg_reason'}) {
2499 @cprs = @{ delete $opt{'cust_pkg_reason'} };
2505 my $cpr = shift @cprs;
2507 $lopt{'reason'} = $cpr->reasonnum;
2508 $lopt{'reason_otaker'} = $cpr->otaker;
2510 warn "no reason found when canceling package ".$_->pkgnum."\n";
2511 # we're not actually required to pass a reason to cust_pkg::cancel,
2512 # but if we're getting to this point, something has gone awry.
2513 $null_reason ||= FS::reason->new_or_existing(
2514 reason => 'unknown reason',
2515 type => 'Cancel Reason',
2518 $lopt{'reason'} = $null_reason->reasonnum;
2519 $lopt{'reason_otaker'} = $FS::CurrentUser::CurrentUser->username;
2522 my $error = $_->cancel(%lopt);
2523 push @errors, 'pkgnum '.$_->pkgnum.': '.$error if $error;
2529 sub _banned_pay_hashref {
2540 'payby' => $payby2ban{$self->payby},
2541 'payinfo' => $self->payinfo,
2542 #don't ever *search* on reason! #'reason' =>
2548 Returns all notes (see L<FS::cust_main_note>) for this customer.
2553 my($self,$orderby_classnum) = (shift,shift);
2554 my $orderby = "sticky DESC, _date DESC";
2555 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2556 qsearch( 'cust_main_note',
2557 { 'custnum' => $self->custnum },
2559 "ORDER BY $orderby",
2565 Returns the agent (see L<FS::agent>) for this customer.
2569 Returns the agent name (see L<FS::agent>) for this customer.
2575 $self->agent->agent;
2580 Returns any tags associated with this customer, as FS::cust_tag objects,
2581 or an empty list if there are no tags.
2585 Returns any tags associated with this customer, as FS::part_tag objects,
2586 or an empty list if there are no tags.
2592 map $_->part_tag, $self->cust_tag;
2598 Returns the customer class, as an FS::cust_class object, or the empty string
2599 if there is no customer class.
2603 Returns the customer category name, or the empty string if there is no customer
2610 my $cust_class = $self->cust_class;
2612 ? $cust_class->categoryname
2618 Returns the customer class name, or the empty string if there is no customer
2625 my $cust_class = $self->cust_class;
2627 ? $cust_class->classname
2633 Returns the external tax status, as an FS::tax_status object, or the empty
2634 string if there is no tax status.
2640 if ( $self->taxstatusnum ) {
2641 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2649 Returns the tax status code if there is one.
2655 my $tax_status = $self->tax_status;
2657 ? $tax_status->taxstatus
2661 =item BILLING METHODS
2663 Documentation on billing methods has been moved to
2664 L<FS::cust_main::Billing>.
2666 =item REALTIME BILLING METHODS
2668 Documentation on realtime billing methods has been moved to
2669 L<FS::cust_main::Billing_Realtime>.
2673 Removes the I<paycvv> field from the database directly.
2675 If there is an error, returns the error, otherwise returns false.
2677 DEPRECATED. Use L</remove_cvv_from_cust_payby> instead.
2683 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2684 or return dbh->errstr;
2685 $sth->execute($self->custnum)
2686 or return $sth->errstr;
2693 Returns the total owed for this customer on all invoices
2694 (see L<FS::cust_bill/owed>).
2700 $self->total_owed_date(2145859200); #12/31/2037
2703 =item total_owed_date TIME
2705 Returns the total owed for this customer on all invoices with date earlier than
2706 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2707 see L<Time::Local> and L<Date::Parse> for conversion functions.
2711 sub total_owed_date {
2715 my $custnum = $self->custnum;
2717 my $owed_sql = FS::cust_bill->owed_sql;
2720 SELECT SUM($owed_sql) FROM cust_bill
2721 WHERE custnum = $custnum
2725 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2729 =item total_owed_pkgnum PKGNUM
2731 Returns the total owed on all invoices for this customer's specific package
2732 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2736 sub total_owed_pkgnum {
2737 my( $self, $pkgnum ) = @_;
2738 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2741 =item total_owed_date_pkgnum TIME PKGNUM
2743 Returns the total owed for this customer's specific package when using
2744 experimental package balances on all invoices with date earlier than
2745 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2746 see L<Time::Local> and L<Date::Parse> for conversion functions.
2750 sub total_owed_date_pkgnum {
2751 my( $self, $time, $pkgnum ) = @_;
2754 foreach my $cust_bill (
2755 grep { $_->_date <= $time }
2756 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2758 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2760 sprintf( "%.2f", $total_bill );
2766 Returns the total amount of all payments.
2773 $total += $_->paid foreach $self->cust_pay;
2774 sprintf( "%.2f", $total );
2777 =item total_unapplied_credits
2779 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2780 customer. See L<FS::cust_credit/credited>.
2782 =item total_credited
2784 Old name for total_unapplied_credits. Don't use.
2788 sub total_credited {
2789 #carp "total_credited deprecated, use total_unapplied_credits";
2790 shift->total_unapplied_credits(@_);
2793 sub total_unapplied_credits {
2796 my $custnum = $self->custnum;
2798 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2801 SELECT SUM($unapplied_sql) FROM cust_credit
2802 WHERE custnum = $custnum
2805 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2809 =item total_unapplied_credits_pkgnum PKGNUM
2811 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2812 customer. See L<FS::cust_credit/credited>.
2816 sub total_unapplied_credits_pkgnum {
2817 my( $self, $pkgnum ) = @_;
2818 my $total_credit = 0;
2819 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2820 sprintf( "%.2f", $total_credit );
2824 =item total_unapplied_payments
2826 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2827 See L<FS::cust_pay/unapplied>.
2831 sub total_unapplied_payments {
2834 my $custnum = $self->custnum;
2836 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2839 SELECT SUM($unapplied_sql) FROM cust_pay
2840 WHERE custnum = $custnum
2843 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2847 =item total_unapplied_payments_pkgnum PKGNUM
2849 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2850 specific package when using experimental package balances. See
2851 L<FS::cust_pay/unapplied>.
2855 sub total_unapplied_payments_pkgnum {
2856 my( $self, $pkgnum ) = @_;
2857 my $total_unapplied = 0;
2858 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2859 sprintf( "%.2f", $total_unapplied );
2863 =item total_unapplied_refunds
2865 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2866 customer. See L<FS::cust_refund/unapplied>.
2870 sub total_unapplied_refunds {
2872 my $custnum = $self->custnum;
2874 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2877 SELECT SUM($unapplied_sql) FROM cust_refund
2878 WHERE custnum = $custnum
2881 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2887 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2888 total_unapplied_credits minus total_unapplied_payments).
2894 $self->balance_date_range;
2897 =item balance_date TIME
2899 Returns the balance for this customer, only considering invoices with date
2900 earlier than TIME (total_owed_date minus total_credited minus
2901 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2902 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2909 $self->balance_date_range(shift);
2912 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2914 Returns the balance for this customer, optionally considering invoices with
2915 date earlier than START_TIME, and not later than END_TIME
2916 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2918 Times are specified as SQL fragments or numeric
2919 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2920 L<Date::Parse> for conversion functions. The empty string can be passed
2921 to disable that time constraint completely.
2923 Accepts the same options as L<balance_date_sql>:
2927 =item unapplied_date
2929 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
2933 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2934 time will be ignored. Note that START_TIME and END_TIME only limit the date
2935 range for invoices and I<unapplied> payments, credits, and refunds.
2941 sub balance_date_range {
2943 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2944 ') FROM cust_main WHERE custnum='. $self->custnum;
2945 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2948 =item balance_pkgnum PKGNUM
2950 Returns the balance for this customer's specific package when using
2951 experimental package balances (total_owed plus total_unrefunded, minus
2952 total_unapplied_credits minus total_unapplied_payments)
2956 sub balance_pkgnum {
2957 my( $self, $pkgnum ) = @_;
2960 $self->total_owed_pkgnum($pkgnum)
2961 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2962 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2963 - $self->total_unapplied_credits_pkgnum($pkgnum)
2964 - $self->total_unapplied_payments_pkgnum($pkgnum)
2970 Returns a hash of useful information for making a payment.
2980 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2981 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2982 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2986 For credit card transactions:
2998 For electronic check transactions:
3013 $return{balance} = $self->balance;
3015 $return{payname} = $self->payname
3016 || ( $self->first. ' '. $self->get('last') );
3018 $return{$_} = $self->bill_location->$_
3019 for qw(address1 address2 city state zip);
3021 $return{payby} = $self->payby;
3022 $return{stateid_state} = $self->stateid_state;
3024 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3025 $return{card_type} = cardtype($self->payinfo);
3026 $return{payinfo} = $self->paymask;
3028 @return{'month', 'year'} = $self->paydate_monthyear;
3032 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3033 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3034 $return{payinfo1} = $payinfo1;
3035 $return{payinfo2} = $payinfo2;
3036 $return{paytype} = $self->paytype;
3037 $return{paystate} = $self->paystate;
3041 #doubleclick protection
3043 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3051 Returns the next payment expiration date for this customer. If they have no
3052 payment methods that will expire, returns 0.
3058 # filter out the ones that individually return 0, but then return 0 if
3059 # there are no results
3060 my @epochs = grep { $_ > 0 } map { $_->paydate_epoch } $self->cust_payby;
3061 min( @epochs ) || 0;
3064 =item paydate_epoch_sql
3066 Returns an SQL expression to get the next payment expiration date for a
3067 customer. Returns 2143260000 (2037-12-01) if there are no payment expiration
3068 dates, so that it's safe to test for "will it expire before date X" for any
3073 sub paydate_epoch_sql {
3075 my $paydate = FS::cust_payby->paydate_epoch_sql;
3076 "(SELECT COALESCE(MIN($paydate), 2143260000) FROM cust_payby WHERE cust_payby.custnum = cust_main.custnum)";
3080 my( $self, $taxname ) = @_;
3082 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3083 'taxname' => $taxname,
3088 =item cust_main_exemption
3090 =item invoicing_list
3092 Returns a list of email addresses (with svcnum entries expanded), and the word
3093 'POST' if the customer receives postal invoices.
3097 sub invoicing_list {
3098 my( $self, $arrayref ) = @_;
3101 warn "FS::cust_main::invoicing_list(ARRAY) is no longer supported.";
3104 my @emails = $self->invoicing_list_emailonly;
3105 push @emails, 'POST' if $self->get('postal_invoice');
3110 =item check_invoicing_list ARRAYREF
3112 Checks these arguements as valid input for the invoicing_list method. If there
3113 is an error, returns the error, otherwise returns false.
3117 sub check_invoicing_list {
3118 my( $self, $arrayref ) = @_;
3120 foreach my $address ( @$arrayref ) {
3122 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3123 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3126 my $cust_main_invoice = new FS::cust_main_invoice ( {
3127 'custnum' => $self->custnum,
3130 my $error = $self->custnum
3131 ? $cust_main_invoice->check
3132 : $cust_main_invoice->checkdest
3134 return $error if $error;
3138 return "Email address required"
3139 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3140 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3147 Returns the email addresses of all accounts provisioned for this customer.
3154 foreach my $cust_pkg ( $self->all_pkgs ) {
3155 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3157 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3158 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3160 $list{$_}=1 foreach map { $_->email } @svc_acct;
3165 =item invoicing_list_addpost
3167 Adds postal invoicing to this customer. If this customer is already configured
3168 to receive postal invoices, does nothing.
3172 sub invoicing_list_addpost {
3174 if ( $self->get('postal_invoice') eq '' ) {
3175 $self->set('postal_invoice', 'Y');
3176 my $error = $self->replace;
3177 warn $error if $error; # should fail harder, but this is traditional
3181 =item invoicing_list_emailonly
3183 Returns the list of email invoice recipients (invoicing_list without non-email
3184 destinations such as POST and FAX).
3188 sub invoicing_list_emailonly {
3190 warn "$me invoicing_list_emailonly called"
3192 return () if !$self->custnum; # not yet inserted
3193 return map { $_->emailaddress }
3195 table => 'cust_contact',
3196 select => 'emailaddress',
3197 addl_from => ' JOIN contact USING (contactnum) '.
3198 ' JOIN contact_email USING (contactnum)',
3199 hashref => { 'custnum' => $self->custnum, },
3200 extra_sql => q( AND cust_contact.invoice_dest = 'Y'),
3204 =item invoicing_list_emailonly_scalar
3206 Returns the list of email invoice recipients (invoicing_list without non-email
3207 destinations such as POST and FAX) as a comma-separated scalar.
3211 sub invoicing_list_emailonly_scalar {
3213 warn "$me invoicing_list_emailonly_scalar called"
3215 join(', ', $self->invoicing_list_emailonly);
3218 =item contact_list [ CLASSNUM, ... ]
3220 Returns a list of contacts (L<FS::contact> objects) for the customer. If
3221 a list of contact classnums is given, returns only contacts in those
3222 classes. If the pseudo-classnum 'invoice' is given, returns contacts that
3223 are marked as invoice destinations. If '0' is given, also returns contacts
3226 If no arguments are given, returns all contacts for the customer.
3234 select => 'contact.*, cust_contact.invoice_dest',
3235 addl_from => ' JOIN cust_contact USING (contactnum)',
3236 extra_sql => ' WHERE cust_contact.custnum = '.$self->custnum,
3242 if ( $_ eq 'invoice' ) {
3243 push @orwhere, 'cust_contact.invoice_dest = \'Y\'';
3244 } elsif ( $_ eq '0' ) {
3245 push @orwhere, 'cust_contact.classnum is null';
3246 } elsif ( /^\d+$/ ) {
3247 push @classnums, $_;
3249 die "bad classnum argument '$_'";
3254 push @orwhere, 'cust_contact.classnum IN ('.join(',', @classnums).')';
3257 $search->{extra_sql} .= ' AND (' .
3258 join(' OR ', map "( $_ )", @orwhere) .
3265 =item contact_list_email [ CLASSNUM, ... ]
3267 Same as L</contact_list>, but returns email destinations instead of contact
3272 sub contact_list_email {
3274 my @contacts = $self->contact_list(@_);
3276 foreach my $contact (@contacts) {
3277 foreach my $contact_email ($contact->contact_email) {
3279 $contact->firstlast . ' <' . $contact_email->emailaddress . '>';
3285 =item referral_custnum_cust_main
3287 Returns the customer who referred this customer (or the empty string, if
3288 this customer was not referred).
3290 Note the difference with referral_cust_main method: This method,
3291 referral_custnum_cust_main returns the single customer (if any) who referred
3292 this customer, while referral_cust_main returns an array of customers referred
3297 sub referral_custnum_cust_main {
3299 return '' unless $self->referral_custnum;
3300 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3303 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3305 Returns an array of customers referred by this customer (referral_custnum set
3306 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3307 customers referred by customers referred by this customer and so on, inclusive.
3308 The default behavior is DEPTH 1 (no recursion).
3310 Note the difference with referral_custnum_cust_main method: This method,
3311 referral_cust_main, returns an array of customers referred BY this customer,
3312 while referral_custnum_cust_main returns the single customer (if any) who
3313 referred this customer.
3317 sub referral_cust_main {
3319 my $depth = @_ ? shift : 1;
3320 my $exclude = @_ ? shift : {};
3323 map { $exclude->{$_->custnum}++; $_; }
3324 grep { ! $exclude->{ $_->custnum } }
3325 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3329 map { $_->referral_cust_main($depth-1, $exclude) }
3336 =item referral_cust_main_ncancelled
3338 Same as referral_cust_main, except only returns customers with uncancelled
3343 sub referral_cust_main_ncancelled {
3345 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3348 =item referral_cust_pkg [ DEPTH ]
3350 Like referral_cust_main, except returns a flat list of all unsuspended (and
3351 uncancelled) packages for each customer. The number of items in this list may
3352 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3356 sub referral_cust_pkg {
3358 my $depth = @_ ? shift : 1;
3360 map { $_->unsuspended_pkgs }
3361 grep { $_->unsuspended_pkgs }
3362 $self->referral_cust_main($depth);
3365 =item referring_cust_main
3367 Returns the single cust_main record for the customer who referred this customer
3368 (referral_custnum), or false.
3372 sub referring_cust_main {
3374 return '' unless $self->referral_custnum;
3375 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3378 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3380 Applies a credit to this customer. If there is an error, returns the error,
3381 otherwise returns false.
3383 REASON can be a text string, an FS::reason object, or a scalar reference to
3384 a reasonnum. If a text string, it will be automatically inserted as a new
3385 reason, and a 'reason_type' option must be passed to indicate the
3386 FS::reason_type for the new reason.
3388 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3389 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3390 I<commission_pkgnum>.
3392 Any other options are passed to FS::cust_credit::insert.
3397 my( $self, $amount, $reason, %options ) = @_;
3399 my $cust_credit = new FS::cust_credit {
3400 'custnum' => $self->custnum,
3401 'amount' => $amount,
3404 if ( ref($reason) ) {
3406 if ( ref($reason) eq 'SCALAR' ) {
3407 $cust_credit->reasonnum( $$reason );
3409 $cust_credit->reasonnum( $reason->reasonnum );
3413 $cust_credit->set('reason', $reason)
3416 $cust_credit->$_( delete $options{$_} )
3417 foreach grep exists($options{$_}),
3418 qw( addlinfo eventnum ),
3419 map "commission_$_", qw( agentnum salesnum pkgnum );
3421 $cust_credit->insert(%options);
3425 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3427 Creates a one-time charge for this customer. If there is an error, returns
3428 the error, otherwise returns false.
3430 New-style, with a hashref of options:
3432 my $error = $cust_main->charge(
3436 'start_date' => str2time('7/4/2009'),
3437 'pkg' => 'Description',
3438 'comment' => 'Comment',
3439 'additional' => [], #extra invoice detail
3440 'classnum' => 1, #pkg_class
3442 'setuptax' => '', # or 'Y' for tax exempt
3444 'locationnum'=> 1234, # optional
3447 'taxclass' => 'Tax class',
3450 'taxproduct' => 2, #part_pkg_taxproduct
3451 'override' => {}, #XXX describe
3453 #will be filled in with the new object
3454 'cust_pkg_ref' => \$cust_pkg,
3456 #generate an invoice immediately
3458 'invoice_terms' => '', #with these terms
3464 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3468 #super false laziness w/quotation::charge
3471 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3472 my ( $pkg, $comment, $additional );
3473 my ( $setuptax, $taxclass ); #internal taxes
3474 my ( $taxproduct, $override ); #vendor (CCH) taxes
3476 my $separate_bill = '';
3477 my $cust_pkg_ref = '';
3478 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3480 if ( ref( $_[0] ) ) {
3481 $amount = $_[0]->{amount};
3482 $setup_cost = $_[0]->{setup_cost};
3483 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3484 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3485 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3486 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3487 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3488 : '$'. sprintf("%.2f",$amount);
3489 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3490 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3491 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3492 $additional = $_[0]->{additional} || [];
3493 $taxproduct = $_[0]->{taxproductnum};
3494 $override = { '' => $_[0]->{tax_override} };
3495 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3496 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3497 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3498 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3499 $separate_bill = $_[0]->{separate_bill} || '';
3505 $pkg = @_ ? shift : 'One-time charge';
3506 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3508 $taxclass = @_ ? shift : '';
3512 local $SIG{HUP} = 'IGNORE';
3513 local $SIG{INT} = 'IGNORE';
3514 local $SIG{QUIT} = 'IGNORE';
3515 local $SIG{TERM} = 'IGNORE';
3516 local $SIG{TSTP} = 'IGNORE';
3517 local $SIG{PIPE} = 'IGNORE';
3519 my $oldAutoCommit = $FS::UID::AutoCommit;
3520 local $FS::UID::AutoCommit = 0;
3523 my $part_pkg = new FS::part_pkg ( {
3525 'comment' => $comment,
3529 'classnum' => ( $classnum ? $classnum : '' ),
3530 'setuptax' => $setuptax,
3531 'taxclass' => $taxclass,
3532 'taxproductnum' => $taxproduct,
3533 'setup_cost' => $setup_cost,
3536 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3537 ( 0 .. @$additional - 1 )
3539 'additional_count' => scalar(@$additional),
3540 'setup_fee' => $amount,
3543 my $error = $part_pkg->insert( options => \%options,
3544 tax_overrides => $override,
3547 $dbh->rollback if $oldAutoCommit;
3551 my $pkgpart = $part_pkg->pkgpart;
3552 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3553 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3554 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3555 $error = $type_pkgs->insert;
3557 $dbh->rollback if $oldAutoCommit;
3562 my $cust_pkg = new FS::cust_pkg ( {
3563 'custnum' => $self->custnum,
3564 'pkgpart' => $pkgpart,
3565 'quantity' => $quantity,
3566 'start_date' => $start_date,
3567 'no_auto' => $no_auto,
3568 'separate_bill' => $separate_bill,
3569 'locationnum'=> $locationnum,
3572 $error = $cust_pkg->insert;
3574 $dbh->rollback if $oldAutoCommit;
3576 } elsif ( $cust_pkg_ref ) {
3577 ${$cust_pkg_ref} = $cust_pkg;
3581 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3582 'pkg_list' => [ $cust_pkg ],
3585 $dbh->rollback if $oldAutoCommit;
3590 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3595 #=item charge_postal_fee
3597 #Applies a one time charge this customer. If there is an error,
3598 #returns the error, returns the cust_pkg charge object or false
3599 #if there was no charge.
3603 # This should be a customer event. For that to work requires that bill
3604 # also be a customer event.
3606 sub charge_postal_fee {
3609 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3610 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3612 my $cust_pkg = new FS::cust_pkg ( {
3613 'custnum' => $self->custnum,
3614 'pkgpart' => $pkgpart,
3618 my $error = $cust_pkg->insert;
3619 $error ? $error : $cust_pkg;
3622 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3624 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3626 Optionally, a list or hashref of additional arguments to the qsearch call can
3633 my $opt = ref($_[0]) ? shift : { @_ };
3635 #return $self->num_cust_bill unless wantarray || keys %$opt;
3637 $opt->{'table'} = 'cust_bill';
3638 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3639 $opt->{'hashref'}{'custnum'} = $self->custnum;
3640 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3642 map { $_ } #behavior of sort undefined in scalar context
3643 sort { $a->_date <=> $b->_date }
3647 =item open_cust_bill
3649 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3654 sub open_cust_bill {
3658 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3664 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3666 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3670 sub legacy_cust_bill {
3673 #return $self->num_legacy_cust_bill unless wantarray;
3675 map { $_ } #behavior of sort undefined in scalar context
3676 sort { $a->_date <=> $b->_date }
3677 qsearch({ 'table' => 'legacy_cust_bill',
3678 'hashref' => { 'custnum' => $self->custnum, },
3679 'order_by' => 'ORDER BY _date ASC',
3683 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3685 Returns all the statements (see L<FS::cust_statement>) for this customer.
3687 Optionally, a list or hashref of additional arguments to the qsearch call can
3692 =item cust_bill_void
3694 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3698 sub cust_bill_void {
3701 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3702 sort { $a->_date <=> $b->_date }
3703 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3706 sub cust_statement {
3708 my $opt = ref($_[0]) ? shift : { @_ };
3710 #return $self->num_cust_statement unless wantarray || keys %$opt;
3712 $opt->{'table'} = 'cust_statement';
3713 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3714 $opt->{'hashref'}{'custnum'} = $self->custnum;
3715 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3717 map { $_ } #behavior of sort undefined in scalar context
3718 sort { $a->_date <=> $b->_date }
3722 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3724 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3726 Optionally, a list or hashref of additional arguments to the qsearch call can
3727 be passed following the SVCDB.
3734 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3735 warn "$me svc_x requires a svcdb";
3738 my $opt = ref($_[0]) ? shift : { @_ };
3740 $opt->{'table'} = $svcdb;
3741 $opt->{'addl_from'} =
3742 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3743 ($opt->{'addl_from'} || '');
3745 my $custnum = $self->custnum;
3746 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3747 my $where = "cust_pkg.custnum = $custnum";
3749 my $extra_sql = $opt->{'extra_sql'} || '';
3750 if ( keys %{ $opt->{'hashref'} } ) {
3751 $extra_sql = " AND $where $extra_sql";
3754 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3755 $extra_sql = "WHERE $where AND $1";
3758 $extra_sql = "WHERE $where $extra_sql";
3761 $opt->{'extra_sql'} = $extra_sql;
3766 # required for use as an eventtable;
3769 $self->svc_x('svc_acct', @_);
3774 Returns all the credits (see L<FS::cust_credit>) for this customer.
3781 #return $self->num_cust_credit unless wantarray;
3783 map { $_ } #behavior of sort undefined in scalar context
3784 sort { $a->_date <=> $b->_date }
3785 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3788 =item cust_credit_pkgnum
3790 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3791 package when using experimental package balances.
3795 sub cust_credit_pkgnum {
3796 my( $self, $pkgnum ) = @_;
3797 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3798 sort { $a->_date <=> $b->_date }
3799 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3800 'pkgnum' => $pkgnum,
3805 =item cust_credit_void
3807 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3811 sub cust_credit_void {
3814 sort { $a->_date <=> $b->_date }
3815 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3820 Returns all the payments (see L<FS::cust_pay>) for this customer.
3826 my $opt = ref($_[0]) ? shift : { @_ };
3828 return $self->num_cust_pay unless wantarray || keys %$opt;
3830 $opt->{'table'} = 'cust_pay';
3831 $opt->{'hashref'}{'custnum'} = $self->custnum;
3833 map { $_ } #behavior of sort undefined in scalar context
3834 sort { $a->_date <=> $b->_date }
3841 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3842 called automatically when the cust_pay method is used in a scalar context.
3848 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3849 my $sth = dbh->prepare($sql) or die dbh->errstr;
3850 $sth->execute($self->custnum) or die $sth->errstr;
3851 $sth->fetchrow_arrayref->[0];
3854 =item unapplied_cust_pay
3856 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3860 sub unapplied_cust_pay {
3864 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3870 =item cust_pay_pkgnum
3872 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3873 package when using experimental package balances.
3877 sub cust_pay_pkgnum {
3878 my( $self, $pkgnum ) = @_;
3879 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3880 sort { $a->_date <=> $b->_date }
3881 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3882 'pkgnum' => $pkgnum,
3889 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3895 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3896 sort { $a->_date <=> $b->_date }
3897 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3900 =item cust_pay_pending
3902 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3903 (without status "done").
3907 sub cust_pay_pending {
3909 return $self->num_cust_pay_pending unless wantarray;
3910 sort { $a->_date <=> $b->_date }
3911 qsearch( 'cust_pay_pending', {
3912 'custnum' => $self->custnum,
3913 'status' => { op=>'!=', value=>'done' },
3918 =item cust_pay_pending_attempt
3920 Returns all payment attempts / declined payments for this customer, as pending
3921 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3922 a corresponding payment (see L<FS::cust_pay>).
3926 sub cust_pay_pending_attempt {
3928 return $self->num_cust_pay_pending_attempt unless wantarray;
3929 sort { $a->_date <=> $b->_date }
3930 qsearch( 'cust_pay_pending', {
3931 'custnum' => $self->custnum,
3938 =item num_cust_pay_pending
3940 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3941 customer (without status "done"). Also called automatically when the
3942 cust_pay_pending method is used in a scalar context.
3946 sub num_cust_pay_pending {
3949 " SELECT COUNT(*) FROM cust_pay_pending ".
3950 " WHERE custnum = ? AND status != 'done' ",
3955 =item num_cust_pay_pending_attempt
3957 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3958 customer, with status "done" but without a corresp. Also called automatically when the
3959 cust_pay_pending method is used in a scalar context.
3963 sub num_cust_pay_pending_attempt {
3966 " SELECT COUNT(*) FROM cust_pay_pending ".
3967 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3974 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3980 map { $_ } #return $self->num_cust_refund unless wantarray;
3981 sort { $a->_date <=> $b->_date }
3982 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3985 =item display_custnum
3987 Returns the displayed customer number for this customer: agent_custid if
3988 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3992 sub display_custnum {
3995 return $self->agent_custid
3996 if $default_agent_custid && $self->agent_custid;
3998 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4002 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
4003 } elsif ( $custnum_display_length ) {
4004 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
4006 return $self->custnum;
4012 Returns a name string for this customer, either "Company (Last, First)" or
4019 my $name = $self->contact;
4020 $name = $self->company. " ($name)" if $self->company;
4024 =item service_contact
4026 Returns the L<FS::contact> object for this customer that has the 'Service'
4027 contact class, or undef if there is no such contact. Deprecated; don't use
4032 sub service_contact {
4034 if ( !exists($self->{service_contact}) ) {
4035 my $classnum = $self->scalar_sql(
4036 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4037 ) || 0; #if it's zero, qsearchs will return nothing
4038 my $cust_contact = qsearchs('cust_contact', {
4039 'classnum' => $classnum,
4040 'custnum' => $self->custnum,
4042 $self->{service_contact} = $cust_contact->contact if $cust_contact;
4044 $self->{service_contact};
4049 Returns a name string for this (service/shipping) contact, either
4050 "Company (Last, First)" or "Last, First".
4057 my $name = $self->ship_contact;
4058 $name = $self->company. " ($name)" if $self->company;
4064 Returns a name string for this customer, either "Company" or "First Last".
4070 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4073 =item ship_name_short
4075 Returns a name string for this (service/shipping) contact, either "Company"
4080 sub ship_name_short {
4082 $self->service_contact
4083 ? $self->ship_contact_firstlast
4089 Returns this customer's full (billing) contact name only, "Last, First"
4095 $self->get('last'). ', '. $self->first;
4100 Returns this customer's full (shipping) contact name only, "Last, First"
4106 my $contact = $self->service_contact || $self;
4107 $contact->get('last') . ', ' . $contact->get('first');
4110 =item contact_firstlast
4112 Returns this customers full (billing) contact name only, "First Last".
4116 sub contact_firstlast {
4118 $self->first. ' '. $self->get('last');
4121 =item ship_contact_firstlast
4123 Returns this customer's full (shipping) contact name only, "First Last".
4127 sub ship_contact_firstlast {
4129 my $contact = $self->service_contact || $self;
4130 $contact->get('first') . ' '. $contact->get('last');
4133 sub bill_country_full {
4135 $self->bill_location->country_full;
4138 sub ship_country_full {
4140 $self->ship_location->country_full;
4143 =item county_state_county [ PREFIX ]
4145 Returns a string consisting of just the county, state and country.
4149 sub county_state_country {
4152 if ( @_ && $_[0] && $self->has_ship_address ) {
4153 $locationnum = $self->ship_locationnum;
4155 $locationnum = $self->bill_locationnum;
4157 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4158 $cust_location->county_state_country;
4161 =item geocode DATA_VENDOR
4163 Returns a value for the customer location as encoded by DATA_VENDOR.
4164 Currently this only makes sense for "CCH" as DATA_VENDOR.
4172 Returns a status string for this customer, currently:
4178 No packages have ever been ordered. Displayed as "No packages".
4182 Recurring packages all are new (not yet billed).
4186 One or more recurring packages is active.
4190 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
4194 All non-cancelled recurring packages are suspended.
4198 All recurring packages are cancelled.
4202 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4203 cust_main-status_module configuration option.
4207 sub status { shift->cust_status(@_); }
4211 return $self->hashref->{cust_status} if $self->hashref->{cust_status};
4212 for my $status ( FS::cust_main->statuses() ) {
4213 my $method = $status.'_sql';
4214 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4215 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4216 $sth->execute( ($self->custnum) x $numnum )
4217 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4218 if ( $sth->fetchrow_arrayref->[0] ) {
4219 $self->hashref->{cust_status} = $status;
4225 =item is_status_delay_cancel
4227 Returns true if customer status is 'suspended'
4228 and all suspended cust_pkg return true for
4229 cust_pkg->is_status_delay_cancel.
4231 This is not a real status, this only meant for hacking display
4232 values, because otherwise treating the customer as suspended is
4233 really the whole point of the delay_cancel option.
4237 sub is_status_delay_cancel {
4239 return 0 unless $self->status eq 'suspended';
4240 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4241 return 0 unless $cust_pkg->is_status_delay_cancel;
4246 =item ucfirst_cust_status
4248 =item ucfirst_status
4250 Deprecated, use the cust_status_label method instead.
4252 Returns the status with the first character capitalized.
4256 sub ucfirst_status {
4257 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4258 local($ucfirst_nowarn) = 1;
4259 shift->ucfirst_cust_status(@_);
4262 sub ucfirst_cust_status {
4263 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4265 ucfirst($self->cust_status);
4268 =item cust_status_label
4272 Returns the display label for this status.
4276 sub status_label { shift->cust_status_label(@_); }
4278 sub cust_status_label {
4280 __PACKAGE__->statuslabels->{$self->cust_status};
4285 Returns a hex triplet color string for this customer's status.
4289 sub statuscolor { shift->cust_statuscolor(@_); }
4291 sub cust_statuscolor {
4293 __PACKAGE__->statuscolors->{$self->cust_status};
4296 =item tickets [ STATUS ]
4298 Returns an array of hashes representing the customer's RT tickets.
4300 An optional status (or arrayref or hashref of statuses) may be specified.
4306 my $status = ( @_ && $_[0] ) ? shift : '';
4308 my $num = $conf->config('cust_main-max_tickets') || 10;
4311 if ( $conf->config('ticket_system') ) {
4312 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4314 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4323 foreach my $priority (
4324 $conf->config('ticket_system-custom_priority_field-values'), ''
4326 last if scalar(@tickets) >= $num;
4328 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4329 $num - scalar(@tickets),
4340 =item appointments [ STATUS ]
4342 Returns an array of hashes representing the customer's RT tickets which
4349 my $status = ( @_ && $_[0] ) ? shift : '';
4351 return () unless $conf->config('ticket_system');
4353 my $queueid = $conf->config('ticket_system-appointment-queueid');
4355 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4364 # Return services representing svc_accts in customer support packages
4365 sub support_services {
4367 my %packages = map { $_ => 1 } $conf->config('support_packages');
4369 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4370 grep { $_->part_svc->svcdb eq 'svc_acct' }
4371 map { $_->cust_svc }
4372 grep { exists $packages{ $_->pkgpart } }
4373 $self->ncancelled_pkgs;
4377 # Return a list of latitude/longitude for one of the services (if any)
4378 sub service_coordinates {
4382 grep { $_->latitude && $_->longitude }
4384 map { $_->cust_svc }
4385 $self->ncancelled_pkgs;
4387 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4392 Returns a masked version of the named field
4397 my ($self,$field) = @_;
4401 'x'x(length($self->getfield($field))-4).
4402 substr($self->getfield($field), (length($self->getfield($field))-4));
4406 =item payment_history
4408 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4409 cust_credit and cust_refund objects. Each hashref has the following fields:
4411 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4413 I<date> - value of _date field, unix timestamp
4415 I<date_pretty> - user-friendly date
4417 I<description> - user-friendly description of item
4419 I<amount> - impact of item on user's balance
4420 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4421 Not to be confused with the native 'amount' field in cust_credit, see below.
4423 I<amount_pretty> - includes money char
4425 I<balance> - customer balance, chronologically as of this item
4427 I<balance_pretty> - includes money char
4429 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4431 I<paid> - amount paid for cust_pay records, undef for other types
4433 I<credit> - amount credited for cust_credit records, undef for other types.
4434 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4436 I<refund> - amount refunded for cust_refund records, undef for other types
4438 The four table-specific keys always have positive values, whether they reflect charges or payments.
4440 The following options may be passed to this method:
4442 I<line_items> - if true, returns charges ('Line item') rather than invoices
4444 I<start_date> - unix timestamp, only include records on or after.
4445 If specified, an item of type 'Previous' will also be included.
4446 It does not have table-specific fields.
4448 I<end_date> - unix timestamp, only include records before
4450 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4452 I<conf> - optional already-loaded FS::Conf object.
4456 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4457 # and also for sending customer statements, which should both be kept customer-friendly.
4458 # If you add anything that shouldn't be passed on through the API or exposed
4459 # to customers, add a new option to include it, don't include it by default
4460 sub payment_history {
4462 my $opt = ref($_[0]) ? $_[0] : { @_ };
4464 my $conf = $$opt{'conf'} || new FS::Conf;
4465 my $money_char = $conf->config("money_char") || '$',
4467 #first load entire history,
4468 #need previous to calculate previous balance
4469 #loading after end_date shouldn't hurt too much?
4471 if ( $$opt{'line_items'} ) {
4473 foreach my $cust_bill ( $self->cust_bill ) {
4476 'type' => 'Line item',
4477 'description' => $_->desc( $self->locale ).
4478 ( $_->sdate && $_->edate
4479 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4480 ' To '. time2str('%d-%b-%Y', $_->edate)
4483 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4484 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4485 'date' => $cust_bill->_date,
4486 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4488 foreach $cust_bill->cust_bill_pkg;
4495 'type' => 'Invoice',
4496 'description' => 'Invoice #'. $_->display_invnum,
4497 'amount' => sprintf('%.2f', $_->charged ),
4498 'charged' => sprintf('%.2f', $_->charged ),
4499 'date' => $_->_date,
4500 'date_pretty' => $self->time2str_local('short', $_->_date ),
4502 foreach $self->cust_bill;
4507 'type' => 'Payment',
4508 'description' => 'Payment', #XXX type
4509 'amount' => sprintf('%.2f', 0 - $_->paid ),
4510 'paid' => sprintf('%.2f', $_->paid ),
4511 'date' => $_->_date,
4512 'date_pretty' => $self->time2str_local('short', $_->_date ),
4514 foreach $self->cust_pay;
4518 'description' => 'Credit', #more info?
4519 'amount' => sprintf('%.2f', 0 -$_->amount ),
4520 'credit' => sprintf('%.2f', $_->amount ),
4521 'date' => $_->_date,
4522 'date_pretty' => $self->time2str_local('short', $_->_date ),
4524 foreach $self->cust_credit;
4528 'description' => 'Refund', #more info? type, like payment?
4529 'amount' => $_->refund,
4530 'refund' => $_->refund,
4531 'date' => $_->_date,
4532 'date_pretty' => $self->time2str_local('short', $_->_date ),
4534 foreach $self->cust_refund;
4536 #put it all in chronological order
4537 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4539 #calculate balance, filter items outside date range
4543 foreach my $item (@history) {
4544 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4545 $balance += $$item{'amount'};
4546 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4547 $previous += $$item{'amount'};
4550 $$item{'balance'} = sprintf("%.2f",$balance);
4551 foreach my $key ( qw(amount balance) ) {
4552 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4557 # start with previous balance, if there was one
4560 'type' => 'Previous',
4561 'description' => 'Previous balance',
4562 'amount' => sprintf("%.2f",$previous),
4563 'balance' => sprintf("%.2f",$previous),
4564 'date' => $$opt{'start_date'},
4565 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4567 #false laziness with above
4568 foreach my $key ( qw(amount balance) ) {
4569 $$item{$key.'_pretty'} = $$item{$key};
4570 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4572 unshift(@out,$item);
4575 @out = reverse @history if $$opt{'reverse_sort'};
4580 =item save_cust_payby
4582 Saves a new cust_payby for this customer, replacing an existing entry only
4583 in select circumstances. Does not validate input.
4585 If auto is specified, marks this as the customer's primary method, or the
4586 specified weight. Existing payment methods have their weight incremented as
4589 If bill_location is specified with auto, also sets location in cust_main.
4591 Will not insert complete duplicates of existing records, or records in which the
4592 only difference from an existing record is to turn off automatic payment (will
4593 return without error.) Will replace existing records in which the only difference
4594 is to add a value to a previously empty preserved field and/or turn on automatic payment.
4595 Fields marked as preserved are optional, and existing values will not be overwritten with
4596 blanks when replacing.
4598 Accepts the following named parameters:
4608 save as an automatic payment type (CARD/CHEK if true, DCRD/DCHK if false)
4612 optional, set higher than 1 for secondary, etc.
4620 optional, but should be specified for anything that might be tokenized, will be preserved when replacing
4628 optional, will be preserved when replacing
4636 CARD only, required, FS::cust_location object
4638 =item paystart_month
4640 CARD only, optional, will be preserved when replacing
4644 CARD only, optional, will be preserved when replacing
4648 CARD only, optional, will be preserved when replacing
4652 CARD only, only used if conf cvv-save is set appropriately
4666 #The code for this option is in place, but it's not currently used
4670 # existing cust_payby object to be replaced (must match custnum)
4672 # stateid/stateid_state/ss are not currently supported in cust_payby,
4673 # might not even work properly in 4.x, but will need to work here if ever added
4675 sub save_cust_payby {
4679 my $old = $opt{'replace'};
4680 my $new = new FS::cust_payby { $old ? $old->hash : () };
4681 return "Customer number does not match" if $new->custnum and $new->custnum != $self->custnum;
4682 $new->set( 'custnum' => $self->custnum );
4684 my $payby = $opt{'payment_payby'};
4685 return "Bad payby" unless grep(/^$payby$/,('CARD','CHEK'));
4687 # don't allow turning off auto when replacing
4688 $opt{'auto'} ||= 1 if $old and $old->payby !~ /^D/;
4690 my @check_existing; # payby relevant to this payment_payby
4692 # set payby based on auto
4693 if ( $payby eq 'CARD' ) {
4694 $new->set( 'payby' => ( $opt{'auto'} ? 'CARD' : 'DCRD' ) );
4695 @check_existing = qw( CARD DCRD );
4696 } elsif ( $payby eq 'CHEK' ) {
4697 $new->set( 'payby' => ( $opt{'auto'} ? 'CHEK' : 'DCHK' ) );
4698 @check_existing = qw( CHEK DCHK );
4701 $new->set( 'weight' => $opt{'auto'} ? $opt{'weight'} : '' );
4704 $new->payinfo($opt{'payinfo'}); # sets default paymask, but not if it's already tokenized
4705 $new->paymask($opt{'paymask'}) if $opt{'paymask'}; # in case it's been tokenized, override with loaded paymask
4706 $new->set( 'payname' => $opt{'payname'} );
4707 $new->set( 'payip' => $opt{'payip'} ); # will be preserved below
4709 my $conf = new FS::Conf;
4711 # compare to FS::cust_main::realtime_bop - check both to make sure working correctly
4712 if ( $payby eq 'CARD' &&
4713 ( (grep { $_ eq cardtype($opt{'payinfo'}) } $conf->config('cvv-save'))
4714 || $conf->exists('business-onlinepayment-verification')
4717 $new->set( 'paycvv' => $opt{'paycvv'} );
4719 $new->set( 'paycvv' => '');
4722 local $SIG{HUP} = 'IGNORE';
4723 local $SIG{INT} = 'IGNORE';
4724 local $SIG{QUIT} = 'IGNORE';
4725 local $SIG{TERM} = 'IGNORE';
4726 local $SIG{TSTP} = 'IGNORE';
4727 local $SIG{PIPE} = 'IGNORE';
4729 my $oldAutoCommit = $FS::UID::AutoCommit;
4730 local $FS::UID::AutoCommit = 0;
4733 # set fields specific to payment_payby
4734 if ( $payby eq 'CARD' ) {
4735 if ($opt{'bill_location'}) {
4736 $opt{'bill_location'}->set('custnum' => $self->custnum);
4737 my $error = $opt{'bill_location'}->find_or_insert;
4739 $dbh->rollback if $oldAutoCommit;
4742 $new->set( 'locationnum' => $opt{'bill_location'}->locationnum );
4744 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
4745 $new->set( $field => $opt{$field} );
4748 foreach my $field ( qw(paytype paystate) ) {
4749 $new->set( $field => $opt{$field} );
4753 # other cust_payby to compare this to
4754 my @existing = $self->cust_payby(@check_existing);
4756 # fields that can overwrite blanks with values, but not values with blanks
4757 my @preserve = qw( paymask locationnum paystart_month paystart_year payissue payip );
4759 my $skip_cust_payby = 0; # true if we don't need to save or reweight cust_payby
4761 # generally, we don't want to overwrite existing cust_payby with this,
4762 # but we can replace if we're only marking it auto or adding a preserved field
4763 # and we can avoid saving a total duplicate or merely turning off auto
4765 foreach my $cust_payby (@existing) {
4766 # check fields that absolutely should not change
4767 foreach my $field ($new->fields) {
4768 next if grep(/^$field$/, qw( custpaybynum payby weight ) );
4769 next if grep(/^$field$/, @preserve );
4770 next PAYBYLOOP unless $new->get($field) eq $cust_payby->get($field);
4772 # now check fields that can replace if one value is blank
4774 foreach my $field (@preserve) {
4776 ( $new->get($field) and !$cust_payby->get($field) ) or
4777 ( $cust_payby->get($field) and !$new->get($field) )
4779 # prevention of overwriting values with blanks happens farther below
4781 } elsif ( $new->get($field) ne $cust_payby->get($field) ) {
4785 unless ( $replace ) {
4786 # nearly identical, now check weight
4787 if ($new->get('weight') eq $cust_payby->get('weight') or !$new->get('weight')) {
4788 # ignore identical cust_payby, and ignore attempts to turn off auto
4789 # no need to save or re-weight cust_payby (but still need to update/commit $self)
4790 $skip_cust_payby = 1;
4793 # otherwise, only change is to mark this as primary
4795 # if we got this far, we're definitely replacing
4802 $new->set( 'custpaybynum' => $old->custpaybynum );
4803 # don't turn off automatic payment (but allow it to be turned on)
4804 if ($new->payby =~ /^D/ and $new->payby ne $old->payby) {
4806 $new->set( 'payby' => $old->payby );
4807 $new->set( 'weight' => 1 );
4809 # make sure we're not overwriting values with blanks
4810 foreach my $field (@preserve) {
4811 if ( $old->get($field) and !$new->get($field) ) {
4812 $new->set( $field => $old->get($field) );
4817 # only overwrite cust_main bill_location if auto
4818 if ($opt{'auto'} && $opt{'bill_location'}) {
4819 $self->set('bill_location' => $opt{'bill_location'});
4820 my $error = $self->replace;
4822 $dbh->rollback if $oldAutoCommit;
4827 # done with everything except reweighting and saving cust_payby
4828 # still need to commit changes to cust_main and cust_location
4829 if ($skip_cust_payby) {
4830 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4834 # re-weight existing primary cust_pay for this payby
4836 foreach my $cust_payby (@existing) {
4837 # relies on cust_payby return order
4838 last unless $cust_payby->payby !~ /^D/;
4839 last if $cust_payby->weight > 1;
4840 next if $new->custpaybynum eq $cust_payby->custpaybynum;
4841 next if $cust_payby->weight < ($opt{'weight'} || 1);
4842 $cust_payby->weight( $cust_payby->weight + 1 );
4843 my $error = $cust_payby->replace;
4845 $dbh->rollback if $oldAutoCommit;
4846 return "Error reweighting cust_payby: $error";
4851 # finally, save cust_payby
4852 my $error = $old ? $new->replace($old) : $new->insert;
4854 $dbh->rollback if $oldAutoCommit;
4858 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4863 =item remove_cvv_from_cust_payby PAYINFO
4865 Removes paycvv from associated cust_payby with matching PAYINFO.
4869 sub remove_cvv_from_cust_payby {
4870 my ($self,$payinfo) = @_;
4872 my $oldAutoCommit = $FS::UID::AutoCommit;
4873 local $FS::UID::AutoCommit = 0;
4876 foreach my $cust_payby ( qsearch('cust_payby',{ custnum => $self->custnum }) ) {
4877 next unless $cust_payby->payinfo eq $payinfo; # can't qsearch on payinfo
4878 $cust_payby->paycvv('');
4879 my $error = $cust_payby->replace;
4881 $dbh->rollback if $oldAutoCommit;
4886 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4892 =head1 CLASS METHODS
4898 Class method that returns the list of possible status strings for customers
4899 (see L<the status method|/status>). For example:
4901 @statuses = FS::cust_main->statuses();
4907 keys %{ $self->statuscolors };
4910 =item cust_status_sql
4912 Returns an SQL fragment to determine the status of a cust_main record, as a
4917 sub cust_status_sql {
4919 for my $status ( FS::cust_main->statuses() ) {
4920 my $method = $status.'_sql';
4921 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4930 Returns an SQL expression identifying prospective cust_main records (customers
4931 with no packages ever ordered)
4935 use vars qw($select_count_pkgs);
4936 $select_count_pkgs =
4937 "SELECT COUNT(*) FROM cust_pkg
4938 WHERE cust_pkg.custnum = cust_main.custnum";
4940 sub select_count_pkgs_sql {
4945 " 0 = ( $select_count_pkgs ) ";
4950 Returns an SQL expression identifying ordered cust_main records (customers with
4951 no active packages, but recurring packages not yet setup or one time charges
4957 FS::cust_main->none_active_sql.
4958 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4963 Returns an SQL expression identifying active cust_main records (customers with
4964 active recurring packages).
4969 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4972 =item none_active_sql
4974 Returns an SQL expression identifying cust_main records with no active
4975 recurring packages. This includes customers of status prospect, ordered,
4976 inactive, and suspended.
4980 sub none_active_sql {
4981 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4986 Returns an SQL expression identifying inactive cust_main records (customers with
4987 no active recurring packages, but otherwise unsuspended/uncancelled).
4992 FS::cust_main->none_active_sql.
4993 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4999 Returns an SQL expression identifying suspended cust_main records.
5004 sub suspended_sql { susp_sql(@_); }
5006 FS::cust_main->none_active_sql.
5007 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
5013 Returns an SQL expression identifying cancelled cust_main records.
5017 sub cancel_sql { shift->cancelled_sql(@_); }
5020 =item uncancelled_sql
5022 Returns an SQL expression identifying un-cancelled cust_main records.
5026 sub uncancelled_sql { uncancel_sql(@_); }
5029 "( NOT (".$self->cancelled_sql.") )"; #sensitive to cust_main-status_module
5034 Returns an SQL fragment to retreive the balance.
5039 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5040 WHERE cust_bill.custnum = cust_main.custnum )
5041 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5042 WHERE cust_pay.custnum = cust_main.custnum )
5043 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5044 WHERE cust_credit.custnum = cust_main.custnum )
5045 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5046 WHERE cust_refund.custnum = cust_main.custnum )
5049 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
5051 Returns an SQL fragment to retreive the balance for this customer, optionally
5052 considering invoices with date earlier than START_TIME, and not
5053 later than END_TIME (total_owed_date minus total_unapplied_credits minus
5054 total_unapplied_payments).
5056 Times are specified as SQL fragments or numeric
5057 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5058 L<Date::Parse> for conversion functions. The empty string can be passed
5059 to disable that time constraint completely.
5061 Available options are:
5065 =item unapplied_date
5067 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
5072 set to true to remove all customer comparison clauses, for totals
5077 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5082 JOIN clause (typically used with the total option)
5086 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
5087 time will be ignored. Note that START_TIME and END_TIME only limit the date
5088 range for invoices and I<unapplied> payments, credits, and refunds.
5094 sub balance_date_sql {
5095 my( $class, $start, $end, %opt ) = @_;
5097 my $cutoff = $opt{'cutoff'};
5099 my $owed = FS::cust_bill->owed_sql($cutoff);
5100 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
5101 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
5102 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5104 my $j = $opt{'join'} || '';
5106 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5107 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5108 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5109 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5111 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5112 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5113 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5114 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5119 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
5121 Returns an SQL fragment to retreive the total unapplied payments for this
5122 customer, only considering payments with date earlier than START_TIME, and
5123 optionally not later than END_TIME.
5125 Times are specified as SQL fragments or numeric
5126 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5127 L<Date::Parse> for conversion functions. The empty string can be passed
5128 to disable that time constraint completely.
5130 Available options are:
5134 sub unapplied_payments_date_sql {
5135 my( $class, $start, $end, %opt ) = @_;
5137 my $cutoff = $opt{'cutoff'};
5139 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5141 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
5142 'unapplied_date'=>1 );
5144 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
5147 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5149 Helper method for balance_date_sql; name (and usage) subject to change
5150 (suggestions welcome).
5152 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5153 cust_refund, cust_credit or cust_pay).
5155 If TABLE is "cust_bill" or the unapplied_date option is true, only
5156 considers records with date earlier than START_TIME, and optionally not
5157 later than END_TIME .
5161 sub _money_table_where {
5162 my( $class, $table, $start, $end, %opt ) = @_;
5165 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5166 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5167 push @where, "$table._date <= $start" if defined($start) && length($start);
5168 push @where, "$table._date > $end" if defined($end) && length($end);
5170 push @where, @{$opt{'where'}} if $opt{'where'};
5171 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5177 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
5178 use FS::cust_main::Search;
5181 FS::cust_main::Search->search(@_);
5190 #=item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5192 #Deprecated. Use event notification and message templates
5193 #(L<FS::msg_template>) instead.
5195 #Sends a templated email notification to the customer (see L<Text::Template>).
5197 #OPTIONS is a hash and may include
5199 #I<from> - the email sender (default is invoice_from)
5201 #I<to> - comma-separated scalar or arrayref of recipients
5202 # (default is invoicing_list)
5204 #I<subject> - The subject line of the sent email notification
5205 # (default is "Notice from company_name")
5207 #I<extra_fields> - a hashref of name/value pairs which will be substituted
5210 #The following variables are vavailable in the template.
5212 #I<$first> - the customer first name
5213 #I<$last> - the customer last name
5214 #I<$company> - the customer company
5215 #I<$payby> - a description of the method of payment for the customer
5216 # # would be nice to use FS::payby::shortname
5217 #I<$payinfo> - the account information used to collect for this customer
5218 #I<$expdate> - the expiration of the customer payment in seconds from epoch
5223 # my ($self, $template, %options) = @_;
5225 # return unless $conf->exists($template);
5227 # my $from = $conf->invoice_from_full($self->agentnum)
5228 # if $conf->exists('invoice_from', $self->agentnum);
5229 # $from = $options{from} if exists($options{from});
5231 # my $to = join(',', $self->invoicing_list_emailonly);
5232 # $to = $options{to} if exists($options{to});
5234 # my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5235 # if $conf->exists('company_name', $self->agentnum);
5236 # $subject = $options{subject} if exists($options{subject});
5238 # my $notify_template = new Text::Template (TYPE => 'ARRAY',
5239 # SOURCE => [ map "$_\n",
5240 # $conf->config($template)]
5242 # or die "can't create new Text::Template object: Text::Template::ERROR";
5243 # $notify_template->compile()
5244 # or die "can't compile template: Text::Template::ERROR";
5246 # $FS::notify_template::_template::company_name =
5247 # $conf->config('company_name', $self->agentnum);
5248 # $FS::notify_template::_template::company_address =
5249 # join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5251 # my $paydate = $self->paydate || '2037-12-31';
5252 # $FS::notify_template::_template::first = $self->first;
5253 # $FS::notify_template::_template::last = $self->last;
5254 # $FS::notify_template::_template::company = $self->company;
5255 # $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5256 # my $payby = $self->payby;
5257 # my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5258 # my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5260 # #credit cards expire at the end of the month/year of their exp date
5261 # if ($payby eq 'CARD' || $payby eq 'DCRD') {
5262 # $FS::notify_template::_template::payby = 'credit card';
5263 # ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5264 # $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5266 # }elsif ($payby eq 'COMP') {
5267 # $FS::notify_template::_template::payby = 'complimentary account';
5269 # $FS::notify_template::_template::payby = 'current method';
5271 # $FS::notify_template::_template::expdate = $expire_time;
5273 # for (keys %{$options{extra_fields}}){
5275 # ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5278 # send_email(from => $from,
5280 # subject => $subject,
5281 # body => $notify_template->fill_in( PACKAGE =>
5282 # 'FS::notify_template::_template' ),
5287 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5289 Generates a templated notification to the customer (see L<Text::Template>).
5291 OPTIONS is a hash and may include
5293 I<extra_fields> - a hashref of name/value pairs which will be substituted
5294 into the template. These values may override values mentioned below
5295 and those from the customer record.
5297 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5299 The following variables are available in the template instead of or in addition
5300 to the fields of the customer record.
5302 I<$payby> - a description of the method of payment for the customer
5303 # would be nice to use FS::payby::shortname
5304 I<$payinfo> - the masked account information used to collect for this customer
5305 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5306 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5310 # a lot like cust_bill::print_latex
5311 sub generate_letter {
5312 my ($self, $template, %options) = @_;
5314 warn "Template $template does not exist" && return
5315 unless $conf->exists($template) || $options{'template_text'};
5317 my $template_source = $options{'template_text'}
5318 ? [ $options{'template_text'} ]
5319 : [ map "$_\n", $conf->config($template) ];
5321 my $letter_template = new Text::Template
5323 SOURCE => $template_source,
5324 DELIMITERS => [ '[@--', '--@]' ],
5326 or die "can't create new Text::Template object: Text::Template::ERROR";
5328 $letter_template->compile()
5329 or die "can't compile template: Text::Template::ERROR";
5331 my %letter_data = map { $_ => $self->$_ } $self->fields;
5332 $letter_data{payinfo} = $self->mask_payinfo;
5334 #my $paydate = $self->paydate || '2037-12-31';
5335 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5337 my $payby = $self->payby;
5338 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5339 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5341 #credit cards expire at the end of the month/year of their exp date
5342 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5343 $letter_data{payby} = 'credit card';
5344 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5345 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5347 }elsif ($payby eq 'COMP') {
5348 $letter_data{payby} = 'complimentary account';
5350 $letter_data{payby} = 'current method';
5352 $letter_data{expdate} = $expire_time;
5354 for (keys %{$options{extra_fields}}){
5355 $letter_data{$_} = $options{extra_fields}->{$_};
5358 unless(exists($letter_data{returnaddress})){
5359 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5360 $self->agent_template)
5362 if ( length($retadd) ) {
5363 $letter_data{returnaddress} = $retadd;
5364 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5365 $letter_data{returnaddress} =
5366 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5370 ( $conf->config('company_name', $self->agentnum),
5371 $conf->config('company_address', $self->agentnum),
5375 $letter_data{returnaddress} = '~';
5379 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5381 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5383 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5385 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5389 ) or die "can't open temp file: $!\n";
5390 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5391 or die "can't write temp file: $!\n";
5393 $letter_data{'logo_file'} = $lh->filename;
5395 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5399 ) or die "can't open temp file: $!\n";
5401 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5403 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5404 return ($1, $letter_data{'logo_file'});
5408 =item print_ps TEMPLATE
5410 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5416 my($file, $lfile) = $self->generate_letter(@_);
5417 my $ps = FS::Misc::generate_ps($file);
5418 unlink($file.'.tex');
5424 =item print TEMPLATE
5426 Prints the filled in template.
5428 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5432 sub queueable_print {
5435 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5436 or die "invalid customer number: " . $opt{custnum};
5438 #do not backport this change to 3.x
5439 # my $error = $self->print( { 'template' => $opt{template} } );
5440 my $error = $self->print( $opt{'template'} );
5441 die $error if $error;
5445 my ($self, $template) = (shift, shift);
5447 [ $self->print_ps($template) ],
5448 'agentnum' => $self->agentnum,
5452 #these three subs should just go away once agent stuff is all config overrides
5454 sub agent_template {
5456 $self->_agent_plandata('agent_templatename');
5459 sub agent_invoice_from {
5461 $self->_agent_plandata('agent_invoice_from');
5464 sub _agent_plandata {
5465 my( $self, $option ) = @_;
5467 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5468 #agent-specific Conf
5470 use FS::part_event::Condition;
5472 my $agentnum = $self->agentnum;
5474 my $regexp = regexp_sql();
5476 my $part_event_option =
5478 'select' => 'part_event_option.*',
5479 'table' => 'part_event_option',
5481 LEFT JOIN part_event USING ( eventpart )
5482 LEFT JOIN part_event_option AS peo_agentnum
5483 ON ( part_event.eventpart = peo_agentnum.eventpart
5484 AND peo_agentnum.optionname = 'agentnum'
5485 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5487 LEFT JOIN part_event_condition
5488 ON ( part_event.eventpart = part_event_condition.eventpart
5489 AND part_event_condition.conditionname = 'cust_bill_age'
5491 LEFT JOIN part_event_condition_option
5492 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5493 AND part_event_condition_option.optionname = 'age'
5496 #'hashref' => { 'optionname' => $option },
5497 #'hashref' => { 'part_event_option.optionname' => $option },
5499 " WHERE part_event_option.optionname = ". dbh->quote($option).
5500 " AND action = 'cust_bill_send_agent' ".
5501 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5502 " AND peo_agentnum.optionname = 'agentnum' ".
5503 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5505 CASE WHEN part_event_condition_option.optionname IS NULL
5507 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5509 , part_event.weight".
5513 unless ( $part_event_option ) {
5514 return $self->agent->invoice_template || ''
5515 if $option eq 'agent_templatename';
5519 $part_event_option->optionvalue;
5523 sub process_o2m_qsearch {
5526 return qsearch($table, @_) unless $table eq 'contact';
5528 my $hashref = shift;
5529 my %hash = %$hashref;
5530 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5531 or die 'guru meditation #4343';
5533 qsearch({ 'table' => 'contact',
5534 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5535 'hashref' => \%hash,
5536 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5537 " cust_contact.custnum = $custnum "
5541 sub process_o2m_qsearchs {
5544 return qsearchs($table, @_) unless $table eq 'contact';
5546 my $hashref = shift;
5547 my %hash = %$hashref;
5548 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5549 or die 'guru meditation #2121';
5551 qsearchs({ 'table' => 'contact',
5552 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5553 'hashref' => \%hash,
5554 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5555 " cust_contact.custnum = $custnum "
5559 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5561 Subroutine (not a method), designed to be called from the queue.
5563 Takes a list of options and values.
5565 Pulls up the customer record via the custnum option and calls bill_and_collect.
5570 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5572 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5573 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5575 #without this errors don't get rolled back
5576 $args{'fatal'} = 1; # runs from job queue, will be caught
5578 $cust_main->bill_and_collect( %args );
5581 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5583 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5584 C<collect> part. This is used in batch tax calculation, where invoice
5585 generation and collection events have to be completely separated.
5589 sub queued_collect {
5591 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5593 $cust_main->collect(%args);
5596 sub process_bill_and_collect {
5599 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5600 or die "custnum '$param->{custnum}' not found!\n";
5601 $param->{'job'} = $job;
5602 $param->{'fatal'} = 1; # runs from job queue, will be caught
5603 $param->{'retry'} = 1;
5605 $cust_main->bill_and_collect( %$param );
5608 #starting to take quite a while for big dbs
5609 # (JRNL: journaled so it only happens once per database)
5610 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5611 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5612 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5613 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5614 # JRNL leading/trailing spaces in first, last, company
5615 # JRNL migrate to cust_payby
5616 # - otaker upgrade? journal and call it good? (double check to make sure
5617 # we're not still setting otaker here)
5619 #only going to get worse with new location stuff...
5621 sub _upgrade_data { #class method
5622 my ($class, %opts) = @_;
5625 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5628 #this seems to be the only expensive one.. why does it take so long?
5629 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5631 'UPDATE cust_main SET signupdate = (SELECT signupdate FROM h_cust_main WHERE signupdate IS NOT NULL AND h_cust_main.custnum = cust_main.custnum ORDER BY historynum DESC LIMIT 1) WHERE signupdate IS NULL';
5632 FS::upgrade_journal->set_done('cust_main__signupdate');
5635 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5637 # fix yyyy-m-dd formatted paydates
5638 if ( driver_name =~ /^mysql/i ) {
5640 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5641 } else { # the SQL standard
5643 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5645 FS::upgrade_journal->set_done('cust_main__paydate');
5648 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5650 push @statements, #fix the weird BILL with a cc# in payinfo problem
5652 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5654 FS::upgrade_journal->set_done('cust_main__payinfo');
5659 foreach my $sql ( @statements ) {
5660 my $sth = dbh->prepare($sql) or die dbh->errstr;
5661 $sth->execute or die $sth->errstr;
5662 #warn ( (time - $t). " seconds\n" );
5666 local($ignore_expired_card) = 1;
5667 local($ignore_banned_card) = 1;
5668 local($skip_fuzzyfiles) = 1;
5669 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5671 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5673 #we don't want to decrypt them, just stuff them as-is into cust_payby
5674 local(@encrypted_fields) = ();
5676 local($FS::cust_payby::ignore_expired_card) = 1;
5677 local($FS::cust_payby::ignore_banned_card) = 1;
5678 local($FS::cust_payby::ignore_cardtype) = 1;
5680 my @payfields = qw( payby payinfo paycvv paymask
5681 paydate paystart_month paystart_year payissue
5682 payname paystate paytype payip
5685 my $search = new FS::Cursor {
5686 'table' => 'cust_main',
5687 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5690 while (my $cust_main = $search->fetch) {
5692 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
5694 my $cust_payby = new FS::cust_payby {
5695 'custnum' => $cust_main->custnum,
5697 map { $_ => $cust_main->$_(); } @payfields
5700 my $error = $cust_payby->insert;
5701 die $error if $error;
5705 # at the time we do this, also migrate paytype into cust_pay_batch
5706 # so that batches that are open before the migration can still be
5708 my @cust_pay_batch = qsearch('cust_pay_batch', {
5709 'custnum' => $cust_main->custnum,
5713 foreach my $cust_pay_batch (@cust_pay_batch) {
5714 $cust_pay_batch->set('paytype', $cust_main->get('paytype'));
5715 my $error = $cust_pay_batch->replace;
5716 die "$error (setting cust_pay_batch.paytype)" if $error;
5719 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
5721 $cust_main->invoice_attn( $cust_main->payname )
5722 if $cust_main->payby eq 'BILL' && $cust_main->payname;
5723 $cust_main->po_number( $cust_main->payinfo )
5724 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
5726 $cust_main->setfield($_, '') foreach @payfields;
5727 my $error = $cust_main->replace;
5728 die "Error upgradging payment information for custnum ".
5729 $cust_main->custnum. ": $error"
5734 FS::upgrade_journal->set_done('cust_main__cust_payby');
5737 FS::cust_main::Location->_upgrade_data(%opts);
5739 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5741 foreach my $cust_main ( qsearch({
5742 'table' => 'cust_main',
5744 'extra_sql' => 'WHERE '.
5746 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5747 qw( first last company )
5750 my $error = $cust_main->replace;
5751 die $error if $error;
5754 FS::upgrade_journal->set_done('cust_main__trimspaces');
5758 $class->_upgrade_otaker(%opts);
5768 The delete method should possibly take an FS::cust_main object reference
5769 instead of a scalar customer number.
5771 Bill and collect options should probably be passed as references instead of a
5774 There should probably be a configuration file with a list of allowed credit
5777 No multiple currency support (probably a larger project than just this module).
5779 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5781 Birthdates rely on negative epoch values.
5783 The payby for card/check batches is broken. With mixed batching, bad
5786 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5790 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5791 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5792 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.