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;
51 $me = '[FS::ClientAPI::MyAccount]';
53 use vars qw( @cust_main_editable_fields @location_editable_fields );
54 @cust_main_editable_fields = qw(
55 first last company daytime night fax mobile
57 payby payinfo payname paystart_month paystart_year payissue payip
58 ss paytype paystate stateid stateid_state
60 @location_editable_fields = qw(
61 address1 address2 city county state zip country
65 BEGIN { #preload to reduce time customer_info takes
66 if ( $FS::TicketSystem::system ) {
67 warn "$me: initializing ticket system\n" if $DEBUG;
68 FS::TicketSystem->init();
73 $cache ||= new FS::ClientAPI_SessionCache( {
74 'namespace' => 'FS::ClientAPI::MyAccount',
81 my($context, $session, $custnum) = _custoragent_session_custnum($p);
82 #return { 'error' => $session } if $context eq 'error';
85 if ( $context eq 'customer' ) {
87 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
90 $sth->execute($custnum) or die $sth->errstr;
92 $agentnum = $sth->fetchrow_arrayref->[0]
93 or die "no agentnum for custnum $custnum";
95 #} elsif ( $context eq 'agent' ) {
96 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
99 $p->{'agentnum'} = $agentnum;
101 my $conf = new FS::Conf;
103 #false laziness w/Signup.pm
105 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
107 if ( $skin_info_cache_agent ) {
109 warn "$me loading cached skin info for agentnum $agentnum\n"
114 warn "$me populating skin info cache for agentnum $agentnum\n"
117 $skin_info_cache_agent = {
118 'agentnum' => $agentnum,
119 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
120 qw( company_name date_format ) ),
121 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
122 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
123 text_color link_color vlink_color hlink_color alink_color
124 font title_color title_align title_size menu_bgcolor menu_fontsize
127 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
128 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
129 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
131 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
132 qw( title_left_image title_right_image
133 menu_top_image menu_body_image menu_bottom_image
136 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
137 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
138 qw( head body_header body_footer company_address ) ),
139 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
142 services.php Services
143 services.php My Services
144 services_new.php Order a new service
147 personal.php Personal Information
148 password.php Change Password
151 payment_cc.php Credit Card Payment
152 payment_ach.php Electronic Check Payment
153 payment_paypal.php PayPal Payment
154 payment_webpay.php Webpay Payments
157 usage_data.php Data usage
158 usage_cdr.php Call usage
160 tickets.php Help Desk
161 tickets.php Open Tickets
162 tickets_resolved.php Resolved Tickets
163 ticket_create.php Create a new ticket
171 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
175 #{ %$skin_info_cache_agent };
176 $skin_info_cache_agent;
183 my $conf = new FS::Conf;
187 'phone_login' => $conf->exists('selfservice_server-phone_login'),
188 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
189 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
190 'banner_image_md5' =>
191 md5_hex($conf->config_binary('selfservice-login_banner_image')),
198 sub login_banner_image {
200 my $conf = new FS::Conf;
201 my $image = $conf->config_binary('selfservice-login_banner_image');
203 'md5' => md5_hex($image),
208 #false laziness w/FS::ClientAPI::passwd::passwd
212 my $conf = new FS::Conf;
216 if ( $p->{'domain'} eq 'svc_phone'
217 && $conf->exists('selfservice_server-phone_login') ) {
219 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
220 return { error => 'Number not found.' } unless $svc_phone;
223 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
224 #return { error => 'Only primary user may log in.' }
225 # if $conf->exists('selfservice_server-primary_only')
226 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
228 return { error => 'Incorrect PIN.' }
229 unless $svc_phone->check_pin($p->{'password'});
233 } elsif ( $p->{email}
234 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
237 return { error => 'Incorrect contact password.' }
238 unless $contact->authenticate_password($p->{'password'});
240 $session->{'custnum'} = $contact->custnum;
244 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
246 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
247 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
249 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
250 'domsvc' => $svc_domain->svcnum, }
252 return { error => 'User not found.' } unless $svc_acct;
254 if($conf->exists('selfservice_server-login_svcpart')) {
255 my @svcpart = $conf->config('selfservice_server-login_svcpart');
256 my $svcpart = $svc_acct->cust_svc->svcpart;
257 return { error => 'Invalid user.' }
258 unless grep($_ eq $svcpart, @svcpart);
261 return { error => 'Incorrect password.' }
262 unless $svc_acct->check_password($p->{'password'});
270 $session->{'svcnum'} = $svc_x->svcnum;
272 my $cust_svc = $svc_x->cust_svc;
273 my $cust_pkg = $cust_svc->cust_pkg;
275 my $cust_main = $cust_pkg->cust_main;
276 $session->{'custnum'} = $cust_main->custnum;
277 if ( $conf->exists('pkg-balances') ) {
278 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
279 $cust_main->ncancelled_pkgs;
280 $session->{'pkgnum'} = $cust_pkg->pkgnum
281 if scalar(@cust_pkg) > 1;
285 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
286 #return { error => 'Only primary user may log in.' }
287 # if $conf->exists('selfservice_server-primary_only')
288 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
289 my $part_pkg = $cust_pkg->part_pkg;
290 return { error => 'Only primary user may log in.' }
291 if $conf->exists('selfservice_server-primary_only')
292 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
298 $session_id = sha512_hex(time(). {}. rand(). $$)
299 } until ( ! defined _cache->get($session_id) ); #just in case
301 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
302 _cache->set( $session_id, $session, $timeout );
304 return { 'error' => '',
305 'session_id' => $session_id,
311 if ( $p->{'session_id'} ) {
312 _cache->remove($p->{'session_id'});
313 return { %{ skin_info($p) }, 'error' => '' };
315 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
322 my($context, $session, $custnum) = _custoragent_session_custnum($p);
323 return { 'error' => $session } if $context eq 'error';
325 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
326 or return { 'error' => "Service not found" };
328 $session->{'svcnum'} = $svc_acct->svcnum;
330 my $conf = new FS::Conf;
331 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
332 _cache->set( $p->{'session_id'}, $session, $timeout );
334 return { 'error' => '' };
338 sub payment_gateway {
340 # takes a cust_main and a cust_payby entry, returns the payment_gateway
341 my $conf = new FS::Conf;
342 my $cust_main = shift;
343 my $cust_payby = shift;
344 my $gatewaynum = $conf->config('selfservice-payment_gateway');
346 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
347 die "configured gatewaynum $gatewaynum not found!" if !$pg;
351 return '' if ! FS::payby->realtime($cust_payby);
352 my $pg = $cust_main->agent->payment_gateway(
353 'method' => FS::payby->payby2bop($cust_payby),
363 my $conf = new FS::Conf;
365 my $info = skin_info($p);
367 use vars qw( $cust_paybys ); #cache for performance
368 unless ( $cust_paybys ) {
370 my %cust_paybys = map { $_ => 1 }
371 map { FS::payby->payby2payment($_) }
372 $conf->config('signup_server-payby');
374 $cust_paybys = [ keys %cust_paybys ];
377 $info->{'cust_paybys'} = $cust_paybys;
379 my($context, $session, $custnum) = _custoragent_session_custnum($p);
380 return { 'error' => $session } if $context eq 'error';
382 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
383 or return { 'error' => "unknown custnum $custnum" };
385 $info->{'hide_payment_fields'} = [
387 my $pg = payment_gateway($cust_main, $_);
388 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
389 } @{ $info->{cust_paybys} }
392 $info->{'self_suspend_reason'} =
393 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
395 $info->{'edit_ticket_subject'} =
396 $conf->exists('ticket_system-selfservice_edit_subject') &&
397 $cust_main->edit_subject;
399 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
402 'custnum' => $custnum,
403 'access_pkgnum' => $session->{'pkgnum'},
404 'access_svcnum' => $session->{'svcnum'},
411 my($context, $session, $custnum) = _custoragent_session_custnum($p);
412 return { 'error' => $session } if $context eq 'error';
416 my $conf = new FS::Conf;
417 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
419 # if ( $FS::TicketSystem::system ) {
420 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
421 # FS::TicketSystem->init();
424 if ( $custnum ) { #customer record
426 %return = ( %return, %{ customer_info_short($p) } );
428 #redundant with customer_info_short, but we need it for several things below
429 my $search = { 'custnum' => $custnum };
430 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
431 my $cust_main = qsearchs('cust_main', $search )
432 or return { 'error' => "unknown custnum $custnum" };
434 my $list_tickets = list_tickets($p);
435 $return{'tickets'} = $list_tickets->{'tickets'};
437 if ( $session->{'pkgnum'} ) {
438 #XXX open invoices in the pkg-balances case
442 invnum => $_->invnum,
443 date => time2str("%b %o, %Y", $_->_date),
446 } $cust_main->open_cust_bill;
447 $return{open_invoices} = \@open;
449 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
450 my $sth = dbh->prepare($sql) or die dbh->errstr;
451 $sth->execute($custnum) or die $sth->errstr;
452 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
453 $return{'last_invoice_date_pretty'} =
454 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
457 #customer_info_short always has nobalance on..
458 $return{small_custview} =
459 small_custview( $cust_main,
460 $return{countrydefault},
461 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
464 $return{has_ship_address} = $cust_main->has_ship_address;
465 $return{status} = $cust_main->status;
466 $return{statuscolor} = $cust_main->statuscolor;
468 # compatibility: some places in selfservice use this to determine
469 # if there's a ship address
470 if ( $return{has_ship_address} ) {
471 $return{ship_last} = $cust_main->last;
472 $return{ship_first} = $cust_main->first;
475 if (scalar($conf->config('support_packages'))) {
476 my @support_services = ();
477 foreach ($cust_main->support_services) {
478 my $seconds = $_->svc_x->seconds || 0;
479 my $time_remaining = (($seconds < 0) ? '-' : '' ).
480 int(abs($seconds)/3600)."h".
481 sprintf("%02d",(abs($seconds)%3600)/60)."m";
482 my $cust_pkg = $_->cust_pkg;
485 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
486 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
487 push @support_services, { svcnum => $_->svcnum,
488 time => $time_remaining,
493 $return{support_services} = \@support_services;
496 if ( $conf->config('prepayment_discounts-credit_type') ) {
498 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
501 } elsif ( $session->{'svcnum'} ) { #no customer record
503 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
504 or die "unknown svcnum";
505 $return{name} = $svc_acct->email;
509 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
513 return { 'error' => '',
514 'custnum' => $custnum,
520 sub customer_info_short {
523 my($context, $session, $custnum) = _custoragent_session_custnum($p);
524 return { 'error' => $session } if $context eq 'error';
528 my $conf = new FS::Conf;
530 if ( $custnum ) { #customer record
532 my $search = { 'custnum' => $custnum };
533 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
534 my $cust_main = qsearchs('cust_main', $search )
535 or return { 'error' => "unknown custnum $custnum" };
537 $return{display_custnum} = $cust_main->display_custnum;
539 if ( $session->{'pkgnum'} ) {
540 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
541 #next_bill_date from cust_pkg?
543 $return{balance} = $cust_main->balance;
544 $return{next_bill_date} = $cust_main->next_bill_date;
545 $return{next_bill_date_pretty} =
546 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
550 $return{countrydefault} = scalar($conf->config('countrydefault'));
552 $return{small_custview} =
553 small_custview( $cust_main,
554 $return{countrydefault},
558 $return{first} = $cust_main->first;
559 $return{'last'} = $cust_main->get('last');
560 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
562 $return{payby} = $cust_main->payby;
564 #none of these are terribly expensive if we want 'em...
565 for (@cust_main_editable_fields) {
566 $return{$_} = $cust_main->get($_);
568 #maybe a little more expensive, but it should be cached by now
569 for (@location_editable_fields) {
570 $return{$_} = $cust_main->bill_location->get($_)
571 if $cust_main->bill_locationnum;
572 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
573 if $cust_main->ship_locationnum;
576 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
577 $return{payinfo} = $cust_main->paymask;
578 @return{'month', 'year'} = $cust_main->paydate_monthyear;
581 my @invoicing_list = $cust_main->invoicing_list;
582 $return{'invoicing_list'} =
583 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
584 $return{'postal_invoicing'} =
585 0 < ( grep { $_ eq 'POST' } @invoicing_list );
587 if ( $session->{'svcnum'} ) {
588 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
589 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
590 $return{'svcnum'} = $session->{'svcnum'};
593 } elsif ( $session->{'svcnum'} ) { #no customer record
595 #uuh, not supproted yet... die?
596 return { 'error' => 'customer_info_short not yet supported as agent' };
600 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
604 return { 'error' => '',
605 'custnum' => $custnum,
610 sub billing_history {
613 my($context, $session, $custnum) = _custoragent_session_custnum($p);
614 return { 'error' => $session } if $context eq 'error';
616 return { 'error' => 'No customer' } unless $custnum;
618 my $search = { 'custnum' => $custnum };
619 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
620 my $cust_main = qsearchs('cust_main', $search )
621 or return { 'error' => "unknown custnum $custnum" };
625 if ( $session->{'pkgnum'} ) {
626 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
627 #next_bill_date from cust_pkg?
628 return { 'error' => 'No history for package' };
631 $return{balance} = $cust_main->balance;
632 $return{next_bill_date} = $cust_main->next_bill_date;
633 $return{next_bill_date_pretty} =
634 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
639 my $conf = new FS::Conf;
641 if ( $conf->exists('selfservice-billing_history-line_items') ) {
643 foreach my $cust_bill ( $cust_main->cust_bill ) {
646 'type' => 'Line item',
647 'description' => $_->desc( $cust_main->locale ).
648 ( $_->sdate && $_->edate
649 ? ' '. time2str('%d-%b-%Y', $_->sdate).
650 ' To '. time2str('%d-%b-%Y', $_->edate)
653 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
654 'date' => $cust_bill->_date,
655 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
657 foreach $cust_bill->cust_bill_pkg;
665 'description' => 'Invoice #'. $_->display_invnum,
666 'amount' => sprintf('%.2f', $_->charged ),
668 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
670 foreach $cust_main->cust_bill;
676 'description' => 'Payment', #XXX type
677 'amount' => sprintf('%.2f', 0 - $_->paid ),
679 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
681 foreach $cust_main->cust_pay;
685 'description' => 'Credit', #more info?
686 'amount' => sprintf('%.2f', 0 -$_->amount ),
688 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
690 foreach $cust_main->cust_credit;
694 'description' => 'Refund', #more info? type, like payment?
695 'amount' => $_->refund,
697 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
699 foreach $cust_main->cust_refund;
701 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
703 $return{'history'} = \@history;
711 my $session = _cache->get($p->{'session_id'})
712 or return { 'error' => "Can't resume session" }; #better error message
714 my $custnum = $session->{'custnum'}
715 or return { 'error' => "no customer record" };
717 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
718 or return { 'error' => "unknown custnum $custnum" };
720 my $new = new FS::cust_main { $cust_main->hash };
722 $new->set( $_ => $p->{$_} )
723 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
725 if ( exists($p->{address1}) ) {
726 my $bill_location = FS::cust_location->new({
727 map { $_ => $p->{$_} } @location_editable_fields
729 # if this is unchanged from before, cust_main::replace will ignore it
730 $new->set('bill_location' => $bill_location);
733 if ( exists($p->{ship_address1}) ) {
734 my $ship_location = FS::cust_location->new({
735 map { $_ => $p->{"ship_$_"} } @location_editable_fields
737 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
738 # Selfservice unfortunately tries to indicate "same as billing
739 # address" by sending all fields empty. Did this ever work?
740 $ship_location = $cust_main->bill_location;
742 $new->set('ship_location' => $ship_location);
744 # but if it hasn't been passed in at all, leave ship_location alone--
745 # DON'T change it to match bill_location.
748 if (exists($p->{'payby'})) {
749 $p->{'payby'} =~ /^([A-Z]{4})$/
750 or return { 'error' => "illegal_payby " . $p->{'payby'} };
754 if ( $payby =~ /^(CARD|DCRD)$/ ) {
756 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
758 if ( $new->payinfo eq $cust_main->paymask ) {
759 $new->payinfo($cust_main->payinfo);
761 $new->payinfo($p->{'payinfo'});
764 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
766 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
769 $p->{'payinfo1'} =~ /^([\dx]+)$/
770 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
772 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
773 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
775 $payinfo = $payinfo1. '@'. $payinfo2;
777 $new->payinfo( ($payinfo eq $cust_main->paymask)
778 ? $cust_main->payinfo
782 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
784 } elsif ( $payby =~ /^(BILL)$/ ) {
786 } elsif ( $payby ) { #notyet ready
787 return { 'error' => "unknown payby $payby" };
791 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
792 #false laziness with httemplate/edit/process/cust_main.cgi
793 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
794 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
796 @invoicing_list = $cust_main->invoicing_list;
799 my $error = $new->replace($cust_main, \@invoicing_list);
800 return { 'error' => $error } if $error;
803 return { 'error' => '' };
808 my $session = _cache->get($p->{'session_id'})
809 or return { 'error' => "Can't resume session" }; #better error message
815 my $conf = new FS::Conf;
816 use vars qw($payment_info); #cache for performance
817 unless ( $payment_info ) {
819 my %states = map { $_->state => 1 }
820 qsearch('cust_main_county', {
821 'country' => $conf->config('countrydefault') || 'US'
824 my %cust_paybys = map { $_ => 1 }
825 map { FS::payby->payby2payment($_) }
826 $conf->config('signup_server-payby');
828 my @cust_paybys = keys %cust_paybys;
832 #list all counties/states/countries
833 'cust_main_county' =>
834 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
836 #shortcut for one-country folks
838 [ sort { $a cmp $b } keys %states ],
840 'card_types' => card_types(),
842 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
843 'require_cvv' => $conf->exists('selfservice-require_cvv'),
845 'paytypes' => [ @FS::cust_main::paytypes ],
847 'paybys' => [ $conf->config('signup_server-payby') ],
848 'cust_paybys' => \@cust_paybys,
850 'stateid_label' => FS::Msgcat::_gettext('stateid'),
851 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
853 'show_ss' => $conf->exists('show_ss'),
854 'show_stateid' => $conf->exists('show_stateid'),
855 'show_paystate' => $conf->exists('show_bankstate'),
857 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
859 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
868 my %return = %$payment_info;
870 my $custnum = $session->{'custnum'};
872 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
873 or return { 'error' => "unknown custnum $custnum" };
875 $return{'hide_payment_fields'} = [
877 my $pg = payment_gateway($cust_main, $_);
878 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
879 } @{ $return{cust_paybys} }
882 $return{balance} = $cust_main->balance; #XXX pkg-balances?
884 $return{payname} = $cust_main->payname
885 || ( $cust_main->first. ' '. $cust_main->get('last') );
887 $return{$_} = $cust_main->bill_location->get($_)
888 for qw(address1 address2 city state zip);
890 $return{payby} = $cust_main->payby;
891 $return{stateid_state} = $cust_main->stateid_state;
893 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
894 $return{card_type} = cardtype($cust_main->payinfo);
895 $return{payinfo} = $cust_main->paymask;
897 @return{'month', 'year'} = $cust_main->paydate_monthyear;
901 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
902 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
903 $return{payinfo1} = $payinfo1;
904 $return{payinfo2} = $payinfo2;
905 $return{paytype} = $cust_main->paytype;
906 $return{paystate} = $cust_main->paystate;
907 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
910 if ( $conf->config('prepayment_discounts-credit_type') ) {
912 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
915 #doubleclick protection
917 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
919 return { 'error' => '',
925 #some false laziness with httemplate/process/payment.cgi - look there for
926 #ACH and CVV support stuff
928 sub validate_payment {
931 my $session = _cache->get($p->{'session_id'})
932 or return { 'error' => "Can't resume session" }; #better error message
934 my $custnum = $session->{'custnum'};
936 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
937 or return { 'error' => "unknown custnum $custnum" };
939 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
940 or return { 'error' => gettext('illegal_amount') };
942 return { error => 'Amount must be greater than 0' } unless $amount > 0;
944 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
945 #changing the hidden form values
946 my $conf = new FS::Conf;
947 my $fee_display = $conf->config('selfservice_process-display') || 'add';
948 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
949 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
950 if ( $fee_display eq 'add'
952 and ! $fee_skip_first || scalar($cust_main->cust_pay)
955 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
956 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
959 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
960 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
961 my $discount_term = $1;
963 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
964 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
967 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
968 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
971 $p->{'payby'} ||= 'CARD';
972 $p->{'payby'} =~ /^([A-Z]{4})$/
973 or return { 'error' => "illegal_payby " . $p->{'payby'} };
976 #false laziness w/process/payment.cgi
979 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
981 $p->{'payinfo1'} =~ /^([\dx]+)$/
982 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
984 $p->{'payinfo2'} =~ /^([\dx]+)$/
985 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
987 $payinfo = $payinfo1. '@'. $payinfo2;
989 $payinfo = $cust_main->payinfo
990 if $cust_main->paymask eq $payinfo;
992 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
994 $payinfo = $p->{'payinfo'};
996 #more intelligent matching will be needed here if you change
997 #card_masking_method and don't remove existing paymasks
998 $payinfo = $cust_main->payinfo
999 if $cust_main->paymask eq $payinfo;
1001 $payinfo =~ s/\D//g;
1002 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1003 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1007 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1008 return { 'error' => gettext('unknown_card_type') }
1009 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1011 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1012 if ( cardtype($payinfo) eq 'American Express card' ) {
1013 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1014 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1017 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1018 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1021 } elsif ( $conf->exists('selfservice-require_cvv') ) { #and you weren't using a card on file?
1022 return { 'error' => 'CVV2 is required' };
1026 die "unknown payby $payby";
1029 my %payby2fields = (
1030 'CARD' => [ qw( paystart_month paystart_year payissue payip
1031 address1 address2 city state zip country ) ],
1032 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1036 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1039 'cust_main' => $cust_main, #XXX or just custnum??
1040 'amount' => sprintf('%.2f', $amount),
1042 'payinfo' => $payinfo,
1043 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1044 'card_type' => $card_type,
1045 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1046 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1047 'month' => $p->{'month'},
1048 'year' => $p->{'year'},
1049 'payname' => $payname,
1050 'paybatch' => $paybatch, #this doesn't actually do anything
1051 'paycvv' => $paycvv,
1052 'payname' => $payname,
1053 'discount_term' => $discount_term,
1054 'pkgnum' => $session->{'pkgnum'},
1055 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1065 my $validate = validate_payment($p);
1066 return $validate if $validate->{'error'};
1068 my $conf = new FS::Conf;
1069 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1070 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1072 +{ map { $_=>$validate->{$_} }
1073 qw( card_type paymask payname paydate_pretty month year amount
1074 address1 address2 city state zip country
1080 sub process_stored_payment {
1083 my $session_id = $p->{'session_id'};
1085 my $payment_info = _cache->get( "payment_$session_id" )
1086 or return { 'error' => "Can't resume session" }; #better error message
1088 do_process_payment($payment_info);
1092 sub process_payment {
1095 my $payment_info = validate_payment($p);
1096 return $payment_info if $payment_info->{'error'};
1098 do_process_payment($payment_info);
1102 sub do_process_payment {
1103 my $validate = shift;
1105 my $cust_main = $validate->{'cust_main'};
1107 my $amount = delete $validate->{'amount'};
1110 my $payby = delete $validate->{'payby'};
1112 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1115 'paynum_ref' => \$paynum,
1118 return { 'error' => $error } if $error;
1120 #no error, so order the fee package if applicable...
1121 my $conf = new FS::Conf;
1122 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1123 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1125 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1127 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1129 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1130 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1133 #and generate an invoice for it now too
1134 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1135 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1140 $cust_main->apply_payments;
1142 if ( $validate->{'save'} ) {
1143 my $new = new FS::cust_main { $cust_main->hash };
1144 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1145 $new->set( $_ => $validate->{$_} )
1146 foreach qw( payname paystart_month paystart_year payissue payip );
1147 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1149 my $bill_location = FS::cust_location->new({
1150 map { $_ => $validate->{$_} }
1151 qw(address1 address2 city state country zip)
1153 $new->set('bill_location' => $bill_location);
1154 # but don't allow the service address to change this way.
1156 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1157 $new->set( $_ => $validate->{$_} )
1158 foreach qw( payname payip paytype paystate
1159 stateid stateid_state );
1160 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1162 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1163 $new->set( 'paydate' => $validate->{'paydate'} );
1164 my $error = $new->replace($cust_main);
1166 #no, this causes customers to process their payments again
1167 #return { 'error' => $error };
1168 #XXX just warn verosely for now so i can figure out how these happen in
1169 # the first place, eventually should redirect them to the "change
1170 #address" page but indicate the payment did process??
1171 delete($validate->{'payinfo'}); #don't want to log this!
1172 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1173 "NEW: ". Dumper($new)."\n".
1174 "OLD: ". Dumper($cust_main)."\n".
1175 "PACKET: ". Dumper($validate)."\n";
1183 my $receipt_html = '';
1185 # currently supported for realtime CC only; send receipt data to SS
1186 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1189 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1192 <TD ALIGN="right">Payment#</TD>
1193 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1197 <TD ALIGN="right">Date</TD>
1199 <TD BGCOLOR="#FFFFFF"><B>! .
1200 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1206 <TD ALIGN="right">Amount</TD>
1207 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1212 <TD ALIGN="right">Payment method</TD>
1213 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1224 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1228 'amount' => sprintf('%.2f', $cust_pay->paid),
1229 'date' => $cust_pay->_date,
1230 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1231 'time_pretty' => time2str('%T', $cust_pay->_date),
1232 'auth_num' => $auth,
1233 'order_num' => $order,
1234 'receipt_html' => $receipt_html,
1241 'receipt_html' => '',
1248 sub realtime_collect {
1251 my $session = _cache->get($p->{'session_id'})
1252 or return { 'error' => "Can't resume session" }; #better error message
1254 my $custnum = $session->{'custnum'};
1256 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1257 or return { 'error' => "unknown custnum $custnum" };
1260 if ( $p->{'amount'} ) {
1261 $amount = $p->{'amount'};
1263 elsif ( $session->{'pkgnum'} ) {
1264 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1267 $amount = $cust_main->balance;
1270 my $error = $cust_main->realtime_collect(
1271 'method' => $p->{'method'},
1272 'amount' => $amount,
1273 'pkgnum' => $session->{'pkgnum'},
1274 'session_id' => $p->{'session_id'},
1278 return { 'error' => $error } unless ref( $error );
1280 return { 'error' => '', amount => $amount, %$error };
1283 sub start_thirdparty {
1285 my $session = _cache->get($p->{'session_id'})
1286 or return { 'error' => "Can't resume session" }; #better error message
1287 my $custnum = $session->{'custnum'};
1288 my $cust_main = FS::cust_main->by_key($custnum);
1290 my $amount = $p->{'amount'}
1291 or return { error => 'no amount' };
1293 my $result = $cust_main->create_payment(
1294 'method' => $p->{'method'},
1295 'amount' => $p->{'amount'},
1296 'pkgnum' => $session->{'pkgnum'},
1297 'session_id' => $p->{'session_id'},
1300 if ( ref($result) ) { # hashref or error
1303 return { error => $result };
1307 sub finish_thirdparty {
1309 my $session_id = delete $p->{'session_id'};
1310 my $session = _cache->get($session_id)
1311 or return { 'error' => "Can't resume session" };
1312 my $custnum = $session->{'custnum'};
1313 my $cust_main = FS::cust_main->by_key($custnum);
1315 if ( $p->{_cancel} ) {
1316 # customer backed out of making a payment
1317 return $cust_main->cancel_payment( $session_id );
1319 my $result = $cust_main->execute_payment( $session_id, %$p );
1320 if ( ref($result) ) {
1323 return { error => $result };
1327 sub process_payment_order_pkg {
1330 my $hr = process_payment($p);
1331 return $hr if $hr->{'error'};
1336 sub process_payment_order_renew {
1339 my $hr = process_payment($p);
1340 return $hr if $hr->{'error'};
1345 sub process_prepay {
1349 my $session = _cache->get($p->{'session_id'})
1350 or return { 'error' => "Can't resume session" }; #better error message
1354 my $custnum = $session->{'custnum'};
1356 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1357 or return { 'error' => "unknown custnum $custnum" };
1359 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1360 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1368 return { 'error' => $error } if $error;
1370 return { 'error' => '',
1371 'amount' => $amount,
1372 'seconds' => $seconds,
1373 'duration' => duration_exact($seconds),
1374 'upbytes' => $upbytes,
1375 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1376 'downbytes' => $downbytes,
1377 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1378 'totalbytes'=> $totalbytes,
1379 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1386 my $session = _cache->get($p->{'session_id'})
1387 or return { 'error' => "Can't resume session" }; #better error message
1389 my $custnum = $session->{'custnum'};
1391 my $invnum = $p->{'invnum'};
1393 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1394 'custnum' => $custnum } )
1395 or return { 'error' => "Can't find invnum" };
1399 return { 'error' => '',
1400 'invnum' => $invnum,
1401 'invoice_text' => join('', $cust_bill->print_text ),
1402 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1409 my $session = _cache->get($p->{'session_id'})
1410 or return { 'error' => "Can't resume session" }; #better error message
1412 my $custnum = $session->{'custnum'};
1414 my $invnum = $p->{'invnum'};
1416 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1417 'custnum' => $custnum } )
1418 or return { 'error' => "Can't find invnum" };
1422 return { 'error' => '',
1423 'invnum' => $invnum,
1424 'invoice_pdf' => $cust_bill->print_pdf({
1425 'unsquelch_cdr' => 1,
1426 'locale' => $p->{'locale'},
1432 sub legacy_invoice {
1434 my $session = _cache->get($p->{'session_id'})
1435 or return { 'error' => "Can't resume session" }; #better error message
1437 my $custnum = $session->{'custnum'};
1439 my $legacyinvnum = $p->{'legacyinvnum'};
1442 'legacyinvnum' => $legacyinvnum,
1443 'custnum' => $custnum,
1446 my $legacy_cust_bill =
1447 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1448 || qsearchs('legacy_cust_bill', \%hash )
1449 or return { 'error' => "Can't find legacyinvnum" };
1453 return { 'error' => '',
1454 'legacyinvnum' => $legacyinvnum,
1455 'legacyid' => $legacy_cust_bill->legacyid,
1456 'invoice_html' => $legacy_cust_bill->content_html,
1461 sub legacy_invoice_pdf {
1463 my $session = _cache->get($p->{'session_id'})
1464 or return { 'error' => "Can't resume session" }; #better error message
1466 my $custnum = $session->{'custnum'};
1468 my $legacyinvnum = $p->{'legacyinvnum'};
1470 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1471 'legacyinvnum' => $legacyinvnum,
1472 'custnum' => $custnum,
1473 }) or return { 'error' => "Can't find legacyinvnum" };
1477 return { 'error' => '',
1478 'legacyinvnum' => $legacyinvnum,
1479 'legacyid' => $legacy_cust_bill->legacyid,
1480 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1488 #sessioning for this? how do we get the session id to the backend invoice
1489 # template so it can add it to the link, blah
1492 if ( $p->{'invnum'} ) {
1493 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1494 or return { 'error' => 'unknown invnum' };
1495 $agentnum = $cust_bill->cust_main->agentnum;
1498 my $templatename = $p->{'template'} || $p->{'templatename'};
1500 #false laziness-ish w/view/cust_bill-logo.cgi
1502 my $conf = new FS::Conf;
1503 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1504 $templatename = "_$1";
1509 my $filename = "logo$templatename.png";
1511 return { 'error' => '',
1512 'logo' => $conf->config_binary($filename, $agentnum),
1513 'content_type' => 'image/png', #should allow gif, jpg too
1520 my $session = _cache->get($p->{'session_id'})
1521 or return { 'error' => "Can't resume session" }; #better error message
1523 my $custnum = $session->{'custnum'};
1525 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1526 or return { 'error' => "unknown custnum $custnum" };
1528 my $conf = new FS::Conf;
1530 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1532 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1536 return { 'error' => '',
1537 'balance' => $cust_main->balance,
1540 my $owed = $_->owed;
1542 +{ 'invnum' => $_->invnum,
1543 '_date' => $_->_date,
1544 'date' => time2str("%b %o, %Y", $_->_date),
1545 'date_short' => time2str("%m-%d-%Y", $_->_date),
1546 'previous' => sprintf('%.2f', ($_->previous)[0]),
1547 'charged' => sprintf('%.2f', $_->charged),
1548 'owed' => sprintf('%.2f', $owed),
1549 'balance' => sprintf('%.2f', $balance),
1554 'legacy_invoices' => [
1556 +{ 'legacyinvnum' => $_->legacyinvnum,
1557 'legacyid' => $_->legacyid,
1558 '_date' => $_->_date,
1559 'date' => time2str("%b %o, %Y", $_->_date),
1560 'date_short' => time2str("%m-%d-%Y", $_->_date),
1561 'charged' => sprintf('%.2f', $_->charged),
1562 'has_content' => ( length($_->content_pdf)
1563 || length($_->content_html) ),
1573 my $session = _cache->get($p->{'session_id'})
1574 or return { 'error' => "Can't resume session" }; #better error message
1576 my $custnum = $session->{'custnum'};
1578 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1579 or return { 'error' => "unknown custnum $custnum" };
1581 my @errors = $cust_main->cancel( 'quiet'=>1 );
1583 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1585 return { 'error' => $error };
1592 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1593 return { 'error' => $session } if $context eq 'error';
1595 my $search = { 'custnum' => $custnum };
1596 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1597 my $cust_main = qsearchs('cust_main', $search )
1598 or return { 'error' => "unknown custnum $custnum" };
1600 my $conf = new FS::Conf;
1602 # the duplication below is necessary:
1603 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1604 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1605 # non-backwards-compatible change breaking the software of anyone using the API
1606 # instead of the stock selfservice
1607 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1608 if( $conf->exists('selfservice_server-view-wholesale') ) {
1609 return { 'svcnum' => $session->{'svcnum'},
1610 'custnum' => $custnum,
1611 'cust_pkg' => [ map {
1613 part_pkg => [ map $_->hashref, $_->part_pkg ],
1615 [ map $_->hashref, $_->available_part_svc ],
1617 [ map { my $ref = { $_->hash,
1618 label => [ $_->label ],
1620 $ref->{_password} = $_->svc_x->_password
1621 if $context eq 'agent'
1622 && $conf->exists('agent-showpasswords')
1623 && $_->part_svc->svcdb eq 'svc_acct';
1628 } $cust_main->cust_pkg
1631 small_custview( $cust_main, $conf->config('countrydefault') ),
1632 'wholesale_view' => 1,
1633 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1634 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1635 'lnp' => $conf->exists('svc_phone-lnp'),
1639 { 'svcnum' => $session->{'svcnum'},
1640 'custnum' => $custnum,
1641 'cust_pkg' => [ map {
1642 my $primary_cust_svc = $_->primary_cust_svc;
1645 pkg_label => $_->pkg_locale,
1646 status => $_->status,
1647 statuscolor => $_->statuscolor,
1649 [ map { $_->hashref }
1650 grep { $_->selfservice_access ne 'hidden' }
1651 $_->available_part_svc
1654 [ map { my $ref = { $_->hash,
1655 label => [ $_->label ],
1657 $ref->{_password} = $_->svc_x->_password
1658 if $context eq 'agent'
1659 && $conf->exists('agent-showpasswords')
1660 && $_->part_svc->svcdb eq 'svc_acct';
1661 $ref->{svchash} = { $_->svc_x->hash } if
1662 $_->part_svc->svcdb eq 'svc_phone';
1663 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1664 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1667 grep { $_->part_svc->selfservice_access ne 'hidden' }
1672 ? { $primary_cust_svc->hash,
1673 label => [ $primary_cust_svc->label ],
1674 finger => $primary_cust_svc->svc_x->finger, #uuh
1675 $primary_cust_svc->part_svc->hash,
1679 } $cust_main->ncancelled_pkgs
1682 small_custview( $cust_main, $conf->config('countrydefault') ),
1683 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1691 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1692 return { 'error' => $session } if $context eq 'error';
1694 my $search = { 'custnum' => $custnum };
1695 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1696 my $cust_main = qsearchs('cust_main', $search )
1697 or return { 'error' => "unknown custnum $custnum" };
1699 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1700 if ( ! $pkgnum && $p->{'svcnum'} ) {
1701 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1702 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1706 my @cust_pkg_usage = ();
1707 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1708 foreach my $cust_pkg ( $p->{'ncancelled'}
1709 ? $cust_main->ncancelled_pkgs
1710 : $cust_main->unsuspended_pkgs ) {
1711 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1712 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1713 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1716 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1718 foreach (@cust_pkg_usage) {
1719 my $part = $_->part_pkg_usage;
1720 my $tag = $part->description . ($part->shared ? 1 : 0);
1721 my $row = $usage_pools{$tag}
1722 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1723 $row->[1] += $_->minutes; # minutes remaining
1724 $row->[2] += $part->minutes; # minutes total
1727 if ( $p->{'svcdb'} ) {
1728 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1730 : ref($p->{'svcdb'}) eq 'ARRAY'
1731 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1732 : { $p->{'svcdb'} => 1 };
1733 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1736 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1739 my $conf = new FS::Conf;
1742 'svcnum' => $session->{'svcnum'},
1743 'custnum' => $custnum,
1744 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1745 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1748 my $svc_x = $_->svc_x;
1749 my($label, $value) = $_->label;
1750 my $part_svc = $_->part_svc;
1751 my $svcdb = $part_svc->svcdb;
1752 my $cust_pkg = $_->cust_pkg;
1753 my $part_pkg = $cust_pkg->part_pkg;
1756 'svcnum' => $_->svcnum,
1757 'display_svcnum' => $_->display_svcnum,
1761 'pkg_label' => $cust_pkg->pkg_locale,
1762 'pkg_status' => $cust_pkg->status,
1763 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1766 if ( $svcdb eq 'svc_acct' ) {
1769 'username' => $svc_x->username,
1770 'email' => $svc_x->email,
1771 'finger' => $svc_x->finger,
1772 'seconds' => $svc_x->seconds,
1773 'upbytes' => display_bytecount($svc_x->upbytes),
1774 'downbytes' => display_bytecount($svc_x->downbytes),
1775 'totalbytes' => display_bytecount($svc_x->totalbytes),
1777 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1778 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1779 'recharge_upbytes' =>
1780 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1781 'recharge_downbytes' =>
1782 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1783 'recharge_totalbytes' =>
1784 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1788 } elsif ( $svcdb eq 'svc_dsl' ) {
1789 $hash{'phonenum'} = $svc_x->phonenum;
1790 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1791 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1792 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1795 $hash{'name'} = $cust_main->name;
1797 } elsif ( $svcdb eq 'svc_phone' ) {
1798 # could potentially show lots of things...
1799 $hash{'outbound'} = 1;
1800 $hash{'inbound'} = 0;
1801 if ( $part_pkg->plan eq 'voip_inbound' ) {
1802 $hash{'outbound'} = 0;
1803 $hash{'inbound'} = 1;
1804 } elsif ( $part_pkg->option('selfservice_inbound_format')
1805 or $conf->config('selfservice-default_inbound_cdr_format')
1807 $hash{'inbound'} = 1;
1809 foreach (qw(inbound outbound)) {
1810 # hmm...we can't filter by status here, because there might
1811 # not be cdr_terminations at all. have to go by date.
1812 # find all since the last bill date.
1813 # XXX cdr types? we are going to need them.
1815 my $sum_cdr = $svc_x->sum_cdrs(
1816 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1817 'begin' => ($cust_pkg->last_bill || 0),
1820 $hash{$_} = $sum_cdr->hashref;
1825 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1836 map { $usage_pools{$_} }
1844 sub _customer_svc_x {
1845 my($custnum, $svcnum, $table) = (shift, shift, shift);
1846 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1848 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1849 my $search = " AND custnum = $1";
1850 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1853 'table' => ($table || 'svc_acct'),
1854 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1855 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1856 #'LEFT JOIN cust_main USING ( custnum ) ',
1857 'hashref' => $hashref,
1858 'extra_sql' => $search, #important
1863 sub svc_status_html {
1866 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1867 return { 'error' => $session } if $context eq 'error';
1869 #XXX only svc_dsl for now
1870 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1871 or return { 'error' => "Service not found" };
1873 my $html = $svc_x->getstatus_html;
1875 return { 'html' => $html };
1879 sub svc_status_hash {
1882 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1883 return { 'error' => $session } if $context eq 'error';
1885 #XXX only svc_acct for now
1886 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1887 or return { 'error' => "Service not found" };
1889 my ( $html, $hashref ) = $svc_x->export_getstatus;
1894 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1895 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1896 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1897 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1898 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1901 my( $p, $method ) = @_;
1903 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1904 return { 'error' => $session } if $context eq 'error';
1906 #XXX only svc_acct for now
1907 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1908 or return { 'error' => "Service not found" };
1910 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1912 my $error = $svc_x->$method($p); #$p? returns error?
1913 return { 'error' => $error } if $error;
1915 return {}; #? { 'error' => '' }
1919 sub acct_forward_info {
1922 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1923 return { 'error' => $session } if $context eq 'error';
1925 my $svc_forward = _customer_svc_x( $custnum,
1926 { 'srcsvc' => $p->{'svcnum'} },
1929 or return { 'error' => '',
1933 return { 'error' => '',
1934 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1939 sub process_acct_forward {
1941 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1942 return { 'error' => $session } if $context eq 'error';
1944 my $old = _customer_svc_x( $custnum,
1945 { 'srcsvc' => $p->{'svcnum'} },
1949 if ( $p->{'dst'} eq '' ) {
1951 my $error = $old->delete;
1952 return { 'error' => $error };
1954 return { 'error' => '' };
1957 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1958 'dst' => $p->{'dst'},
1963 $new->svcnum($old->svcnum);
1964 my $cust_svc = $old->cust_svc;
1965 $new->svcpart($old->svcpart);
1966 $new->pkgnuym($old->pkgnum);
1967 $error = $new->replace($old);
1969 my $conf = new FS::Conf;
1970 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1972 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1973 or return { 'error' => 'No service' }; #how would we even get here?
1975 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1977 $error = $new->insert;
1980 return { 'error' => $error };
1984 sub list_dsl_devices {
1987 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1988 return { 'error' => $session } if $context eq 'error';
1990 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1991 or return { 'error' => "Service not found" };
1994 'devices' => [ map {
1995 +{ 'mac_addr' => $_->mac_addr };
1996 } $svc_dsl->dsl_device
2002 sub add_dsl_device {
2005 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2006 return { 'error' => $session } if $context eq 'error';
2008 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2009 or return { 'error' => "Service not found" };
2011 return { 'error' => 'No MAC address supplied' }
2012 unless length($p->{'mac_addr'});
2014 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2015 'mac_addr' => scalar($p->{'mac_addr'}),
2017 my $error = $dsl_device->insert;
2018 return { 'error' => $error };
2022 sub delete_dsl_device {
2025 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2026 return { 'error' => $session } if $context eq 'error';
2028 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2029 or return { 'error' => "Service not found" };
2031 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2032 'mac_addr' => scalar($p->{'mac_addr'}),
2035 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2037 my $error = $dsl_device->delete;
2038 return { 'error' => $error };
2044 _usage_details( \&_port_graph, $p,
2045 'svcdb' => 'svc_port',
2050 my($svc_port, $begin, $end) = @_;
2052 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2053 push @usage, { 'png' => $pngOrError };
2057 sub _list_svc_usage {
2058 my($svc_acct, $begin, $end) = @_;
2060 foreach my $part_export (
2061 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2062 qw( sqlradius sqlradius_withdomain )
2064 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2069 sub list_svc_usage {
2070 _usage_details(\&_list_svc_usage, @_);
2073 sub _list_support_usage {
2074 my($svc_acct, $begin, $end) = @_;
2076 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2077 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2079 push @usage, { 'seconds' => $_->seconds,
2080 'support' => $_->support,
2081 '_date' => $_->_date,
2082 'id' => $_->transaction_id,
2083 'creator' => $_->creator,
2084 'subject' => $_->subject,
2085 'status' => $_->status,
2086 'ticketid' => $_->ticketid,
2092 sub list_support_usage {
2093 _usage_details(\&_list_support_usage, @_);
2096 sub _list_cdr_usage {
2097 # XXX CDR type support...
2098 # XXX any way to do a paged search on this?
2099 # we have to return the results all at once...
2100 my($svc_phone, $begin, $end, %opt) = @_;
2101 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2102 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, %opt );
2105 sub list_cdr_usage {
2107 _usage_details( \&_list_cdr_usage, $p,
2108 'svcdb' => 'svc_phone',
2112 sub _usage_details {
2113 my($callback, $p, %opt) = @_;
2115 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2116 return { 'error' => $session } if $context eq 'error';
2118 my $search = { 'svcnum' => $p->{'svcnum'} };
2119 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2121 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2123 my $svc_x = qsearchs( $svcdb, $search );
2124 return { 'error' => 'No service selected in list_svc_usage' }
2127 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2128 my $freq = $cust_pkg->part_pkg->freq;
2131 if ( $svcdb eq 'svc_phone' ) {
2132 my $conf = FS::Conf->new;
2134 if ( $p->{inbound} ) {
2135 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2136 || $conf->config('selfservice-default_inbound_cdr_format')
2137 || 'source_default';
2138 $callback_opt{inbound} = 1;
2140 $format = $cust_pkg->part_pkg->option('selfservice_format')
2141 || $conf->config('selfservice-default_cdr_format')
2145 $callback_opt{format} = $format;
2146 $callback_opt{use_clid} = 1;
2147 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2150 my $start = $cust_pkg->setup;
2151 #my $end = $cust_pkg->bill; # or time?
2154 unless ( $p->{beginning} ) {
2155 $p->{beginning} = $cust_pkg->last_bill;
2156 $p->{ending} = $end;
2159 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2160 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2162 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2166 #kinda false laziness with FS::cust_main::bill, but perhaps
2167 #we should really change this bit to DateTime and DateTime::Duration
2169 #change this bit to use Date::Manip? CAREFUL with timezones (see
2170 # mailing list archive)
2171 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2172 (localtime($p->{ending}) )[0,1,2,3,4,5];
2173 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2174 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2176 if ( $freq =~ /^\d+$/ ) {
2178 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2180 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2181 } elsif ( $freq =~ /^(\d+)w$/ ) {
2183 $nmday += $weeks * 7;
2184 $pmday -= $weeks * 7;
2185 } elsif ( $freq =~ /^(\d+)d$/ ) {
2189 } elsif ( $freq =~ /^(\d+)h$/ ) {
2194 return { 'error' => "unparsable frequency: ". $freq };
2197 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2198 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2202 'svcnum' => $p->{svcnum},
2203 'beginning' => $p->{beginning},
2204 'ending' => $p->{ending},
2205 'inbound' => $p->{inbound},
2206 'previous' => ($previous > $start) ? $previous : $start,
2207 'next' => ($next < $end) ? $next : $end,
2208 'header' => $header,
2216 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2217 return { 'error' => $session } if $context eq 'error';
2219 my $search = { 'custnum' => $custnum };
2220 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2221 my $cust_main = qsearchs('cust_main', $search )
2222 or return { 'error' => "unknown custnum $custnum" };
2224 my $status = $cust_main->status;
2225 #false laziness w/ClientAPI/Signup.pm
2227 my $cust_pkg = new FS::cust_pkg ( {
2228 'custnum' => $custnum,
2229 'pkgpart' => $p->{'pkgpart'},
2231 my $error = $cust_pkg->check;
2232 return { 'error' => $error } if $error;
2235 unless ( $p->{'svcpart'} eq 'none' ) {
2239 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2241 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2242 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2243 $svcdb = $part_svc->svcdb;
2245 $svcdb = 'svc_acct';
2247 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2250 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2251 'svc_domain' => [ qw( domain ) ],
2252 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2253 'svc_external' => [ qw( id title ) ],
2254 'svc_pbx' => [ qw( id title ) ],
2257 my $svc_x = "FS::$svcdb"->new( {
2258 'svcpart' => $svcpart,
2259 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2262 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2265 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2266 my $acct_snarf = new FS::acct_snarf ( {
2267 'machine' => $p->{"snarf_machine$snarfnum"},
2268 'protocol' => $p->{"snarf_protocol$snarfnum"},
2269 'username' => $p->{"snarf_username$snarfnum"},
2270 '_password' => $p->{"snarf_password$snarfnum"},
2273 push @acct_snarf, $acct_snarf;
2275 $svc_x->child_objects( \@acct_snarf );
2278 my $y = $svc_x->setdefault; # arguably should be in new method
2279 return { 'error' => $y } if $y && !ref($y);
2281 $error = $svc_x->check;
2282 return { 'error' => $error } if $error;
2289 tie my %hash, 'Tie::RefHash';
2290 %hash = ( $cust_pkg => \@svc );
2292 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2293 return { 'error' => $error } if $error;
2295 my $conf = new FS::Conf;
2296 if ( $conf->exists('signup_server-realtime') ) {
2298 my $bill_error = _do_bop_realtime( $cust_main, $status );
2301 $cust_pkg->cancel('quiet'=>1);
2304 $cust_pkg->reexport;
2308 $cust_pkg->reexport;
2311 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2313 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2320 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2321 return { 'error' => $session } if $context eq 'error';
2323 my $search = { 'custnum' => $custnum };
2324 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2325 my $cust_main = qsearchs('cust_main', $search )
2326 or return { 'error' => "unknown custnum $custnum" };
2328 my $status = $cust_main->status;
2329 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2330 or return { 'error' => "unknown package $p->{pkgnum}" };
2332 #if someone does need self-service package change of suspended packages,
2333 # figure out how to be more discriminating
2334 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2335 if $cust_pkg->status eq 'suspended';
2338 my $error = FS::cust_pkg::order( $custnum,
2344 my $conf = new FS::Conf;
2345 if ( $conf->exists('signup_server-realtime') ) {
2347 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2350 $newpkg[0]->suspend;
2353 $newpkg[0]->reexport;
2357 $newpkg[0]->reexport;
2360 return { error => '', pkgnum => $cust_pkg->pkgnum };
2364 sub order_recharge {
2367 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2368 return { 'error' => $session } if $context eq 'error';
2370 my $search = { 'custnum' => $custnum };
2371 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2372 my $cust_main = qsearchs('cust_main', $search )
2373 or return { 'error' => "unknown custnum $custnum" };
2375 my $status = $cust_main->status;
2376 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2377 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2379 my $svc_x = $cust_svc->svc_x;
2380 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2383 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2384 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2385 recharge_totalbytes );
2386 my $amount = $part_pkg->option('recharge_amount', 1);
2388 my ($l, $v, $d) = $cust_svc->label; # blah
2389 my $pkg = "Recharge $v";
2391 my $bill_error = $cust_main->charge($amount, $pkg,
2392 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2393 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2394 $part_pkg->taxclass); #meh
2396 my $conf = new FS::Conf;
2397 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2399 $bill_error = _do_bop_realtime( $cust_main, $status );
2404 my $error = $svc_x->recharge (\%vhash);
2405 return { 'error' => $error } if $error;
2409 my $error = $bill_error;
2410 $error ||= $svc_x->recharge (\%vhash);
2411 return { 'error' => $error } if $error;
2414 return { error => '', svc => $cust_svc->part_svc->svc };
2418 sub _do_bop_realtime {
2419 my ($cust_main, $status, %opt) = @_;
2421 my $old_balance = $cust_main->balance;
2423 my $bill_error = $cust_main->bill
2424 || $cust_main->apply_payments_and_credits;
2426 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2427 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2429 if ( $cust_main->balance > $old_balance
2430 && $cust_main->balance > 0
2431 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2432 || $status eq 'suspended'
2436 unless ( $opt{'no_credit'} ) {
2437 #this makes sense. credit is "un-doing" the invoice
2438 my $conf = new FS::Conf;
2439 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2440 'self-service decline',
2441 reason_type=>$conf->config('signup_credit_type'),
2443 $cust_main->apply_credits( 'order' => 'newest' );
2446 return { 'error' => '_decline', 'bill_error' => $bill_error };
2455 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2456 return { 'error' => $session } if $context eq 'error';
2458 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2459 or return { 'error' => "unknown custnum $custnum" };
2461 my @cust_pkg = sort { $a->bill <=> $b->bill }
2462 grep { $_->part_pkg->freq ne '0' }
2463 $cust_main->ncancelled_pkgs;
2465 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2467 my $total = $cust_main->balance;
2470 my $bill = $_->bill;
2471 $total += $_->part_pkg->base_recur($_, \$bill);
2472 my $renew_date = $_->part_pkg->add_freq($_->bill);
2474 'pkgnum' => $_->pkgnum,
2475 'amount' => sprintf('%.2f', $total),
2476 'bill_date' => $_->bill,
2477 'bill_date_pretty' => time2str('%x', $_->bill),
2478 'renew_date' => $renew_date,
2479 'renew_date_pretty' => time2str('%x', $renew_date),
2480 'expire_date' => $_->expire,
2481 'expire_date_pretty' => time2str('%x', $_->expire),
2486 return { 'dates' => \@array };
2490 sub payment_info_renew_info {
2492 my $renew_info = renew_info($p);
2493 my $payment_info = payment_info($p);
2494 return { %$renew_info,
2502 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2503 return { 'error' => $session } if $context eq 'error';
2505 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2506 or return { 'error' => "unknown custnum $custnum" };
2508 my $date = $p->{'date'};
2512 #freeside-daily -n -d $date fs_daily $custnum
2513 $cust_main->bill_and_collect( 'time' => $date,
2514 'invoice_time' => $now,
2515 'actual_time' => $now,
2516 'check_freq' => '1d',
2519 return { 'error' => '' };
2525 my $session = _cache->get($p->{'session_id'})
2526 or return { 'error' => "Can't resume session" }; #better error message
2528 my $custnum = $session->{'custnum'};
2530 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2531 or return { 'error' => "unknown custnum $custnum" };
2533 my $conf = new FS::Conf;
2535 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2536 or return { 'error' => 'Permission denied' };
2538 my $pkgnum = $p->{'pkgnum'};
2540 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2541 'pkgnum' => $pkgnum, } )
2542 or return { 'error' => "unknown pkgnum $pkgnum" };
2544 my $error = $cust_pkg->suspend(reason => $reasonnum);
2545 return { 'error' => $error };
2551 my $session = _cache->get($p->{'session_id'})
2552 or return { 'error' => "Can't resume session" }; #better error message
2554 my $custnum = $session->{'custnum'};
2556 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2557 or return { 'error' => "unknown custnum $custnum" };
2559 my $pkgnum = $p->{'pkgnum'};
2561 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2562 'pkgnum' => $pkgnum, } )
2563 or return { 'error' => "unknown pkgnum $pkgnum" };
2565 my $error = $cust_pkg->cancel('quiet' => 1);
2566 return { 'error' => $error };
2570 sub provision_phone {
2573 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2575 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2576 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2577 return { 'error' => $session } if $context eq 'error';
2579 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2580 return { 'error' => 'service not found' } unless $svc_phone;
2581 return { 'error' => 'invalid svcnum' }
2582 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2584 $svc_phone->email($p->{'email'})
2585 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2586 $svc_phone->forwarddst($p->{'forwarddst'})
2587 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2588 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2589 return { 'error' => $svc_phone->replace };
2593 unless($p->{'lnp'}) {
2594 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2595 $p->{'lnp_status'} = "portingin";
2596 return _provision( 'FS::svc_phone',
2597 [qw(lnp_desired_due_date lnp_other_provider
2598 lnp_other_provider_account phonenum countrycode lnp_status)],
2599 [qw(phonenum countrycode)],
2606 unless (scalar(@bulkdid)) {
2607 return _provision( 'FS::svc_phone',
2608 [qw(phonenum countrycode)],
2609 [qw(phonenum countrycode)],
2615 # bulk DID order case
2617 foreach my $did ( @bulkdid ) {
2618 $did =~ s/[^0-9]//g;
2619 $error = _provision( 'FS::svc_phone',
2620 [qw(phonenum countrycode)],
2621 [qw(phonenum countrycode)],
2623 'pkgnum' => $p->{'pkgnum'},
2624 'svcpart' => $p->{'svcpart'},
2626 'countrycode' => $p->{'countrycode'},
2627 'session_id' => $p->{'session_id'},
2630 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2632 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2635 sub provision_acct {
2637 warn "provision_acct called\n"
2640 return { 'error' => gettext('passwords_dont_match') }
2641 if $p->{'_password'} ne $p->{'_password2'};
2642 return { 'error' => gettext('empty_password') }
2643 unless length($p->{'_password'});
2645 if ($p->{'domsvc'}) {
2646 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2647 qw ( svcpart pkgnum ) );
2648 return { 'error' => gettext('invalid_domain') }
2649 unless ($domains{$p->{'domsvc'}});
2652 warn "provision_acct calling _provision\n"
2654 _provision( 'FS::svc_acct',
2655 [qw(username _password domsvc)],
2656 [qw(username _password domsvc)],
2662 sub provision_external {
2664 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2665 _provision( 'FS::svc_external',
2674 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2675 warn "_provision called for $class\n"
2678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2679 return { 'error' => $session } if $context eq 'error';
2681 my $search = { 'custnum' => $custnum };
2682 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2683 my $cust_main = qsearchs('cust_main', $search )
2684 or return { 'error' => "unknown custnum $custnum" };
2686 my $pkgnum = $p->{'pkgnum'};
2688 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2690 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2691 'pkgnum' => $pkgnum,
2693 or return { 'error' => "unknown pkgnum $pkgnum" };
2695 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2697 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2698 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2700 warn "creating $class record\n"
2702 my $svc_x = $class->new( {
2703 'pkgnum' => $p->{'pkgnum'},
2704 'svcpart' => $p->{'svcpart'},
2705 map { $_ => $p->{$_} } @$fields
2707 warn "inserting $class record\n"
2709 my $error = $svc_x->insert;
2712 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2714 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2717 my $return = { 'svc' => $part_svc->svc,
2719 map { $_ => $svc_x->get($_) } @$return_fields
2721 warn "_provision returning ". Dumper($return). "\n"
2730 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2731 return { 'error' => $session } if $context eq 'error';
2733 my $search = { 'custnum' => $custnum };
2734 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2735 my $cust_main = qsearchs('cust_main', $search )
2736 or return { 'error' => "unknown custnum $custnum" };
2738 my $pkgnum = $p->{'pkgnum'};
2740 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2741 'pkgnum' => $pkgnum,
2743 or return { 'error' => "unknown pkgnum $pkgnum" };
2745 my $svcpart = $p->{'svcpart'};
2747 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2748 'svcpart' => $svcpart, } )
2749 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2750 my $part_svc = $pkg_svc->part_svc;
2752 my $conf = new FS::Conf;
2755 'svc' => $part_svc->svc,
2756 'svcdb' => $part_svc->svcdb,
2757 'pkgnum' => $pkgnum,
2758 'svcpart' => $svcpart,
2759 'custnum' => $custnum,
2761 'security_phrase' => 0, #XXX !
2762 'svc_acct_pop' => [], #XXX !
2764 'init_popstate' => '',
2769 small_custview( $cust_main, $conf->config('countrydefault') ),
2773 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2774 && $ret->{'svcdb'} eq 'svc_phone') {
2775 $ret->{'svcnum'} = $p->{'svcnum'};
2776 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2777 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2778 $ret->{'email'} = $svc_phone->email;
2779 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2786 sub unprovision_svc {
2789 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2790 return { 'error' => $session } if $context eq 'error';
2792 my $search = { 'custnum' => $custnum };
2793 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2794 my $cust_main = qsearchs('cust_main', $search )
2795 or return { 'error' => "unknown custnum $custnum" };
2797 my $svcnum = $p->{'svcnum'};
2799 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2800 or return { 'error' => "unknown svcnum $svcnum" };
2802 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2803 unless $cust_svc->cust_pkg->custnum == $custnum;
2805 my $conf = new FS::Conf;
2807 return { 'svc' => $cust_svc->part_svc->svc,
2808 'error' => $cust_svc->cancel,
2810 small_custview( $cust_main, $conf->config('countrydefault') ),
2815 sub myaccount_passwd {
2817 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2818 return { 'error' => $session } if $context eq 'error';
2820 return { 'error' => "New passwords don't match." }
2821 if $p->{'new_password'} ne $p->{'new_password2'};
2823 return { 'error' => 'Enter new password' }
2824 unless length($p->{'new_password'});
2826 #my $search = { 'custnum' => $custnum };
2827 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2828 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2829 my $search = " AND custnum = $1";
2830 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2832 my $svc_acct = qsearchs( {
2833 'table' => 'svc_acct',
2834 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2835 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2836 'LEFT JOIN cust_main USING ( custnum ) ',
2837 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2838 'extra_sql' => $search, #important
2840 or return { 'error' => "Service not found" };
2844 my $conf = new FS::Conf;
2845 $error = 'Password too short.'
2846 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2847 $error = 'Password too long.'
2848 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2850 $svc_acct->set_password($p->{'new_password'});
2851 $error ||= $svc_acct->replace();
2853 #regular pw change in self-service should change contact pw too, otherwise its
2854 #way too confusing. hell its confusing they're separate at all, but alas.
2855 #need to support the "ISP provides email that's used as a contact email" case
2857 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2858 if ( $contact && $contact->custnum == $custnum ) {
2859 #svc_acct was successful but this one returns an error? "shouldn't happen"
2860 $error ||= $contact->change_password($p->{'new_password'});
2863 my($label, $value) = $svc_acct->cust_svc->label;
2865 return { 'error' => $error,
2872 # sub contact_passwd {
2874 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2875 # return { 'error' => $session } if $context eq 'error';
2877 # return { 'error' => 'Not logged in as a contact.' }
2878 # unless $session->{'contactnum'};
2880 # return { 'error' => "New passwords don't match." }
2881 # if $p->{'new_password'} ne $p->{'new_password2'};
2883 # return { 'error' => 'Enter new password' }
2884 # unless length($p->{'new_password'});
2886 # #my $search = { 'custnum' => $custnum };
2887 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2888 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2889 # my $search = " AND selfservice_access IS NOT NULL ".
2890 # " AND selfservice_access = 'Y' ".
2891 # " AND ( disabled IS NULL OR disabled = '' )".
2892 # " AND custnum IS NOT NULL AND custnum = $1";
2893 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2895 # my $contact = qsearchs( {
2896 # 'table' => 'contact',
2897 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2898 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2899 # 'extra_sql' => $search, #important
2901 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2902 # # deleted since then?
2906 # # use these svc_acct length restrictions??
2907 # my $conf = new FS::Conf;
2908 # $error = 'Password too short.'
2909 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2910 # $error = 'Password too long.'
2911 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2913 # $error ||= $contact->change_password($p->{'new_password'});
2915 # return { 'error' => $error, };
2922 my $info = skin_info($p);
2924 my $conf = new FS::Conf;
2925 my $verification = $conf->config('selfservice-password_reset_verification')
2926 or return { %$info, 'error' => 'Password resets disabled' };
2931 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2933 $contact = FS::contact->by_selfservice_email($p->{'email'});
2935 $cust_main = $contact->cust_main if $contact;
2937 #also look for an svc_acct, otherwise it would be super confusing
2939 my($username, $domain) = split('@', $p->{'email'});
2940 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2941 if ( $svc_domain ) {
2942 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2943 'domsvc' => $svc_domain->svcnum }
2946 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2947 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
2949 #precaution: don't change svc_acct password not part of the same
2950 # customer as contact
2951 $svc_acct = '' if ! $cust_pkg
2952 || $cust_pkg->custnum != $cust_main->custnum;
2957 return { %$info, 'error' => 'Email address not found' }
2958 unless $contact || $svc_acct;
2960 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
2962 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2963 or return { %$info, 'error' => 'Account not found' };
2965 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2966 'domsvc' => $svc_domain->svcnum }
2968 or return { %$info, 'error' => 'Account not found' };
2970 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2971 or return { %$info, 'error' => 'Account not found' };
2973 $cust_main = $cust_pkg->cust_main;
2978 'email' => sub { 1; },
2980 my( $p, $cust_main ) = @_;
2981 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2982 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2985 my( $p, $cust_main ) = @_;
2986 my $cust_pay = qsearchs({
2987 'table' => 'cust_pay',
2988 'hashref' => { 'custnum' => $cust_main->custnum },
2989 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2993 $p->{'amount'} == $cust_pay->paid;
2996 my( $p, $cust_main ) = @_;
2997 $p->{'zip'} eq $cust_main->zip
2998 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3002 foreach my $verify ( split(',', $verification) ) {
3004 &{ $verify{$verify} }( $p, $cust_main )
3005 or return { %$info, 'error' => 'Account not found' };
3009 #okay, we're verified
3013 my $error = $contact->send_reset_email(
3014 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3018 return { %$info, 'error' => $error }; #????
3021 } elsif ( $svc_acct ) {
3023 #create a unique session
3025 my $reset_session = {
3026 'svcnum' => $svc_acct->svcnum,
3030 my $timeout = '1 hour'; #?
3032 my $reset_session_id;
3034 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3035 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3038 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3042 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3043 $cust_main->agentnum);
3044 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3045 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3047 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3048 my $error = $msg_template->send( 'cust_main' => $cust_main,
3049 'object' => $svc_acct,
3050 'substitutions' => {
3051 'session_id' => $reset_session_id,
3055 return { %$info, 'error' => $error }; #????
3060 return { %$info, 'error' => '' };
3063 sub check_reset_passwd {
3066 my $conf = new FS::Conf;
3067 my $verification = $conf->config('selfservice-password_reset_verification')
3068 or return { 'error' => 'Password resets disabled' };
3070 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3071 or return { 'error' => "Can't resume session" }; #better error message
3073 if ( $reset_session->{'svcnum'} ) {
3075 my $svcnum = $reset_session->{'svcnum'};
3077 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3078 or return { 'error' => "Service not found" };
3080 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3081 my $info = skin_info($p);
3085 'session_id' => $p->{'session_id'},
3086 'username' => $svc_acct->username,
3089 } elsif ( $reset_session->{'contactnum'} ) {
3091 my $contactnum = $reset_session->{'contactnum'};
3093 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3094 or return { 'error' => "Contact not found" };
3096 my @contact_email = $contact->contact_email;
3097 return { 'error' => 'No contact email' } unless @contact_email;
3099 $p->{'agentnum'} = $contact->cust_main->agentnum;
3100 my $info = skin_info($p);
3104 'session_id' => $p->{'session_id'},
3105 'email' => $contact_email[0]->email, #the first?
3110 return { 'error' => 'No svcnum or contactnum in session' }; #??
3116 sub process_reset_passwd {
3119 my $conf = new FS::Conf;
3120 my $verification = $conf->config('selfservice-password_reset_verification')
3121 or return { 'error' => 'Password resets disabled' };
3123 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3124 or return { 'error' => "Can't resume session" }; #better error message
3129 if ( $reset_session->{'svcnum'} ) {
3131 my $svcnum = $reset_session->{'svcnum'};
3133 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3134 or return { 'error' => "Service not found" };
3136 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3137 $info ||= skin_info($p);
3142 if ( $reset_session->{'contactnum'} ) {
3144 my $contactnum = $reset_session->{'contactnum'};
3146 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3147 or return { 'error' => "Contact not found" };
3149 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3150 $info ||= skin_info($p);
3154 return { %$info, 'error' => "New passwords don't match." }
3155 if $p->{'new_password'} ne $p->{'new_password2'};
3157 return { %$info, 'error' => 'Enter new password' }
3158 unless length($p->{'new_password'});
3162 $svc_acct->set_password($p->{'new_password'});
3163 my $error = $svc_acct->replace();
3165 return { %$info, 'error' => $error } if $error;
3167 #my($label, $value) = $svc_acct->cust_svc->label;
3168 #return { 'error' => $error,
3169 # #'label' => $label,
3170 # #'value' => $value,
3177 my $error = $contact->change_password($p->{'new_password'});
3179 return { %$info, 'error' => $error }; # if $error;
3183 #password changed ,so remove session, don't want it reused
3184 _cache->remove($p->{'session_id'});
3186 return { %$info, 'error' => '' };
3192 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3193 return { 'error' => $session } if $context eq 'error';
3196 if ( $session->{'pkgnum'} ) {
3198 #tickets for specific service with pkg-balances on
3199 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3200 'pkgnum' => $session->{'pkgnum'} })
3201 or return { 'error' => 'unknown package' };
3202 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3203 push @tickets, $cust_svc->tickets( $p->{status} );
3208 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3209 or return { 'error' => "unknown custnum $custnum" };
3211 @tickets = $cust_main->tickets( $p->{status} );
3214 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3215 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3216 my $conf = new FS::Conf;
3217 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3221 ($a->{'_selfservice_priority'} eq '') <=>
3222 ($b->{'_selfservice_priority'} eq '')
3225 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3231 +{ tickets => \@tickets };
3238 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3239 return { 'error' => $session } if $context eq 'error';
3241 # warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3242 # FS::TicketSystem->init();
3244 my $conf = new FS::Conf;
3245 my $queue = $p->{'queue'}
3246 || $conf->config('ticket_system-selfservice_queueid')
3247 || $conf->config('ticket_system-default_queueid');
3249 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3250 my $err_or_ticket = FS::TicketSystem->create_ticket(
3251 '', #create RT session based on FS CurrentUser (fs_selfservice)
3253 'custnum' => $custnum,
3254 'svcnum' => $session->{'svcnum'},
3255 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3258 if ( ref($err_or_ticket) ) {
3259 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3261 return { 'error' => '',
3262 'ticket_id' => $err_or_ticket->id,
3265 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3267 return { 'error' => $err_or_ticket };
3275 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3276 return { 'error' => $session } if $context eq 'error';
3278 return { error => 'requested format not implemented' }
3279 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3281 my $conf = new FS::Conf;
3282 my $age_threshold = 0;
3283 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3284 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3286 my $search = { 'custnum' => $custnum };
3287 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3288 my $cust_main = qsearchs('cust_main', $search )
3289 or return { 'error' => "unknown custnum $custnum" };
3291 # does it make more sense to just run one sql query for this instead of all the
3292 # insanity below? would increase performance greately for large data sets?
3294 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3295 my @part_svc = $cust_pkg->part_svc;
3296 foreach my $part_svc ( @part_svc ) {
3297 if($part_svc->svcdb eq 'svc_phone'){
3298 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3299 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3300 push @svc_phone, $cust_pkg_svc->svc_x
3301 if $cust_pkg_svc->date_inserted >= $age_threshold;
3309 my($xls_r,$xls_c) = (0,0);
3312 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3313 if($p->{'format'} eq 'csv') {
3314 $csv = new Text::CSV_XS { 'always_quote' => 1,
3317 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3318 $content .= $csv->string;
3320 elsif($p->{'format'} eq 'xls') {
3321 my $XLS1 = new IO::Scalar \$content;
3322 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3323 or return { 'error' => "Error opening .xls file: $!" };
3324 $xls = $xls_workbook->add_worksheet('DIDs');
3325 foreach ( @fields ) {
3326 $xls->write(0,$xls_c++,$_);
3331 foreach my $svc_phone ( @svc_phone ) {
3332 my @cols = map { $svc_phone->$_ } @fields;
3333 if($p->{'format'} eq 'csv') {
3334 return { 'error' => 'Unable to create CSV' }
3335 unless $csv->combine(@cols);
3336 $content .= $csv->string;
3338 elsif($p->{'format'} eq 'xls') {
3341 $xls->write($xls_r,$xls_c++,$_);
3347 $xls_workbook->close() if $p->{'format'} eq 'xls';
3349 { content => $content, format => $p->{'format'}, };
3354 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3355 return { 'error' => $session } if $context eq 'error';
3357 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3358 # FS::TicketSystem->init();
3359 # return { 'error' => 'get_ticket configuration error' }
3360 # if $FS::TicketSystem::system ne 'RT_Internal';
3362 # check existence and ownership as part of this
3363 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3364 my $rt_session = FS::TicketSystem->session('');
3365 my $Ticket = FS::TicketSystem->get_ticket_object(
3367 ticket_id => $p->{'ticket_id'},
3370 return { 'error' => 'ticket not found' } if !$Ticket;
3372 if ( length( $p->{'subject'} || '' ) ) {
3374 if ( $p->{'subject'} ne $Ticket->Subject ) {
3375 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3376 return { 'error' => "unable to set subject: $msg" } if !$val;
3380 if(length($p->{'reply'})) {
3381 my @err_or_res = FS::TicketSystem->correspond_ticket(
3383 'ticket_id' => $p->{'ticket_id'},
3384 'content' => $p->{'reply'},
3387 return { 'error' => 'unable to reply to ticket' }
3388 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3391 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3392 my $err_or_ticket = FS::TicketSystem->get_ticket(
3394 'ticket_id' => $p->{'ticket_id'},
3397 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3398 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3400 return { 'error' => $err_or_ticket };
3403 my @custs = @{$err_or_ticket->{'custs'}};
3404 my @txns = @{$err_or_ticket->{'txns'}};
3407 # superseded by check in get_ticket_object
3408 #return { 'error' => 'invalid ticket requested' }
3409 #unless grep($_ eq $custnum, @custs);
3411 foreach my $txn ( @txns ) {
3412 push @filtered_txns, $txn
3413 if ($txn->{'type'} eq 'EmailRecord'
3414 || $txn->{'type'} eq 'Correspond'
3415 || $txn->{'type'} eq 'Create');
3418 warn "$me get_ticket: successful: \n"
3420 return { 'error' => '',
3421 'transactions' => \@filtered_txns,
3422 'ticket_fields' => $err_or_ticket->{'fields'},
3423 'ticket_id' => $p->{'ticket_id'},
3427 sub adjust_ticket_priority {
3429 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3430 return { 'error' => $session } if $context eq 'error';
3432 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3433 # FS::TicketSystem->init;
3434 my $ss_priority = FS::TicketSystem->selfservice_priority;
3436 return { 'error' => 'adjust_ticket_priority configuration error' }
3437 if $FS::TicketSystem::system ne 'RT_Internal'
3440 my $values = $p->{'values'}; #hashref, id => priority value
3443 foreach my $id (keys %$values) {
3444 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3445 my $Ticket = FS::TicketSystem->get_ticket_object('',
3447 'custnum' => $custnum,
3450 $ticket_error{$id} = 'ticket not found';
3454 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3455 # We're not going to implement it for RT_External.
3456 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3457 my $new_value = $values->{$id};
3458 next if $old_value eq $new_value;
3460 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3462 # AddCustomFieldValue works fine (replacing any existing value) if it's
3463 # a single-valued custom field, which it should be. If it's not, you're
3464 # doing something wrong.
3466 if ( length($new_value) ) {
3467 ($val, $msg) = $Ticket->AddCustomFieldValue(
3468 Field => $ss_priority,
3469 Value => $new_value,
3473 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3474 Field => $ss_priority,
3475 Value => $old_value,
3479 $ticket_error{$id} = $msg if !$val;
3480 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3482 return { 'error' => '',
3483 'ticket_error' => \%ticket_error,
3484 %{ customer_info($p) } # send updated customer info back
3490 sub _custoragent_session_custnum {
3493 my($context, $session, $custnum);
3494 if ( $p->{'session_id'} ) {
3496 $context = 'customer';
3497 $session = _cache->get($p->{'session_id'})
3498 or return ( 'error' => "Can't resume session" ); #better error message
3499 $custnum = $session->{'custnum'};
3501 } elsif ( $p->{'agent_session_id'} ) {
3504 my $agent_cache = new FS::ClientAPI_SessionCache( {
3505 'namespace' => 'FS::ClientAPI::Agent',
3507 $session = $agent_cache->get($p->{'agent_session_id'})
3508 or return ( 'error' => "Can't resume session" ); #better error message
3509 $custnum = $p->{'custnum'};
3513 return ( 'error' => "Can't resume session" ); #better error message
3516 ($context, $session, $custnum);