1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
52 use FS::ClientAPI::MyAccount::quotation; # just for code organization
55 $me = '[FS::ClientAPI::MyAccount]';
57 use vars qw( @cust_main_editable_fields @location_editable_fields );
58 @cust_main_editable_fields = qw(
59 first last company daytime night fax mobile
61 payby payinfo payname paystart_month paystart_year payissue payip
62 ss paytype paystate stateid stateid_state
64 @location_editable_fields = qw(
65 address1 address2 city county state zip country
69 BEGIN { #preload to reduce time customer_info takes
70 if ( $FS::TicketSystem::system ) {
71 warn "$me: initializing ticket system\n" if $DEBUG;
72 FS::TicketSystem->init();
77 $cache ||= new FS::ClientAPI_SessionCache( {
78 'namespace' => 'FS::ClientAPI::MyAccount',
85 my($context, $session, $custnum) = _custoragent_session_custnum($p);
86 #return { 'error' => $session } if $context eq 'error';
89 if ( $context eq 'customer' && $custnum ) {
91 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
94 $sth->execute($custnum) or die $sth->errstr;
96 $agentnum = $sth->fetchrow_arrayref->[0]
97 or die "no agentnum for custnum $custnum";
99 #} elsif ( $context eq 'agent' ) {
100 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
103 $p->{'agentnum'} = $agentnum;
105 my $conf = new FS::Conf;
107 #false laziness w/Signup.pm
109 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
111 if ( $skin_info_cache_agent ) {
113 warn "$me loading cached skin info for agentnum $agentnum\n"
118 warn "$me populating skin info cache for agentnum $agentnum\n"
121 $skin_info_cache_agent = {
122 'agentnum' => $agentnum,
123 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
124 qw( company_name date_format ) ),
125 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
126 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
127 text_color link_color vlink_color hlink_color alink_color
128 font title_color title_align title_size menu_bgcolor menu_fontsize
131 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
132 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
133 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
135 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
136 qw( title_left_image title_right_image
137 menu_top_image menu_body_image menu_bottom_image
140 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
141 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
142 qw( head body_header body_footer company_address ) ),
143 'money_char' => $conf->config("money_char") || '$',
144 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
147 services.php Services
148 services.php My Services
149 services_new.php Order a new service
152 personal.php Personal Information
153 password.php Change Password
156 payment_cc.php Credit Card Payment
157 payment_ach.php Electronic Check Payment
158 payment_paypal.php PayPal Payment
159 payment_webpay.php Webpay Payments
162 usage_data.php Data usage
163 usage_cdr.php Call usage
165 tickets.php Help Desk
166 tickets.php Open Tickets
167 tickets_resolved.php Resolved Tickets
168 ticket_create.php Create a new ticket
176 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
180 #{ %$skin_info_cache_agent };
181 $skin_info_cache_agent;
188 my $conf = new FS::Conf;
192 'phone_login' => $conf->exists('selfservice_server-phone_login'),
193 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
194 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
195 'banner_image_md5' =>
196 md5_hex($conf->config_binary('selfservice-login_banner_image')),
203 sub login_banner_image {
205 my $conf = new FS::Conf;
206 my $image = $conf->config_binary('selfservice-login_banner_image');
208 'md5' => md5_hex($image),
213 #false laziness w/FS::ClientAPI::passwd::passwd
217 my $conf = new FS::Conf;
221 if ( $p->{'domain'} eq 'svc_phone'
222 && $conf->exists('selfservice_server-phone_login') ) {
224 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
225 return { error => 'Number not found.' } unless $svc_phone;
228 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
229 #return { error => 'Only primary user may log in.' }
230 # if $conf->exists('selfservice_server-primary_only')
231 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
233 return { error => 'Incorrect PIN.' }
234 unless $svc_phone->check_pin($p->{'password'});
238 } elsif ( $p->{email}
239 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
242 return { error => 'Incorrect contact password.' }
243 unless $contact->authenticate_password($p->{'password'});
245 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
246 if ( scalar(@cust_contact) == 1 ) {
247 $session->{'custnum'} = $cust_contact[0]->custnum;
248 } elsif ( scalar(@cust_contact) ) {
249 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
253 return { error => 'No customer self-service access for contact' }; #??
258 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
260 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
261 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
263 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
264 'domsvc' => $svc_domain->svcnum, }
267 if ( $conf->exists('selfservice_server-login_svcpart') ) {
268 my @svcpart = $conf->config('selfservice_server-login_svcpart');
269 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
270 scalar( grep( $_ eq $svcpart, @svcpart ) );
275 if ( $conf->exists('selfservice_server-primary_only') ) {
278 my $cust_svc = $_->cust_svc;
279 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
280 == $cust_svc->svcpart
285 return { error => 'User not found.' } unless @svc_acct;
287 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
289 my $svc_acct = $svc_acct[0];
291 if ( $conf->exists('selfservice_server-login_svcpart') ) {
292 my @svcpart = $conf->config('selfservice_server-login_svcpart');
293 my $svcpart = $svc_acct->cust_svc->svcpart;
294 return { error => 'Invalid user.' }
295 unless grep($_ eq $svcpart, @svcpart);
298 return { error => 'Incorrect password.' }
299 unless $svc_acct->check_password($p->{'password'});
307 $session->{'svcnum'} = $svc_x->svcnum;
309 my $cust_svc = $svc_x->cust_svc;
310 my $cust_pkg = $cust_svc->cust_pkg;
312 my $cust_main = $cust_pkg->cust_main;
313 $session->{'custnum'} = $cust_main->custnum;
314 if ( $conf->exists('pkg-balances') ) {
315 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
316 $cust_main->ncancelled_pkgs;
317 $session->{'pkgnum'} = $cust_pkg->pkgnum
318 if scalar(@cust_pkg) > 1;
322 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
323 #return { error => 'Only primary user may log in.' }
324 # if $conf->exists('selfservice_server-primary_only')
325 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
326 my $part_pkg = $cust_pkg->part_pkg;
327 return { error => 'Only primary user may log in.' }
328 if $conf->exists('selfservice_server-primary_only')
329 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
335 $session_id = sha512_hex(time(). {}. rand(). $$)
336 } until ( ! defined _cache->get($session_id) ); #just in case
338 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
339 _cache->set( $session_id, $session, $timeout );
341 return { 'error' => '',
342 'session_id' => $session_id,
349 my $skin_info = skin_info($p);
350 if ( $p->{'session_id'} ) {
351 _cache->remove($p->{'session_id'});
352 return { %$skin_info, 'error' => '' };
354 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
361 my($context, $session, $custnum) = _custoragent_session_custnum($p);
362 return { 'error' => $session } if $context eq 'error';
364 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
365 or return { 'error' => "Service not found" };
367 $session->{'svcnum'} = $svc_acct->svcnum;
369 my $conf = new FS::Conf;
370 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
371 _cache->set( $p->{'session_id'}, $session, $timeout );
373 return { 'error' => '' };
379 my($context, $session, $custnum) = _custoragent_session_custnum($p);
380 return { 'error' => $session } if $context eq 'error';
382 $session->{'custnum'} = $p->{'custnum'}
383 if exists $session->{'customers'}{ $p->{'custnum'} };
385 my $conf = new FS::Conf;
386 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
387 _cache->set( $p->{'session_id'}, $session, $timeout );
389 return { 'error' => '',
390 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
394 sub payment_gateway {
396 # takes a cust_main and a cust_payby entry, returns the payment_gateway
397 my $conf = new FS::Conf;
398 my $cust_main = shift;
399 my $cust_payby = shift;
400 my $gatewaynum = $conf->config('selfservice-payment_gateway');
402 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
403 die "configured gatewaynum $gatewaynum not found!" if !$pg;
407 return '' if ! FS::payby->realtime($cust_payby);
408 my $pg = $cust_main->agent->payment_gateway(
409 'method' => FS::payby->payby2bop($cust_payby),
419 my $conf = new FS::Conf;
421 my $info = skin_info($p);
423 use vars qw( $cust_paybys ); #cache for performance
424 unless ( $cust_paybys ) {
426 my %cust_paybys = map { $_ => 1 }
427 map { FS::payby->payby2payment($_) }
428 $conf->config('signup_server-payby');
430 $cust_paybys = [ keys %cust_paybys ];
433 $info->{'cust_paybys'} = $cust_paybys;
435 my($context, $session, $custnum) = _custoragent_session_custnum($p);
436 return { 'error' => $session } if $context eq 'error';
438 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
440 $info->{'hide_payment_fields'} = [
442 my $pg = $cust_main && payment_gateway($cust_main, $_);
443 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
444 } @{ $info->{cust_paybys} }
447 $info->{'self_suspend_reason'} =
448 $conf->config('selfservice-self_suspend_reason',
449 $cust_main ? $cust_main->agentnum : ''
452 $info->{'edit_ticket_subject'} =
453 $conf->exists('ticket_system-selfservice_edit_subject') &&
454 $cust_main && $cust_main->edit_subject;
456 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
458 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
461 'custnum' => $custnum,
462 'access_pkgnum' => $session->{'pkgnum'},
463 'access_svcnum' => $session->{'svcnum'},
470 my($context, $session, $custnum) = _custoragent_session_custnum($p);
471 return { 'error' => $session } if $context eq 'error';
475 my $conf = new FS::Conf;
476 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
478 # if ( $FS::TicketSystem::system ) {
479 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
480 # FS::TicketSystem->init();
483 if ( $custnum ) { #customer record
485 %return = ( %return, %{ customer_info_short($p) } );
487 #redundant with customer_info_short, but we need it for several things below
488 my $search = { 'custnum' => $custnum };
489 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
490 my $cust_main = qsearchs('cust_main', $search )
491 or return { 'error' => "customer_info: unknown custnum $custnum" };
493 my $list_tickets = list_tickets($p);
494 $return{'tickets'} = $list_tickets->{'tickets'};
496 if ( $session->{'pkgnum'} ) {
497 #XXX open invoices in the pkg-balances case
499 $return{'money_char'} = $conf->config("money_char") || '$';
502 invnum => $_->invnum,
503 date => time2str("%b %o, %Y", $_->_date),
505 charged => $_->charged,
507 } $cust_main->open_cust_bill;
508 $return{open_invoices} = \@open;
510 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
511 my $sth = dbh->prepare($sql) or die dbh->errstr;
512 $sth->execute($custnum) or die $sth->errstr;
513 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
514 $return{'last_invoice_date_pretty'} =
515 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
518 #customer_info_short always has nobalance on..
519 $return{small_custview} =
520 small_custview( $cust_main,
521 $return{countrydefault},
522 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
525 $return{has_ship_address} = $cust_main->has_ship_address;
526 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
527 $return{statuscolor} = $cust_main->statuscolor;
528 $return{status_label} = $cust_main->status_label;
530 # compatibility: some places in selfservice use this to determine
531 # if there's a ship address
532 if ( $return{has_ship_address} ) {
533 $return{ship_last} = $cust_main->last;
534 $return{ship_first} = $cust_main->first;
537 if (scalar($conf->config('support_packages'))) {
538 my @support_services = ();
539 foreach ($cust_main->support_services) {
540 my $seconds = $_->svc_x->seconds || 0;
541 my $time_remaining = (($seconds < 0) ? '-' : '' ).
542 int(abs($seconds)/3600)."h".
543 sprintf("%02d",(abs($seconds)%3600)/60)."m";
544 my $cust_pkg = $_->cust_pkg;
547 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
548 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
549 push @support_services, { svcnum => $_->svcnum,
550 time => $time_remaining,
555 $return{support_services} = \@support_services;
558 if ( $conf->config('prepayment_discounts-credit_type') ) {
560 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
563 } elsif ( $session->{'svcnum'} ) { #no customer record
565 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
566 or die "unknown svcnum";
567 $return{name} = $svc_acct->email;
571 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
575 return { 'error' => '',
576 'custnum' => $custnum,
582 sub customer_info_short {
585 my($context, $session, $custnum) = _custoragent_session_custnum($p);
586 return { 'error' => $session } if $context eq 'error';
590 my $conf = new FS::Conf;
592 if ( $custnum ) { #customer record
594 my $search = { 'custnum' => $custnum };
595 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
596 my $cust_main = qsearchs('cust_main', $search )
597 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
599 $return{display_custnum} = $cust_main->display_custnum;
601 if ( $session->{'pkgnum'} ) {
602 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
603 #next_bill_date from cust_pkg?
605 $return{balance} = $cust_main->balance;
606 $return{next_bill_date} = $cust_main->next_bill_date;
607 $return{next_bill_date_pretty} =
608 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
612 $return{countrydefault} = scalar($conf->config('countrydefault'));
614 $return{small_custview} =
615 small_custview( $cust_main,
616 $return{countrydefault},
620 $return{first} = $cust_main->first;
621 $return{'last'} = $cust_main->get('last');
622 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
624 $return{payby} = $cust_main->payby;
626 #none of these are terribly expensive if we want 'em...
627 for (@cust_main_editable_fields) {
628 $return{$_} = $cust_main->get($_);
630 #maybe a little more expensive, but it should be cached by now
631 for (@location_editable_fields) {
632 $return{$_} = $cust_main->bill_location->get($_)
633 if $cust_main->bill_locationnum;
634 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
635 if $cust_main->ship_locationnum;
638 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
639 $return{payinfo} = $cust_main->paymask;
640 @return{'month', 'year'} = $cust_main->paydate_monthyear;
643 my @invoicing_list = $cust_main->invoicing_list;
644 $return{'invoicing_list'} =
645 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
646 $return{'postal_invoicing'} =
647 0 < ( grep { $_ eq 'POST' } @invoicing_list );
649 if ( $session->{'svcnum'} ) {
650 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
651 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
652 $return{'svcnum'} = $session->{'svcnum'};
655 } elsif ( $session->{'svcnum'} ) { #no customer record
657 #uuh, not supproted yet... die?
658 return { 'error' => 'customer_info_short not yet supported as agent' };
662 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
666 return { 'error' => '',
667 'custnum' => $custnum,
672 sub billing_history {
675 my($context, $session, $custnum) = _custoragent_session_custnum($p);
676 return { 'error' => $session } if $context eq 'error';
678 return { 'error' => 'No customer' } unless $custnum;
680 my $search = { 'custnum' => $custnum };
681 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
682 my $cust_main = qsearchs('cust_main', $search )
683 or return { 'error' => "unknown custnum $custnum" };
687 if ( $session->{'pkgnum'} ) {
688 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
689 #next_bill_date from cust_pkg?
690 return { 'error' => 'No history for package' };
693 $return{balance} = $cust_main->balance;
694 $return{next_bill_date} = $cust_main->next_bill_date;
695 $return{next_bill_date_pretty} =
696 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
701 my $conf = new FS::Conf;
703 if ( $conf->exists('selfservice-billing_history-line_items') ) {
705 foreach my $cust_bill ( $cust_main->cust_bill ) {
708 'type' => 'Line item',
709 'description' => $_->desc( $cust_main->locale ).
710 ( $_->sdate && $_->edate
711 ? ' '. time2str('%d-%b-%Y', $_->sdate).
712 ' To '. time2str('%d-%b-%Y', $_->edate)
715 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
716 'date' => $cust_bill->_date,
717 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
719 foreach $cust_bill->cust_bill_pkg;
727 'description' => 'Invoice #'. $_->display_invnum,
728 'amount' => sprintf('%.2f', $_->charged ),
730 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
732 foreach $cust_main->cust_bill;
738 'description' => 'Payment', #XXX type
739 'amount' => sprintf('%.2f', 0 - $_->paid ),
741 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
743 foreach $cust_main->cust_pay;
747 'description' => 'Credit', #more info?
748 'amount' => sprintf('%.2f', 0 -$_->amount ),
750 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
752 foreach $cust_main->cust_credit;
756 'description' => 'Refund', #more info? type, like payment?
757 'amount' => $_->refund,
759 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
761 foreach $cust_main->cust_refund;
763 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
765 $return{'history'} = \@history;
773 my $session = _cache->get($p->{'session_id'})
774 or return { 'error' => "Can't resume session" }; #better error message
776 my $custnum = $session->{'custnum'}
777 or return { 'error' => "no customer record" };
779 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
780 or return { 'error' => "unknown custnum $custnum" };
782 my $new = new FS::cust_main { $cust_main->hash };
784 $new->set( $_ => $p->{$_} )
785 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
787 if ( exists($p->{address1}) ) {
788 my $bill_location = FS::cust_location->new({
789 map { $_ => $p->{$_} } @location_editable_fields
791 # if this is unchanged from before, cust_main::replace will ignore it
792 $new->set('bill_location' => $bill_location);
795 if ( exists($p->{ship_address1}) ) {
796 my $ship_location = FS::cust_location->new({
797 map { $_ => $p->{"ship_$_"} } @location_editable_fields
799 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
800 # Selfservice unfortunately tries to indicate "same as billing
801 # address" by sending all fields empty. Did this ever work?
802 $ship_location = $cust_main->bill_location;
804 $new->set('ship_location' => $ship_location);
806 # but if it hasn't been passed in at all, leave ship_location alone--
807 # DON'T change it to match bill_location.
810 if (exists($p->{'payby'})) {
811 $p->{'payby'} =~ /^([A-Z]{4})$/
812 or return { 'error' => "illegal_payby " . $p->{'payby'} };
816 my $conf = new FS::Conf;
818 if ( $payby =~ /^(CARD|DCRD)$/ ) {
820 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
822 if ( $new->payinfo eq $cust_main->paymask ) {
823 $new->payinfo($cust_main->payinfo);
824 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
826 $new->payinfo($p->{'payinfo'});
827 return { 'error' => 'CVV2 is required' }
828 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
829 $new->paycvv( $p->{'paycvv'} )
832 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
834 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
837 $p->{'payinfo1'} =~ /^([\dx]+)$/
838 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
840 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
841 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
843 $payinfo = $payinfo1. '@'. $payinfo2;
845 $new->payinfo( ($payinfo eq $cust_main->paymask)
846 ? $cust_main->payinfo
850 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
852 } elsif ( $payby =~ /^(BILL)$/ ) {
854 } elsif ( $payby ) { #notyet ready
855 return { 'error' => "unknown payby $payby" };
859 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
860 #false laziness with httemplate/edit/process/cust_main.cgi
861 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
862 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
864 @invoicing_list = $cust_main->invoicing_list;
867 my $error = $new->replace($cust_main, \@invoicing_list);
868 return { 'error' => $error } if $error;
871 return { 'error' => '' };
876 my $session = _cache->get($p->{'session_id'})
877 or return { 'error' => "Can't resume session" }; #better error message
883 my $conf = new FS::Conf;
884 use vars qw($payment_info); #cache for performance
885 unless ( $payment_info ) {
887 my %states = map { $_->state => 1 }
888 qsearch('cust_main_county', {
889 'country' => $conf->config('countrydefault') || 'US'
892 my %cust_paybys = map { $_ => 1 }
893 map { FS::payby->payby2payment($_) }
894 $conf->config('signup_server-payby');
896 my @cust_paybys = keys %cust_paybys;
900 #list all counties/states/countries
901 'cust_main_county' =>
902 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
904 #shortcut for one-country folks
906 [ sort { $a cmp $b } keys %states ],
908 'card_types' => card_types(),
910 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
911 'require_cvv' => $conf->exists('selfservice-require_cvv'),
912 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
914 'paytypes' => [ @FS::cust_main::paytypes ],
916 'paybys' => [ $conf->config('signup_server-payby') ],
917 'cust_paybys' => \@cust_paybys,
919 'stateid_label' => FS::Msgcat::_gettext('stateid'),
920 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
922 'show_ss' => $conf->exists('show_ss'),
923 'show_stateid' => $conf->exists('show_stateid'),
924 'show_paystate' => $conf->exists('show_bankstate'),
926 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
928 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
937 my %return = %$payment_info;
939 my $custnum = $session->{'custnum'};
941 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
942 or return { 'error' => "unknown custnum $custnum" };
944 $return{'hide_payment_fields'} = [
946 my $pg = payment_gateway($cust_main, $_);
947 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
948 } @{ $return{cust_paybys} }
951 $return{balance} = $cust_main->balance; #XXX pkg-balances?
953 $return{payname} = $cust_main->payname
954 || ( $cust_main->first. ' '. $cust_main->get('last') );
956 $return{$_} = $cust_main->bill_location->get($_)
957 for qw(address1 address2 city state zip);
959 $return{payby} = $cust_main->payby;
960 $return{stateid_state} = $cust_main->stateid_state;
962 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
963 $return{card_type} = cardtype($cust_main->payinfo);
964 $return{payinfo} = $cust_main->paymask;
966 @return{'month', 'year'} = $cust_main->paydate_monthyear;
970 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
971 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
972 $return{payinfo1} = $payinfo1;
973 $return{payinfo2} = $payinfo2;
974 $return{paytype} = $cust_main->paytype;
975 $return{paystate} = $cust_main->paystate;
976 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
979 if ( $conf->config('prepayment_discounts-credit_type') ) {
981 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
984 #doubleclick protection
986 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
987 $return{paybatch} = $return{payunique}; #back compat
989 return { 'error' => '',
995 #some false laziness with httemplate/process/payment.cgi - look there for
996 #ACH and CVV support stuff
998 sub validate_payment {
1001 my $session = _cache->get($p->{'session_id'})
1002 or return { 'error' => "Can't resume session" }; #better error message
1004 my $custnum = $session->{'custnum'};
1006 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1007 or return { 'error' => "unknown custnum $custnum" };
1009 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
1010 or return { 'error' => gettext('illegal_amount') };
1012 return { error => 'Amount must be greater than 0' } unless $amount > 0;
1014 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
1015 #changing the hidden form values
1016 my $conf = new FS::Conf;
1017 my $fee_display = $conf->config('selfservice_process-display') || 'add';
1018 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1019 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1020 if ( $fee_display eq 'add'
1022 and ! $fee_skip_first || scalar($cust_main->cust_pay)
1025 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
1026 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
1029 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
1030 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
1031 my $discount_term = $1;
1033 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1034 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1037 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1038 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1041 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1042 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1045 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1047 $p->{'payby'} ||= 'CARD';
1048 $p->{'payby'} =~ /^([A-Z]{4})$/
1049 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1052 #false laziness w/process/payment.cgi
1055 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1057 $p->{'payinfo1'} =~ /^([\dx]+)$/
1058 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1060 $p->{'payinfo2'} =~ /^([\dx]+)$/
1061 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1063 $payinfo = $payinfo1. '@'. $payinfo2;
1065 $payinfo = $cust_main->payinfo
1066 if $cust_main->paymask eq $payinfo;
1068 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1070 $payinfo = $p->{'payinfo'};
1074 #more intelligent matching will be needed here if you change
1075 #card_masking_method and don't remove existing paymasks
1076 if ( $cust_main->paymask eq $payinfo ) {
1077 $payinfo = $cust_main->payinfo;
1081 $payinfo =~ s/\D//g;
1082 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1083 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1087 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1088 return { 'error' => gettext('unknown_card_type') }
1089 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1091 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1092 if ( cardtype($payinfo) eq 'American Express card' ) {
1093 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1094 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1097 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1098 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1101 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1102 return { 'error' => 'CVV2 is required' };
1103 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1104 return { 'error' => 'CVV2 is required' };
1108 die "unknown payby $payby";
1111 my %payby2fields = (
1112 'CARD' => [ qw( paystart_month paystart_year payissue payip
1113 address1 address2 city state zip country ) ],
1114 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1118 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1121 'cust_main' => $cust_main, #XXX or just custnum??
1122 'amount' => sprintf('%.2f', $amount),
1124 'payinfo' => $payinfo,
1125 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1126 'card_type' => $card_type,
1127 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1128 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1129 'month' => $p->{'month'},
1130 'year' => $p->{'year'},
1131 'payname' => $payname,
1132 'payunique' => $payunique,
1133 'paybatch' => $paybatch,
1134 'paycvv' => $paycvv,
1135 'payname' => $payname,
1136 'discount_term' => $discount_term,
1137 'pkgnum' => $session->{'pkgnum'},
1138 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1148 my $validate = validate_payment($p);
1149 return $validate if $validate->{'error'};
1151 my $conf = new FS::Conf;
1152 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1153 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1155 +{ map { $_=>$validate->{$_} }
1156 qw( card_type paymask payname paydate_pretty month year amount
1157 address1 address2 city state zip country
1163 sub process_stored_payment {
1166 my $session_id = $p->{'session_id'};
1168 my $payment_info = _cache->get( "payment_$session_id" )
1169 or return { 'error' => "Can't resume session" }; #better error message
1171 do_process_payment($payment_info);
1175 sub process_payment {
1178 my $payment_info = validate_payment($p);
1179 return $payment_info if $payment_info->{'error'};
1181 do_process_payment($payment_info);
1185 sub do_process_payment {
1186 my $validate = shift;
1188 my $cust_main = $validate->{'cust_main'};
1190 my $amount = delete $validate->{'amount'};
1193 my $payby = delete $validate->{'payby'};
1195 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1199 'paynum_ref' => \$paynum,
1202 return { 'error' => $error } if $error;
1204 #no error, so order the fee package if applicable...
1205 my $conf = new FS::Conf;
1206 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1207 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1209 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1211 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1213 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1214 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1217 #and generate an invoice for it now too
1218 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1219 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1224 $cust_main->apply_payments;
1226 if ( $validate->{'save'} ) {
1227 my $new = new FS::cust_main { $cust_main->hash };
1228 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1229 $new->set( $_ => $validate->{$_} )
1230 foreach qw( payname paystart_month paystart_year payissue payip );
1231 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1233 my $bill_location = FS::cust_location->new({
1234 map { $_ => $validate->{$_} }
1235 qw(address1 address2 city state country zip)
1237 $new->set('bill_location' => $bill_location);
1238 # but don't allow the service address to change this way.
1240 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1241 $new->set( $_ => $validate->{$_} )
1242 foreach qw( payname payip paytype paystate
1243 stateid stateid_state );
1244 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1246 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1247 $new->set( 'paydate' => $validate->{'paydate'} );
1248 my $error = $new->replace($cust_main);
1250 #no, this causes customers to process their payments again
1251 #return { 'error' => $error };
1252 #XXX just warn verosely for now so i can figure out how these happen in
1253 # the first place, eventually should redirect them to the "change
1254 #address" page but indicate the payment did process??
1255 delete($validate->{'payinfo'}); #don't want to log this!
1256 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1257 "NEW: ". Dumper($new)."\n".
1258 "OLD: ". Dumper($cust_main)."\n".
1259 "PACKET: ". Dumper($validate)."\n";
1267 my $receipt_html = '';
1269 # currently supported for realtime CC only; send receipt data to SS
1270 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1273 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1276 <TD ALIGN="right">Payment#</TD>
1277 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1281 <TD ALIGN="right">Date</TD>
1283 <TD BGCOLOR="#FFFFFF"><B>! .
1284 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1290 <TD ALIGN="right">Amount</TD>
1291 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1296 <TD ALIGN="right">Payment method</TD>
1297 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1310 'amount' => sprintf('%.2f', $cust_pay->paid),
1311 'date' => $cust_pay->_date,
1312 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1313 'time_pretty' => time2str('%T', $cust_pay->_date),
1314 'auth_num' => $cust_pay->auth,
1315 'order_num' => $cust_pay->order_number,
1316 'receipt_html' => $receipt_html,
1323 'receipt_html' => '',
1330 sub realtime_collect {
1333 my $session = _cache->get($p->{'session_id'})
1334 or return { 'error' => "Can't resume session" }; #better error message
1336 my $custnum = $session->{'custnum'};
1338 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1339 or return { 'error' => "unknown custnum $custnum" };
1342 if ( $p->{'amount'} ) {
1343 $amount = $p->{'amount'};
1345 elsif ( $session->{'pkgnum'} ) {
1346 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1349 $amount = $cust_main->balance;
1352 my $error = $cust_main->realtime_collect(
1353 'method' => $p->{'method'},
1354 'amount' => $amount,
1355 'pkgnum' => $session->{'pkgnum'},
1356 'session_id' => $p->{'session_id'},
1360 return { 'error' => $error } unless ref( $error );
1362 return { 'error' => '', amount => $amount, %$error };
1365 sub start_thirdparty {
1367 my $session = _cache->get($p->{'session_id'})
1368 or return { 'error' => "Can't resume session" }; #better error message
1369 my $custnum = $session->{'custnum'};
1370 my $cust_main = FS::cust_main->by_key($custnum);
1372 my $amount = $p->{'amount'}
1373 or return { error => 'no amount' };
1375 my $result = $cust_main->create_payment(
1376 'method' => $p->{'method'},
1377 'amount' => $p->{'amount'},
1378 'pkgnum' => $session->{'pkgnum'},
1379 'session_id' => $p->{'session_id'},
1382 if ( ref($result) ) { # hashref or error
1385 return { error => $result };
1389 sub finish_thirdparty {
1391 my $session_id = delete $p->{'session_id'};
1392 my $session = _cache->get($session_id)
1393 or return { 'error' => "Can't resume session" };
1394 my $custnum = $session->{'custnum'};
1395 my $cust_main = FS::cust_main->by_key($custnum);
1397 if ( $p->{_cancel} ) {
1398 # customer backed out of making a payment
1399 return $cust_main->cancel_payment( $session_id );
1401 my $result = $cust_main->execute_payment( $session_id, %$p );
1402 if ( ref($result) ) {
1405 return { error => $result };
1409 sub process_payment_order_pkg {
1412 my $hr = process_payment($p);
1413 return $hr if $hr->{'error'};
1418 sub process_payment_order_renew {
1421 my $hr = process_payment($p);
1422 return $hr if $hr->{'error'};
1427 sub process_prepay {
1431 my $session = _cache->get($p->{'session_id'})
1432 or return { 'error' => "Can't resume session" }; #better error message
1436 my $custnum = $session->{'custnum'};
1438 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1439 or return { 'error' => "unknown custnum $custnum" };
1441 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1442 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1450 return { 'error' => $error } if $error;
1452 return { 'error' => '',
1453 'amount' => $amount,
1454 'seconds' => $seconds,
1455 'duration' => duration_exact($seconds),
1456 'upbytes' => $upbytes,
1457 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1458 'downbytes' => $downbytes,
1459 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1460 'totalbytes'=> $totalbytes,
1461 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1468 my $session = _cache->get($p->{'session_id'})
1469 or return { 'error' => "Can't resume session" }; #better error message
1471 my $custnum = $session->{'custnum'};
1473 my $invnum = $p->{'invnum'};
1475 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1476 'custnum' => $custnum } )
1477 or return { 'error' => "Can't find invnum" };
1481 return { 'error' => '',
1482 'invnum' => $invnum,
1483 'invoice_text' => join('', $cust_bill->print_text ),
1484 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1491 my $session = _cache->get($p->{'session_id'})
1492 or return { 'error' => "Can't resume session" }; #better error message
1494 my $custnum = $session->{'custnum'};
1496 my $invnum = $p->{'invnum'};
1498 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1499 'custnum' => $custnum } )
1500 or return { 'error' => "Can't find invnum" };
1504 return { 'error' => '',
1505 'invnum' => $invnum,
1506 'invoice_pdf' => $cust_bill->print_pdf({
1507 'unsquelch_cdr' => 1,
1508 'locale' => $p->{'locale'},
1514 sub legacy_invoice {
1516 my $session = _cache->get($p->{'session_id'})
1517 or return { 'error' => "Can't resume session" }; #better error message
1519 my $custnum = $session->{'custnum'};
1521 my $legacyinvnum = $p->{'legacyinvnum'};
1524 'legacyinvnum' => $legacyinvnum,
1525 'custnum' => $custnum,
1528 my $legacy_cust_bill =
1529 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1530 || qsearchs('legacy_cust_bill', \%hash )
1531 or return { 'error' => "Can't find legacyinvnum" };
1535 return { 'error' => '',
1536 'legacyinvnum' => $legacyinvnum,
1537 'legacyid' => $legacy_cust_bill->legacyid,
1538 'invoice_html' => $legacy_cust_bill->content_html,
1543 sub legacy_invoice_pdf {
1545 my $session = _cache->get($p->{'session_id'})
1546 or return { 'error' => "Can't resume session" }; #better error message
1548 my $custnum = $session->{'custnum'};
1550 my $legacyinvnum = $p->{'legacyinvnum'};
1552 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1553 'legacyinvnum' => $legacyinvnum,
1554 'custnum' => $custnum,
1555 }) or return { 'error' => "Can't find legacyinvnum" };
1559 return { 'error' => '',
1560 'legacyinvnum' => $legacyinvnum,
1561 'legacyid' => $legacy_cust_bill->legacyid,
1562 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1570 #sessioning for this? how do we get the session id to the backend invoice
1571 # template so it can add it to the link, blah
1574 if ( $p->{'invnum'} ) {
1575 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1576 or return { 'error' => 'unknown invnum' };
1577 $agentnum = $cust_bill->cust_main->agentnum;
1580 my $templatename = $p->{'template'} || $p->{'templatename'};
1582 #false laziness-ish w/view/cust_bill-logo.cgi
1584 my $conf = new FS::Conf;
1585 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1586 $templatename = "_$1";
1591 my $filename = "logo$templatename.png";
1593 return { 'error' => '',
1594 'logo' => $conf->config_binary($filename, $agentnum),
1595 'content_type' => 'image/png', #should allow gif, jpg too
1602 my $session = _cache->get($p->{'session_id'})
1603 or return { 'error' => "Can't resume session" }; #better error message
1605 my $custnum = $session->{'custnum'};
1607 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1608 or return { 'error' => "unknown custnum $custnum" };
1610 my $conf = new FS::Conf;
1612 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1614 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1619 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1620 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1621 my $owed = $_->owed;
1623 +{ 'invnum' => $_->invnum,
1624 '_date' => $_->_date,
1625 'date' => time2str("%b %o, %Y", $_->_date),
1626 'date_short' => time2str("%m-%d-%Y", $_->_date),
1627 'previous' => sprintf('%.2f', ($_->previous)[0]),
1628 'charged' => sprintf('%.2f', $_->charged),
1629 'owed' => sprintf('%.2f', $owed),
1630 'balance' => sprintf('%.2f', $balance),
1631 'lastpay' => @payments_and_credits
1632 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1638 return { 'error' => '',
1639 'balance' => $cust_main->balance,
1640 'money_char' => $conf->config("money_char") || '$',
1641 'invoices' => $invoices,
1642 'legacy_invoices' => [
1644 +{ 'legacyinvnum' => $_->legacyinvnum,
1645 'legacyid' => $_->legacyid,
1646 '_date' => $_->_date,
1647 'date' => time2str("%b %o, %Y", $_->_date),
1648 'date_short' => time2str("%m-%d-%Y", $_->_date),
1649 'charged' => sprintf('%.2f', $_->charged),
1650 'has_content' => ( length($_->content_pdf)
1651 || length($_->content_html) ),
1661 my $session = _cache->get($p->{'session_id'})
1662 or return { 'error' => "Can't resume session" }; #better error message
1664 my $custnum = $session->{'custnum'};
1666 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1667 or return { 'error' => "unknown custnum $custnum" };
1669 my @errors = $cust_main->cancel( 'quiet'=>1 );
1671 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1673 return { 'error' => $error };
1680 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1681 return { 'error' => $session } if $context eq 'error';
1683 my $search = { 'custnum' => $custnum };
1684 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1685 my $cust_main = qsearchs('cust_main', $search )
1686 or return { 'error' => "unknown custnum $custnum" };
1688 my $conf = new FS::Conf;
1689 my $immutable = $conf->exists('selfservice_immutable-package');
1691 # the duplication below is necessary:
1692 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1693 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1694 # non-backwards-compatible change breaking the software of anyone using the API
1695 # instead of the stock selfservice
1696 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1697 if( $conf->exists('selfservice_server-view-wholesale') ) {
1698 return { 'svcnum' => $session->{'svcnum'},
1699 'custnum' => $custnum,
1700 'cust_pkg' => [ map {
1702 immutable => $immutable,
1703 part_pkg => [ map $_->hashref, $_->part_pkg ],
1705 [ map $_->hashref, $_->available_part_svc ],
1707 [ map { my $ref = { $_->hash,
1708 label => [ $_->label ],
1710 $ref->{_password} = $_->svc_x->_password
1711 if $context eq 'agent'
1712 && $conf->exists('agent-showpasswords')
1713 && $_->part_svc->svcdb eq 'svc_acct';
1718 } $cust_main->cust_pkg
1721 small_custview( $cust_main, $conf->config('countrydefault') ),
1722 'wholesale_view' => 1,
1723 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1724 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1725 'lnp' => $conf->exists('svc_phone-lnp'),
1729 { 'svcnum' => $session->{'svcnum'},
1730 'custnum' => $custnum,
1731 'cust_pkg' => [ map {
1732 my $primary_cust_svc = $_->primary_cust_svc;
1735 immutable => $immutable,
1736 pkg_label => $_->pkg_locale,
1737 status => $_->status,
1738 statuscolor => $_->statuscolor,
1740 [ map { $_->hashref }
1741 grep { $_->selfservice_access ne 'hidden' }
1742 $_->available_part_svc
1745 [ map { my $ref = { $_->hash,
1746 label => [ $_->label ],
1748 $ref->{_password} = $_->svc_x->_password
1749 if $context eq 'agent'
1750 && $conf->exists('agent-showpasswords')
1751 && $_->part_svc->svcdb eq 'svc_acct';
1752 $ref->{svchash} = { $_->svc_x->hash } if
1753 $_->part_svc->svcdb eq 'svc_phone';
1754 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1755 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1758 grep { $_->part_svc->selfservice_access ne 'hidden' }
1763 ? { $primary_cust_svc->hash,
1764 label => [ $primary_cust_svc->label ],
1765 finger => $primary_cust_svc->svc_x->finger, #uuh
1766 $primary_cust_svc->part_svc->hash,
1770 } $cust_main->ncancelled_pkgs
1773 small_custview( $cust_main, $conf->config('countrydefault') ),
1774 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1782 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1783 return { 'error' => $session } if $context eq 'error';
1785 my $conf = new FS::Conf;
1787 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1788 my $search = { 'custnum' => $custnum };
1789 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1790 my $cust_main = qsearchs('cust_main', $search )
1791 or return { 'error' => "unknown custnum $custnum" };
1793 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1794 if ( ! $pkgnum && $p->{'svcnum'} ) {
1795 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1796 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1800 my @cust_pkg_usage = ();
1801 foreach my $cust_pkg ( $p->{'ncancelled'}
1802 ? $cust_main->ncancelled_pkgs
1803 : $cust_main->unsuspended_pkgs ) {
1804 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1805 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1806 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1809 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1812 foreach (@cust_pkg_usage) {
1813 my $part = $_->part_pkg_usage;
1814 my $tag = $part->description . ($part->shared ? 1 : 0);
1815 my $row = $usage_pools{$tag}
1816 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1817 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1818 $row->[2] += $part->minutes; # minutes total
1820 } # otherwise just leave them empty
1822 if ( $p->{'svcdb'} ) {
1823 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1825 : ref($p->{'svcdb'}) eq 'ARRAY'
1826 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1827 : { $p->{'svcdb'} => 1 };
1828 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1831 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1834 my @svcs; # stuff to return to the client
1835 foreach my $cust_svc (@cust_svc) {
1836 my $svc_x = $cust_svc->svc_x;
1837 my($label, $value) = $cust_svc->label;
1838 my $part_svc = $cust_svc->part_svc;
1839 my $svcdb = $part_svc->svcdb;
1840 my $cust_pkg = $cust_svc->cust_pkg;
1841 my $part_pkg = $cust_pkg->part_pkg;
1844 'svcnum' => $cust_svc->svcnum,
1845 'display_svcnum' => $cust_svc->display_svcnum,
1849 'pkg_label' => $cust_pkg->pkg_locale,
1850 'pkg_status' => $cust_pkg->status,
1851 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1854 # would it make sense to put this in a svc_* method?
1856 if ( $svcdb eq 'svc_acct' ) {
1857 foreach (qw(username email finger seconds)) {
1858 $hash{$_} = $svc_x->$_;
1864 'upbytes' => display_bytecount($svc_x->upbytes),
1865 'downbytes' => display_bytecount($svc_x->downbytes),
1866 'totalbytes' => display_bytecount($svc_x->totalbytes),
1868 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1869 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1870 'recharge_upbytes' =>
1871 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1872 'recharge_downbytes' =>
1873 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1874 'recharge_totalbytes' =>
1875 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1880 } elsif ( $svcdb eq 'svc_dsl' ) {
1882 $hash{'phonenum'} = $svc_x->phonenum;
1883 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1884 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1885 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1888 $hash{'name'} = $cust_main->name;
1890 # no usage to hide here
1892 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1894 # could potentially show lots of things...
1895 $hash{'outbound'} = 1;
1896 $hash{'inbound'} = 0;
1897 if ( $svcdb eq 'svc_phone' ) {
1898 if ( $part_pkg->plan eq 'voip_inbound' ) {
1899 $hash{'outbound'} = 0;
1900 $hash{'inbound'} = 1;
1901 } elsif ( $part_pkg->option('selfservice_inbound_format')
1902 or $conf->config('selfservice-default_inbound_cdr_format')
1904 $hash{'inbound'} = 1;
1907 foreach (qw(inbound outbound)) {
1908 # hmm...we can't filter by status here, because there might
1909 # not be cdr_terminations at all. have to go by date.
1910 # find all since the last bill date.
1911 # XXX cdr types? we are going to need them.
1913 my $sum_cdr = $svc_x->sum_cdrs(
1914 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1915 'begin' => ($cust_pkg->last_bill || 0),
1917 'disable_charged_party' => 1,
1919 $hash{$_} = $sum_cdr->hashref;
1922 } # not hiding usage
1926 } # foreach $cust_svc
1929 'svcnum' => $session->{'svcnum'},
1930 'custnum' => $custnum,
1931 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1932 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1935 map { $usage_pools{$_} }
1939 'hide_usage' => $hide_usage,
1944 sub _customer_svc_x {
1945 my($custnum, $svcnum, $table) = (shift, shift, shift);
1946 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1948 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1949 my $search = " AND custnum = $1";
1950 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1953 'table' => ($table || 'svc_acct'),
1954 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1955 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1956 #'LEFT JOIN cust_main USING ( custnum ) ',
1957 'hashref' => $hashref,
1958 'extra_sql' => $search, #important
1963 sub svc_status_html {
1966 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1967 return { 'error' => $session } if $context eq 'error';
1969 #XXX only svc_dsl for now
1970 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1971 or return { 'error' => "Service not found" };
1973 my $html = $svc_x->getstatus_html;
1975 return { 'html' => $html };
1979 sub svc_status_hash {
1982 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1983 return { 'error' => $session } if $context eq 'error';
1985 #XXX only svc_acct for now
1986 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1987 or return { 'error' => "Service not found" };
1989 my ( $html, $hashref ) = $svc_x->export_getstatus;
1994 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1995 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1996 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1997 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1998 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2001 my( $p, $method ) = @_;
2003 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2004 return { 'error' => $session } if $context eq 'error';
2006 #XXX only svc_acct for now
2007 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2008 or return { 'error' => "Service not found" };
2010 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2012 my $error = $svc_x->$method($p); #$p? returns error?
2013 return { 'error' => $error } if $error;
2015 return {}; #? { 'error' => '' }
2019 sub acct_forward_info {
2022 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2023 return { 'error' => $session } if $context eq 'error';
2025 my $svc_forward = _customer_svc_x( $custnum,
2026 { 'srcsvc' => $p->{'svcnum'} },
2029 or return { 'error' => '',
2033 return { 'error' => '',
2034 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2039 sub process_acct_forward {
2041 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2042 return { 'error' => $session } if $context eq 'error';
2044 my $old = _customer_svc_x( $custnum,
2045 { 'srcsvc' => $p->{'svcnum'} },
2049 if ( $p->{'dst'} eq '' ) {
2051 my $error = $old->delete;
2052 return { 'error' => $error };
2054 return { 'error' => '' };
2057 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2058 'dst' => $p->{'dst'},
2063 $new->svcnum($old->svcnum);
2064 my $cust_svc = $old->cust_svc;
2065 $new->svcpart($old->svcpart);
2066 $new->pkgnuym($old->pkgnum);
2067 $error = $new->replace($old);
2069 my $conf = new FS::Conf;
2070 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2072 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2073 or return { 'error' => 'No service' }; #how would we even get here?
2075 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2077 $error = $new->insert;
2080 return { 'error' => $error };
2084 sub list_dsl_devices {
2087 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2088 return { 'error' => $session } if $context eq 'error';
2090 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2091 or return { 'error' => "Service not found" };
2094 'devices' => [ map {
2095 +{ 'mac_addr' => $_->mac_addr };
2096 } $svc_dsl->dsl_device
2102 sub add_dsl_device {
2105 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2106 return { 'error' => $session } if $context eq 'error';
2108 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2109 or return { 'error' => "Service not found" };
2111 return { 'error' => 'No MAC address supplied' }
2112 unless length($p->{'mac_addr'});
2114 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2115 'mac_addr' => scalar($p->{'mac_addr'}),
2117 my $error = $dsl_device->insert;
2118 return { 'error' => $error };
2122 sub delete_dsl_device {
2125 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2126 return { 'error' => $session } if $context eq 'error';
2128 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2129 or return { 'error' => "Service not found" };
2131 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2132 'mac_addr' => scalar($p->{'mac_addr'}),
2135 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2137 my $error = $dsl_device->delete;
2138 return { 'error' => $error };
2144 _usage_details( \&_port_graph, $p,
2145 'svcdb' => 'svc_port',
2150 my($svc_port, $begin, $end) = @_;
2152 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2153 push @usage, { 'png' => $pngOrError };
2157 sub _list_svc_usage {
2158 my($svc_acct, $begin, $end) = @_;
2160 foreach my $part_export (
2161 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2162 qw( sqlradius sqlradius_withdomain )
2164 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2169 sub list_svc_usage {
2170 _usage_details(\&_list_svc_usage, @_);
2173 sub _list_support_usage {
2174 my($svc_acct, $begin, $end) = @_;
2176 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2177 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2179 push @usage, { 'seconds' => $_->seconds,
2180 'support' => $_->support,
2181 '_date' => $_->_date,
2182 'id' => $_->transaction_id,
2183 'creator' => $_->creator,
2184 'subject' => $_->subject,
2185 'status' => $_->status,
2186 'ticketid' => $_->ticketid,
2192 sub list_support_usage {
2193 _usage_details(\&_list_support_usage, @_);
2196 sub _list_cdr_usage {
2197 # XXX CDR type support...
2198 # XXX any way to do a paged search on this?
2199 # we have to return the results all at once...
2200 my($svc_x, $begin, $end, %opt) = @_;
2201 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2205 'disable_charged_party' => 1,
2210 sub list_cdr_usage {
2212 _usage_details( \&_list_cdr_usage, $p );
2215 sub _usage_details {
2216 my($callback, $p, %opt) = @_;
2217 my $conf = FS::Conf->new;
2219 if ( $conf->exists('selfservice_hide-usage') ) {
2220 return { 'error' => 'Viewing usage is not allowed.' };
2223 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2224 return { 'error' => $session } if $context eq 'error';
2226 my $search = { 'svcnum' => $p->{'svcnum'} };
2227 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2229 my $cust_svc = qsearchs( 'cust_svc', $search );
2230 return { 'error' => 'No service selected in list_svc_usage' }
2233 my $svc_x = $cust_svc->svc_x;
2234 my $svcdb = $svc_x->table;
2235 my $cust_pkg = $cust_svc->cust_pkg;
2236 my $freq = $cust_pkg->part_pkg->freq;
2239 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2241 if ( $p->{inbound} ) {
2242 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2243 || $conf->config('selfservice-default_inbound_cdr_format')
2244 || 'source_default';
2245 $callback_opt{inbound} = 1;
2247 $format = $cust_pkg->part_pkg->option('selfservice_format')
2248 || $conf->config('selfservice-default_cdr_format')
2252 $callback_opt{format} = $format;
2253 $callback_opt{use_clid} = 1;
2254 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2257 my $start = $cust_pkg->setup;
2258 #my $end = $cust_pkg->bill; # or time?
2261 unless ( $p->{beginning} ) {
2262 $p->{beginning} = $cust_pkg->last_bill;
2263 $p->{ending} = $end;
2266 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2267 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2269 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2273 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2274 # ugly kludge, I know
2275 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2276 if (defined $delete_col) {
2277 delete($_->[$delete_col]) foreach ($header, @usage);
2281 #kinda false laziness with FS::cust_main::bill, but perhaps
2282 #we should really change this bit to DateTime and DateTime::Duration
2284 #change this bit to use Date::Manip? CAREFUL with timezones (see
2285 # mailing list archive)
2286 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2287 (localtime($p->{ending}) )[0,1,2,3,4,5];
2288 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2289 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2291 if ( $freq =~ /^\d+$/ ) {
2293 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2295 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2296 } elsif ( $freq =~ /^(\d+)w$/ ) {
2298 $nmday += $weeks * 7;
2299 $pmday -= $weeks * 7;
2300 } elsif ( $freq =~ /^(\d+)d$/ ) {
2304 } elsif ( $freq =~ /^(\d+)h$/ ) {
2309 return { 'error' => "unparsable frequency: ". $freq };
2312 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2313 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2317 'svcnum' => $p->{svcnum},
2318 'beginning' => $p->{beginning},
2319 'ending' => $p->{ending},
2320 'inbound' => $p->{inbound},
2321 'previous' => ($previous > $start) ? $previous : $start,
2322 'next' => ($next < $end) ? $next : $end,
2323 'header' => $header,
2331 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2332 return { 'error' => $session } if $context eq 'error';
2334 my $search = { 'custnum' => $custnum };
2335 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2336 my $cust_main = qsearchs('cust_main', $search )
2337 or return { 'error' => "unknown custnum $custnum" };
2339 my $status = $cust_main->status;
2341 my %order_pkg_options = ();
2342 if ( $p->{locationnum} > 0 ) {
2343 $order_pkg_options{locationnum} = delete($p->{locationnum});
2344 } elsif ( $p->{address1} ) {
2345 $order_pkg_options{'cust_location'} = new FS::cust_location {
2346 map { $_ => $p->{$_} }
2347 qw( address1 address2 city county state zip country )
2351 #false laziness w/ClientAPI/Signup.pm
2353 my $cust_pkg = new FS::cust_pkg ( {
2354 'custnum' => $custnum,
2355 'pkgpart' => $p->{'pkgpart'},
2356 'quantity' => $p->{'quantity'} || 1,
2358 my $error = $cust_pkg->check;
2359 return { 'error' => $error } if $error;
2362 unless ( $p->{'svcpart'} eq 'none' ) {
2366 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2368 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2369 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2370 $svcdb = $part_svc->svcdb;
2372 $svcdb = 'svc_acct';
2374 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2377 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2378 'svc_domain' => [ qw( domain ) ],
2379 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2380 'svc_external' => [ qw( id title ) ],
2381 'svc_pbx' => [ qw( id title ) ],
2384 my $svc_x = "FS::$svcdb"->new( {
2385 'svcpart' => $svcpart,
2386 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2389 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2392 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2393 my $acct_snarf = new FS::acct_snarf ( {
2394 'machine' => $p->{"snarf_machine$snarfnum"},
2395 'protocol' => $p->{"snarf_protocol$snarfnum"},
2396 'username' => $p->{"snarf_username$snarfnum"},
2397 '_password' => $p->{"snarf_password$snarfnum"},
2400 push @acct_snarf, $acct_snarf;
2402 $svc_x->child_objects( \@acct_snarf );
2405 my $y = $svc_x->setdefault; # arguably should be in new method
2406 return { 'error' => $y } if $y && !ref($y);
2408 $error = $svc_x->check;
2409 return { 'error' => $error } if $error;
2415 $error = $cust_main->order_pkg(
2416 'cust_pkg' => $cust_pkg,
2421 return { 'error' => $error } if $error;
2423 my $conf = new FS::Conf;
2424 if ( $conf->exists('signup_server-realtime') ) {
2426 my $bill_error = _do_bop_realtime( $cust_main, $status );
2429 $cust_pkg->cancel('quiet'=>1);
2432 $cust_pkg->reexport;
2436 $cust_pkg->reexport;
2439 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2441 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2448 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2449 return { 'error' => $session } if $context eq 'error';
2451 my $conf = new FS::Conf;
2452 my $immutable = $conf->exists('selfservice_immutable-package');
2453 return { 'error' => "Package modification disabled" } if $immutable;
2455 my $search = { 'custnum' => $custnum };
2456 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2457 my $cust_main = qsearchs('cust_main', $search )
2458 or return { 'error' => "unknown custnum $custnum" };
2460 my $status = $cust_main->status;
2461 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2462 or return { 'error' => "unknown package $p->{pkgnum}" };
2464 #if someone does need self-service package change of suspended packages,
2465 # figure out how to be more discriminating
2466 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2467 if $cust_pkg->status eq 'suspended';
2469 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2470 'quantity' => $p->{'quantity'} || 1,
2473 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2474 unless ref($err_or_cust_pkg);
2476 if ( $conf->exists('signup_server-realtime') ) {
2478 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2481 $err_or_cust_pkg->suspend;
2484 $err_or_cust_pkg->reexport;
2488 $err_or_cust_pkg->reexport;
2491 return { error => '', pkgnum => $cust_pkg->pkgnum };
2495 sub order_recharge {
2498 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2499 return { 'error' => $session } if $context eq 'error';
2501 my $search = { 'custnum' => $custnum };
2502 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2503 my $cust_main = qsearchs('cust_main', $search )
2504 or return { 'error' => "unknown custnum $custnum" };
2506 my $status = $cust_main->status;
2507 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2508 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2510 my $svc_x = $cust_svc->svc_x;
2511 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2514 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2515 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2516 recharge_totalbytes );
2517 my $amount = $part_pkg->option('recharge_amount', 1);
2519 my ($l, $v, $d) = $cust_svc->label; # blah
2520 my $pkg = "Recharge $v";
2522 my $bill_error = $cust_main->charge($amount, $pkg,
2523 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2524 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2525 $part_pkg->taxclass); #meh
2527 my $conf = new FS::Conf;
2528 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2530 $bill_error = _do_bop_realtime( $cust_main, $status );
2535 my $error = $svc_x->recharge (\%vhash);
2536 return { 'error' => $error } if $error;
2540 my $error = $bill_error;
2541 $error ||= $svc_x->recharge (\%vhash);
2542 return { 'error' => $error } if $error;
2545 return { error => '', svc => $cust_svc->part_svc->svc };
2549 sub _do_bop_realtime {
2550 my ($cust_main, $status, %opt) = @_;
2552 my $old_balance = $cust_main->balance;
2554 my $bill_error = $cust_main->bill
2555 || $cust_main->apply_payments_and_credits;
2557 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2558 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2560 if ( $cust_main->balance > $old_balance
2561 && $cust_main->balance > 0
2562 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2563 || $status eq 'suspended'
2567 unless ( $opt{'no_credit'} ) {
2568 #this makes sense. credit is "un-doing" the invoice
2569 my $conf = new FS::Conf;
2570 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2571 'self-service decline',
2572 reason_type=>$conf->config('signup_credit_type'),
2574 $cust_main->apply_credits( 'order' => 'newest' );
2577 return { 'error' => '_decline', 'bill_error' => $bill_error };
2586 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2587 return { 'error' => $session } if $context eq 'error';
2589 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2590 or return { 'error' => "unknown custnum $custnum" };
2592 my @cust_pkg = sort { $a->bill <=> $b->bill }
2593 grep { $_->part_pkg->freq ne '0' }
2594 $cust_main->ncancelled_pkgs;
2596 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2598 my $total = $cust_main->balance;
2601 my $bill = $_->bill;
2602 $total += $_->part_pkg->base_recur($_, \$bill);
2603 my $renew_date = $_->part_pkg->add_freq($_->bill);
2605 'pkgnum' => $_->pkgnum,
2606 'amount' => sprintf('%.2f', $total),
2607 'bill_date' => $_->bill,
2608 'bill_date_pretty' => time2str('%x', $_->bill),
2609 'renew_date' => $renew_date,
2610 'renew_date_pretty' => time2str('%x', $renew_date),
2611 'expire_date' => $_->expire,
2612 'expire_date_pretty' => time2str('%x', $_->expire),
2617 return { 'dates' => \@array };
2621 sub payment_info_renew_info {
2623 my $renew_info = renew_info($p);
2624 my $payment_info = payment_info($p);
2625 return { %$renew_info,
2633 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2634 return { 'error' => $session } if $context eq 'error';
2636 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2637 or return { 'error' => "unknown custnum $custnum" };
2639 my $date = $p->{'date'};
2643 #freeside-daily -n -d $date fs_daily $custnum
2644 $cust_main->bill_and_collect( 'time' => $date,
2645 'invoice_time' => $now,
2646 'actual_time' => $now,
2647 'check_freq' => '1d',
2650 return { 'error' => '' };
2656 my $session = _cache->get($p->{'session_id'})
2657 or return { 'error' => "Can't resume session" }; #better error message
2659 my $custnum = $session->{'custnum'};
2661 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2662 or return { 'error' => "unknown custnum $custnum" };
2664 my $conf = new FS::Conf;
2666 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2667 or return { 'error' => 'Permission denied' };
2669 my $pkgnum = $p->{'pkgnum'};
2671 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2672 'pkgnum' => $pkgnum, } )
2673 or return { 'error' => "unknown pkgnum $pkgnum" };
2675 my $error = $cust_pkg->suspend(reason => $reasonnum);
2676 return { 'error' => $error };
2682 my $session = _cache->get($p->{'session_id'})
2683 or return { 'error' => "Can't resume session" }; #better error message
2685 my $custnum = $session->{'custnum'};
2687 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2688 or return { 'error' => "unknown custnum $custnum" };
2690 my $pkgnum = $p->{'pkgnum'};
2692 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2693 'pkgnum' => $pkgnum, } )
2694 or return { 'error' => "unknown pkgnum $pkgnum" };
2696 my $error = $cust_pkg->cancel('quiet' => 1);
2697 return { 'error' => $error };
2701 sub provision_phone {
2704 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2706 #editing an existing phone number
2707 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2708 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2709 return { 'error' => $session } if $context eq 'error';
2711 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2712 return { 'error' => 'service not found' } unless $svc_phone;
2713 return { 'error' => 'invalid svcnum' }
2714 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2716 $svc_phone->email($p->{'email'})
2717 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2718 $svc_phone->forwarddst($p->{'forwarddst'})
2719 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2720 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2721 return { 'error' => $svc_phone->replace };
2725 unless ( $p->{'lnp'} ) {
2726 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2727 $p->{'lnp_status'} = "portingin";
2728 return _provision( 'FS::svc_phone',
2729 [qw(lnp_desired_due_date lnp_other_provider
2730 lnp_other_provider_account phonenum countrycode lnp_status)],
2731 [qw(phonenum countrycode)],
2737 # single DID order (the usual case)
2738 unless (scalar(@bulkdid)) {
2739 return _provision( 'FS::svc_phone',
2740 [qw(phonenum countrycode)],
2741 [qw(phonenum countrycode)],
2747 # bulk DID order case
2749 foreach my $did ( @bulkdid ) {
2750 $did =~ s/[^0-9]//g;
2751 $error = _provision( 'FS::svc_phone',
2752 [qw(phonenum countrycode)],
2753 [qw(phonenum countrycode)],
2755 'pkgnum' => $p->{'pkgnum'},
2756 'svcpart' => $p->{'svcpart'},
2758 'countrycode' => $p->{'countrycode'},
2759 'session_id' => $p->{'session_id'},
2762 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2764 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2769 warn "provision_pbx called\n"
2772 warn "provision_pbx calling _provision\n"
2774 _provision( 'FS::svc_pbx',
2775 [qw(id title max_extensions max_simultaneous ip_addr)],
2776 [qw(id title max_extensions max_simultaneous ip_addr)],
2782 sub provision_acct {
2784 warn "provision_acct called\n"
2787 return { 'error' => gettext('passwords_dont_match') }
2788 if $p->{'_password'} ne $p->{'_password2'};
2789 return { 'error' => gettext('empty_password') }
2790 unless length($p->{'_password'});
2792 if ($p->{'domsvc'}) {
2793 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2794 qw ( svcpart pkgnum ) );
2795 return { 'error' => gettext('invalid_domain') }
2796 unless ($domains{$p->{'domsvc'}});
2799 warn "provision_acct calling _provision\n"
2801 _provision( 'FS::svc_acct',
2802 [qw(username _password domsvc)],
2803 [qw(username _password domsvc)],
2809 sub provision_external {
2811 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2812 _provision( 'FS::svc_external',
2820 sub provision_forward {
2822 _provision( 'FS::svc_forward',
2823 ['srcsvc','src','dstsvc','dst'],
2830 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2831 warn "_provision called for $class\n"
2834 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2835 return { 'error' => $session } if $context eq 'error';
2837 my $search = { 'custnum' => $custnum };
2838 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2839 my $cust_main = qsearchs('cust_main', $search )
2840 or return { 'error' => "unknown custnum $custnum" };
2842 my $pkgnum = $p->{'pkgnum'};
2844 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2846 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2847 'pkgnum' => $pkgnum,
2849 or return { 'error' => "unknown pkgnum $pkgnum" };
2851 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2853 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2854 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2856 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2857 if $class ne 'FS::'. $part_svc->svcdb;
2859 warn "creating $class record\n"
2861 my $svc_x = $class->new( {
2862 'pkgnum' => $p->{'pkgnum'},
2863 'svcpart' => $p->{'svcpart'},
2864 map { $_ => $p->{$_} } @$fields
2867 my %insert_args = ();
2868 #i shouldn't be a special case here (pass an option or something)
2869 if ( $class eq 'FS::svc_phone'
2870 && grep length($p->{$_}), @location_editable_fields
2873 $insert_args{'cust_location'} = new FS::cust_location {
2874 map { $_ => $p->{$_} } @location_editable_fields
2878 warn "inserting $class record\n"
2880 my $error = $svc_x->insert(%insert_args);
2883 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2885 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2888 my $return = { 'svc' => $part_svc->svc,
2890 map { $_ => $svc_x->get($_) } @$return_fields
2892 warn "_provision returning ". Dumper($return). "\n"
2901 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2902 return { 'error' => $session } if $context eq 'error';
2904 my $search = { 'custnum' => $custnum };
2905 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2906 my $cust_main = qsearchs('cust_main', $search )
2907 or return { 'error' => "unknown custnum $custnum" };
2909 my $pkgnum = $p->{'pkgnum'};
2911 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2912 'pkgnum' => $pkgnum,
2914 or return { 'error' => "unknown pkgnum $pkgnum" };
2916 my $svcpart = $p->{'svcpart'};
2918 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2919 'svcpart' => $svcpart, } )
2920 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2921 my $part_svc = $pkg_svc->part_svc;
2923 my $conf = new FS::Conf;
2926 'svc' => $part_svc->svc,
2927 'svcdb' => $part_svc->svcdb,
2928 'pkgnum' => $pkgnum,
2929 'svcpart' => $svcpart,
2930 'custnum' => $custnum,
2932 'security_phrase' => 0, #XXX !
2933 'svc_acct_pop' => [], #XXX !
2935 'init_popstate' => '',
2940 small_custview( $cust_main, $conf->config('countrydefault') ),
2944 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2945 && $ret->{'svcdb'} eq 'svc_phone') {
2946 $ret->{'svcnum'} = $p->{'svcnum'};
2947 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2948 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2949 $ret->{'email'} = $svc_phone->email;
2950 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2954 if ($ret->{'svcdb'} eq 'svc_forward') {
2955 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2961 sub unprovision_svc {
2964 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2965 return { 'error' => $session } if $context eq 'error';
2967 my $search = { 'custnum' => $custnum };
2968 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2969 my $cust_main = qsearchs('cust_main', $search )
2970 or return { 'error' => "unknown custnum $custnum" };
2972 my $svcnum = $p->{'svcnum'};
2974 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2975 or return { 'error' => "unknown svcnum $svcnum" };
2977 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2978 unless $cust_svc->cust_pkg->custnum == $custnum;
2980 my $conf = new FS::Conf;
2982 return { 'svc' => $cust_svc->part_svc->svc,
2983 'error' => $cust_svc->cancel,
2985 small_custview( $cust_main, $conf->config('countrydefault') ),
2990 sub myaccount_passwd {
2992 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2993 return { 'error' => $session } if $context eq 'error';
2995 return { 'error' => "New passwords don't match." }
2996 if $p->{'new_password'} ne $p->{'new_password2'};
2998 return { 'error' => 'Enter new password' }
2999 unless length($p->{'new_password'});
3001 #my $search = { 'custnum' => $custnum };
3002 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3003 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3004 my $search = " AND custnum = $1";
3005 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3007 my $svc_acct = qsearchs( {
3008 'table' => 'svc_acct',
3009 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3010 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3011 'LEFT JOIN cust_main USING ( custnum ) ',
3012 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3013 'extra_sql' => $search, #important
3015 or return { 'error' => "Service not found" };
3019 my $conf = new FS::Conf;
3021 return { 'error' => 'Incorrect current password.' }
3022 if ( exists($p->{'old_password'})
3023 || $conf->exists('selfservice-password_change_oldpass')
3025 && ! $svc_acct->check_password($p->{'old_password'});
3027 $error = 'Password too short.'
3028 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
3029 $error = 'Password too long.'
3030 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
3032 $svc_acct->set_password($p->{'new_password'});
3033 $error ||= $svc_acct->replace();
3035 #regular pw change in self-service should change contact pw too, otherwise its
3036 #way too confusing. hell its confusing they're separate at all, but alas.
3037 #need to support the "ISP provides email that's used as a contact email" case
3039 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3040 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3041 custnum => $custnum,
3042 selfservice_access => 'Y',
3046 #svc_acct was successful but this one returns an error? "shouldn't happen"
3047 $error ||= $contact->change_password($p->{'new_password'});
3050 my($label, $value) = $svc_acct->cust_svc->label;
3052 return { 'error' => $error,
3059 # sub contact_passwd {
3061 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
3062 # return { 'error' => $session } if $context eq 'error';
3064 # return { 'error' => 'Not logged in as a contact.' }
3065 # unless $session->{'contactnum'};
3067 # return { 'error' => "New passwords don't match." }
3068 # if $p->{'new_password'} ne $p->{'new_password2'};
3070 # return { 'error' => 'Enter new password' }
3071 # unless length($p->{'new_password'});
3073 # #my $search = { 'custnum' => $custnum };
3074 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3075 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
3076 # my $search = " AND selfservice_access IS NOT NULL ".
3077 # " AND selfservice_access = 'Y' ".
3078 # " AND ( disabled IS NULL OR disabled = '' )".
3079 # " AND custnum IS NOT NULL AND custnum = $1";
3080 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3082 # my $contact = qsearchs( {
3083 # 'table' => 'contact',
3084 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
3085 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
3086 # 'extra_sql' => $search, #important
3088 # or return { 'error' => "Email not found" }; #? how did we get logged in?
3089 # # deleted since then?
3093 # # use these svc_acct length restrictions??
3094 # my $conf = new FS::Conf;
3095 # $error = 'Password too short.'
3096 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
3097 # $error = 'Password too long.'
3098 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
3100 # $error ||= $contact->change_password($p->{'new_password'});
3102 # return { 'error' => $error, };
3109 my $info = skin_info($p);
3111 my $conf = new FS::Conf;
3112 my $verification = $conf->config('selfservice-password_reset_verification')
3113 or return { %$info, 'error' => 'Password resets disabled' };
3118 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3120 $contact = FS::contact->by_selfservice_email($p->{'email'});
3123 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3124 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3127 #also look for an svc_acct, otherwise it would be super confusing
3129 my($username, $domain) = split('@', $p->{'email'});
3130 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3131 if ( $svc_domain ) {
3132 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3133 'domsvc' => $svc_domain->svcnum }
3136 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3137 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3139 #precaution: don't change svc_acct password not part of the same
3140 # customer as contact
3141 $svc_acct = '' if ! $cust_pkg
3142 || $cust_pkg->custnum != $cust_main->custnum;
3147 return { %$info, 'error' => 'Email address not found' }
3148 unless $contact || $svc_acct;
3150 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3152 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3153 or return { %$info, 'error' => 'Account not found' };
3155 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3156 'domsvc' => $svc_domain->svcnum }
3158 or return { %$info, 'error' => 'Account not found' };
3160 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3161 or return { %$info, 'error' => 'Account not found' };
3163 $cust_main = $cust_pkg->cust_main;
3167 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3168 if ! $cust_main && $verification ne 'email';
3171 'email' => sub { 1; },
3173 my( $p, $cust_main ) = @_;
3174 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3175 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3178 my( $p, $cust_main ) = @_;
3179 my $cust_pay = qsearchs({
3180 'table' => 'cust_pay',
3181 'hashref' => { 'custnum' => $cust_main->custnum },
3182 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3186 $p->{'amount'} == $cust_pay->paid;
3189 my( $p, $cust_main ) = @_;
3190 $p->{'zip'} eq $cust_main->zip
3191 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3195 foreach my $verify ( split(',', $verification) ) {
3197 &{ $verify{$verify} }( $p, $cust_main )
3198 or return { %$info, 'error' => 'Account not found' };
3202 #okay, we're verified
3206 my $error = $contact->send_reset_email(
3207 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3211 return { %$info, 'error' => $error }; #????
3214 } elsif ( $svc_acct ) {
3216 #create a unique session
3218 my $reset_session = {
3219 'svcnum' => $svc_acct->svcnum,
3223 my $timeout = '1 hour'; #?
3225 my $reset_session_id;
3227 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3228 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3231 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3235 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3236 $cust_main->agentnum);
3237 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3238 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3240 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3241 my $error = $msg_template->send( 'cust_main' => $cust_main,
3242 'object' => $svc_acct,
3243 'substitutions' => {
3244 'session_id' => $reset_session_id,
3248 return { %$info, 'error' => $error }; #????
3253 return { %$info, 'error' => '' };
3256 sub check_reset_passwd {
3259 my $conf = new FS::Conf;
3260 my $verification = $conf->config('selfservice-password_reset_verification')
3261 or return { 'error' => 'Password resets disabled' };
3263 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3264 or return { 'error' => "Can't resume session" }; #better error message
3266 if ( $reset_session->{'svcnum'} ) {
3268 my $svcnum = $reset_session->{'svcnum'};
3270 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3271 or return { 'error' => "Service not found" };
3273 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3274 my $info = skin_info($p);
3278 'session_id' => $p->{'session_id'},
3279 'username' => $svc_acct->username,
3282 } elsif ( $reset_session->{'contactnum'} ) {
3284 my $contactnum = $reset_session->{'contactnum'};
3286 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3287 or return { 'error' => "Contact not found" };
3289 my @contact_email = $contact->contact_email;
3290 return { 'error' => 'No contact email' } unless @contact_email;
3292 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3293 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3294 if scalar(@cust_contact) == 1;
3295 my $info = skin_info($p);
3299 'session_id' => $p->{'session_id'},
3300 'email' => $contact_email[0]->email, #the first?
3305 return { 'error' => 'No svcnum or contactnum in session' }; #??
3311 sub process_reset_passwd {
3314 my $conf = new FS::Conf;
3315 my $verification = $conf->config('selfservice-password_reset_verification')
3316 or return { 'error' => 'Password resets disabled' };
3318 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3319 or return { 'error' => "Can't resume session" }; #better error message
3324 if ( $reset_session->{'svcnum'} ) {
3326 my $svcnum = $reset_session->{'svcnum'};
3328 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3329 or return { 'error' => "Service not found" };
3331 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3332 $info ||= skin_info($p);
3337 if ( $reset_session->{'contactnum'} ) {
3339 my $contactnum = $reset_session->{'contactnum'};
3341 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3342 or return { 'error' => "Contact not found" };
3344 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3345 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3346 if scalar(@cust_contact) == 1;
3347 $info ||= skin_info($p);
3351 return { %$info, 'error' => "New passwords don't match." }
3352 if $p->{'new_password'} ne $p->{'new_password2'};
3354 return { %$info, 'error' => 'Enter new password' }
3355 unless length($p->{'new_password'});
3359 $svc_acct->set_password($p->{'new_password'});
3360 my $error = $svc_acct->replace();
3362 return { %$info, 'error' => $error } if $error;
3364 #my($label, $value) = $svc_acct->cust_svc->label;
3365 #return { 'error' => $error,
3366 # #'label' => $label,
3367 # #'value' => $value,
3374 my $error = $contact->change_password($p->{'new_password'});
3376 return { %$info, 'error' => $error }; # if $error;
3380 #password changed ,so remove session, don't want it reused
3381 _cache->remove($p->{'session_id'});
3383 return { %$info, 'error' => '' };
3389 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3390 return { 'error' => $session } if $context eq 'error';
3393 if ( $session->{'pkgnum'} ) {
3395 #tickets for specific service with pkg-balances on
3396 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3397 'pkgnum' => $session->{'pkgnum'} })
3398 or return { 'error' => 'unknown package' };
3399 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3400 push @tickets, $cust_svc->tickets( $p->{status} );
3405 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3406 or return { 'error' => "unknown custnum $custnum" };
3408 @tickets = $cust_main->tickets( $p->{status} );
3411 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3412 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3413 my $conf = new FS::Conf;
3414 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3418 ($a->{'_selfservice_priority'} eq '') <=>
3419 ($b->{'_selfservice_priority'} eq '')
3422 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3428 +{ tickets => \@tickets };
3435 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3436 return { 'error' => $session } if $context eq 'error';
3438 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3439 FS::TicketSystem->init();
3441 my $conf = new FS::Conf;
3442 my $queue = $p->{'queue'}
3443 || $conf->config('ticket_system-selfservice_queueid')
3444 || $conf->config('ticket_system-default_queueid');
3446 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3447 my $err_or_ticket = FS::TicketSystem->create_ticket(
3448 '', #create RT session based on FS CurrentUser (fs_selfservice)
3450 'custnum' => $custnum,
3451 'svcnum' => $session->{'svcnum'},
3452 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3455 if ( ref($err_or_ticket) ) {
3456 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3458 return { 'error' => '',
3459 'ticket_id' => $err_or_ticket->id,
3462 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3464 return { 'error' => $err_or_ticket };
3472 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3473 return { 'error' => $session } if $context eq 'error';
3475 return { error => 'requested format not implemented' }
3476 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3478 my $conf = new FS::Conf;
3479 my $age_threshold = 0;
3480 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3481 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3483 my $search = { 'custnum' => $custnum };
3484 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3485 my $cust_main = qsearchs('cust_main', $search )
3486 or return { 'error' => "unknown custnum $custnum" };
3488 # does it make more sense to just run one sql query for this instead of all the
3489 # insanity below? would increase performance greately for large data sets?
3491 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3492 my @part_svc = $cust_pkg->part_svc;
3493 foreach my $part_svc ( @part_svc ) {
3494 if($part_svc->svcdb eq 'svc_phone'){
3495 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3496 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3497 push @svc_phone, $cust_pkg_svc->svc_x
3498 if $cust_pkg_svc->date_inserted >= $age_threshold;
3506 my($xls_r,$xls_c) = (0,0);
3509 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3510 if($p->{'format'} eq 'csv') {
3511 $csv = new Text::CSV_XS { 'always_quote' => 1,
3514 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3515 $content .= $csv->string;
3517 elsif($p->{'format'} eq 'xls') {
3518 my $XLS1 = new IO::Scalar \$content;
3519 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3520 or return { 'error' => "Error opening .xls file: $!" };
3521 $xls = $xls_workbook->add_worksheet('DIDs');
3522 foreach ( @fields ) {
3523 $xls->write(0,$xls_c++,$_);
3528 foreach my $svc_phone ( @svc_phone ) {
3529 my @cols = map { $svc_phone->$_ } @fields;
3530 if($p->{'format'} eq 'csv') {
3531 return { 'error' => 'Unable to create CSV' }
3532 unless $csv->combine(@cols);
3533 $content .= $csv->string;
3535 elsif($p->{'format'} eq 'xls') {
3538 $xls->write($xls_r,$xls_c++,$_);
3544 $xls_workbook->close() if $p->{'format'} eq 'xls';
3546 { content => $content, format => $p->{'format'}, };
3551 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3552 return { 'error' => $session } if $context eq 'error';
3554 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3555 # FS::TicketSystem->init();
3556 # return { 'error' => 'get_ticket configuration error' }
3557 # if $FS::TicketSystem::system ne 'RT_Internal';
3559 # check existence and ownership as part of this
3560 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3561 my $rt_session = FS::TicketSystem->session('');
3562 my $Ticket = FS::TicketSystem->get_ticket_object(
3564 ticket_id => $p->{'ticket_id'},
3567 return { 'error' => 'ticket not found' } if !$Ticket;
3569 if ( length( $p->{'subject'} || '' ) ) {
3571 if ( $p->{'subject'} ne $Ticket->Subject ) {
3572 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3573 return { 'error' => "unable to set subject: $msg" } if !$val;
3577 if(length($p->{'reply'})) {
3578 my @err_or_res = FS::TicketSystem->correspond_ticket(
3580 'ticket_id' => $p->{'ticket_id'},
3581 'content' => $p->{'reply'},
3584 return { 'error' => 'unable to reply to ticket' }
3585 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3588 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3589 my $err_or_ticket = FS::TicketSystem->get_ticket(
3591 'ticket_id' => $p->{'ticket_id'},
3594 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3595 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3597 return { 'error' => $err_or_ticket };
3600 my @custs = @{$err_or_ticket->{'custs'}};
3601 my @txns = @{$err_or_ticket->{'txns'}};
3604 # superseded by check in get_ticket_object
3605 #return { 'error' => 'invalid ticket requested' }
3606 #unless grep($_ eq $custnum, @custs);
3608 foreach my $txn ( @txns ) {
3609 push @filtered_txns, $txn
3610 if ($txn->{'type'} eq 'EmailRecord'
3611 || $txn->{'type'} eq 'Correspond'
3612 || $txn->{'type'} eq 'Create');
3615 warn "$me get_ticket: successful: \n"
3617 return { 'error' => '',
3618 'transactions' => \@filtered_txns,
3619 'ticket_fields' => $err_or_ticket->{'fields'},
3620 'ticket_id' => $p->{'ticket_id'},
3624 sub adjust_ticket_priority {
3626 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3627 return { 'error' => $session } if $context eq 'error';
3629 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3630 # FS::TicketSystem->init;
3631 my $ss_priority = FS::TicketSystem->selfservice_priority;
3633 return { 'error' => 'adjust_ticket_priority configuration error' }
3634 if $FS::TicketSystem::system ne 'RT_Internal'
3637 my $values = $p->{'values'}; #hashref, id => priority value
3640 foreach my $id (keys %$values) {
3641 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3642 my $Ticket = FS::TicketSystem->get_ticket_object('',
3644 'custnum' => $custnum,
3647 $ticket_error{$id} = 'ticket not found';
3651 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3652 # We're not going to implement it for RT_External.
3653 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3654 my $new_value = $values->{$id};
3655 next if $old_value eq $new_value;
3657 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3659 # AddCustomFieldValue works fine (replacing any existing value) if it's
3660 # a single-valued custom field, which it should be. If it's not, you're
3661 # doing something wrong.
3663 if ( length($new_value) ) {
3664 ($val, $msg) = $Ticket->AddCustomFieldValue(
3665 Field => $ss_priority,
3666 Value => $new_value,
3670 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3671 Field => $ss_priority,
3672 Value => $old_value,
3676 $ticket_error{$id} = $msg if !$val;
3677 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3679 return { 'error' => '',
3680 'ticket_error' => \%ticket_error,
3681 %{ customer_info($p) } # send updated customer info back
3687 sub _custoragent_session_custnum {
3690 my($context, $session, $custnum);
3691 if ( $p->{'session_id'} ) {
3693 $context = 'customer';
3694 $session = _cache->get($p->{'session_id'})
3695 or return ( 'error' => "Can't resume session" ); #better error message
3696 $custnum = $session->{'custnum'};
3698 } elsif ( $p->{'agent_session_id'} ) {
3701 my $agent_cache = new FS::ClientAPI_SessionCache( {
3702 'namespace' => 'FS::ClientAPI::Agent',
3704 $session = $agent_cache->get($p->{'agent_session_id'})
3705 or return ( 'error' => "Can't resume session" ); #better error message
3706 $custnum = $p->{'custnum'};
3710 return ( 'error' => "Can't resume session" ); #better error message
3713 ($context, $session, $custnum);