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 = md5_hex(md5_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 my $skin_info = skin_info($p);
312 if ( $p->{'session_id'} ) {
313 _cache->remove($p->{'session_id'});
314 return { %$skin_info, 'error' => '' };
316 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
323 my($context, $session, $custnum) = _custoragent_session_custnum($p);
324 return { 'error' => $session } if $context eq 'error';
326 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
327 or return { 'error' => "Service not found" };
329 $session->{'svcnum'} = $svc_acct->svcnum;
331 my $conf = new FS::Conf;
332 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
333 _cache->set( $p->{'session_id'}, $session, $timeout );
335 return { 'error' => '' };
339 sub payment_gateway {
341 # takes a cust_main and a cust_payby entry, returns the payment_gateway
342 my $conf = new FS::Conf;
343 my $cust_main = shift;
344 my $cust_payby = shift;
345 my $gatewaynum = $conf->config('selfservice-payment_gateway');
347 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
348 die "configured gatewaynum $gatewaynum not found!" if !$pg;
352 return '' if ! FS::payby->realtime($cust_payby);
353 my $pg = $cust_main->agent->payment_gateway(
354 'method' => FS::payby->payby2bop($cust_payby),
364 my $conf = new FS::Conf;
366 my $info = skin_info($p);
368 use vars qw( $cust_paybys ); #cache for performance
369 unless ( $cust_paybys ) {
371 my %cust_paybys = map { $_ => 1 }
372 map { FS::payby->payby2payment($_) }
373 $conf->config('signup_server-payby');
375 $cust_paybys = [ keys %cust_paybys ];
378 $info->{'cust_paybys'} = $cust_paybys;
380 my($context, $session, $custnum) = _custoragent_session_custnum($p);
381 return { 'error' => $session } if $context eq 'error';
383 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
384 or return { 'error' => "unknown custnum $custnum" };
386 $info->{'hide_payment_fields'} = [
388 my $pg = payment_gateway($cust_main, $_);
389 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
390 } @{ $info->{cust_paybys} }
393 $info->{'self_suspend_reason'} =
394 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
396 $info->{'edit_ticket_subject'} =
397 $conf->exists('ticket_system-selfservice_edit_subject') &&
398 $cust_main->edit_subject;
400 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
402 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
405 'custnum' => $custnum,
406 'access_pkgnum' => $session->{'pkgnum'},
407 'access_svcnum' => $session->{'svcnum'},
414 my($context, $session, $custnum) = _custoragent_session_custnum($p);
415 return { 'error' => $session } if $context eq 'error';
419 my $conf = new FS::Conf;
420 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
422 # if ( $FS::TicketSystem::system ) {
423 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
424 # FS::TicketSystem->init();
427 if ( $custnum ) { #customer record
429 %return = ( %return, %{ customer_info_short($p) } );
431 #redundant with customer_info_short, but we need it for several things below
432 my $search = { 'custnum' => $custnum };
433 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
434 my $cust_main = qsearchs('cust_main', $search )
435 or return { 'error' => "unknown custnum $custnum" };
437 my $list_tickets = list_tickets($p);
438 $return{'tickets'} = $list_tickets->{'tickets'};
440 if ( $session->{'pkgnum'} ) {
441 #XXX open invoices in the pkg-balances case
445 invnum => $_->invnum,
446 date => time2str("%b %o, %Y", $_->_date),
449 } $cust_main->open_cust_bill;
450 $return{open_invoices} = \@open;
452 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
453 my $sth = dbh->prepare($sql) or die dbh->errstr;
454 $sth->execute($custnum) or die $sth->errstr;
455 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
456 $return{'last_invoice_date_pretty'} =
457 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
460 #customer_info_short always has nobalance on..
461 $return{small_custview} =
462 small_custview( $cust_main,
463 $return{countrydefault},
464 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
467 $return{has_ship_address} = $cust_main->has_ship_address;
468 $return{status} = $cust_main->status;
469 $return{statuscolor} = $cust_main->statuscolor;
471 # compatibility: some places in selfservice use this to determine
472 # if there's a ship address
473 if ( $return{has_ship_address} ) {
474 $return{ship_last} = $cust_main->last;
475 $return{ship_first} = $cust_main->first;
478 if (scalar($conf->config('support_packages'))) {
479 my @support_services = ();
480 foreach ($cust_main->support_services) {
481 my $seconds = $_->svc_x->seconds || 0;
482 my $time_remaining = (($seconds < 0) ? '-' : '' ).
483 int(abs($seconds)/3600)."h".
484 sprintf("%02d",(abs($seconds)%3600)/60)."m";
485 my $cust_pkg = $_->cust_pkg;
488 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
489 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
490 push @support_services, { svcnum => $_->svcnum,
491 time => $time_remaining,
496 $return{support_services} = \@support_services;
499 if ( $conf->config('prepayment_discounts-credit_type') ) {
501 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
504 } elsif ( $session->{'svcnum'} ) { #no customer record
506 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
507 or die "unknown svcnum";
508 $return{name} = $svc_acct->email;
512 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
516 return { 'error' => '',
517 'custnum' => $custnum,
523 sub customer_info_short {
526 my($context, $session, $custnum) = _custoragent_session_custnum($p);
527 return { 'error' => $session } if $context eq 'error';
531 my $conf = new FS::Conf;
533 if ( $custnum ) { #customer record
535 my $search = { 'custnum' => $custnum };
536 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
537 my $cust_main = qsearchs('cust_main', $search )
538 or return { 'error' => "unknown custnum $custnum" };
540 $return{display_custnum} = $cust_main->display_custnum;
542 if ( $session->{'pkgnum'} ) {
543 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
544 #next_bill_date from cust_pkg?
546 $return{balance} = $cust_main->balance;
547 $return{next_bill_date} = $cust_main->next_bill_date;
548 $return{next_bill_date_pretty} =
549 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
553 $return{countrydefault} = scalar($conf->config('countrydefault'));
555 $return{small_custview} =
556 small_custview( $cust_main,
557 $return{countrydefault},
561 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
563 $return{payby} = $cust_main->payby;
565 #none of these are terribly expensive if we want 'em...
566 for (@cust_main_editable_fields) {
567 $return{$_} = $cust_main->get($_);
569 #maybe a little more expensive, but it should be cached by now
570 for (@location_editable_fields) {
571 $return{$_} = $cust_main->bill_location->get($_);
572 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
575 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
576 $return{payinfo} = $cust_main->paymask;
577 @return{'month', 'year'} = $cust_main->paydate_monthyear;
580 my @invoicing_list = $cust_main->invoicing_list;
581 $return{'invoicing_list'} =
582 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
583 $return{'postal_invoicing'} =
584 0 < ( grep { $_ eq 'POST' } @invoicing_list );
586 if ( $session->{'svcnum'} ) {
587 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
588 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
589 $return{'svcnum'} = $session->{'svcnum'};
592 } elsif ( $session->{'svcnum'} ) { #no customer record
594 #uuh, not supproted yet... die?
595 return { 'error' => 'customer_info_short not yet supported as agent' };
599 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
603 return { 'error' => '',
604 'custnum' => $custnum,
609 sub billing_history {
612 my($context, $session, $custnum) = _custoragent_session_custnum($p);
613 return { 'error' => $session } if $context eq 'error';
615 return { 'error' => 'No customer' } unless $custnum;
617 my $search = { 'custnum' => $custnum };
618 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
619 my $cust_main = qsearchs('cust_main', $search )
620 or return { 'error' => "unknown custnum $custnum" };
624 if ( $session->{'pkgnum'} ) {
625 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
626 #next_bill_date from cust_pkg?
627 return { 'error' => 'No history for package' };
630 $return{balance} = $cust_main->balance;
631 $return{next_bill_date} = $cust_main->next_bill_date;
632 $return{next_bill_date_pretty} =
633 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
638 my $conf = new FS::Conf;
640 if ( $conf->exists('selfservice-billing_history-line_items') ) {
642 foreach my $cust_bill ( $cust_main->cust_bill ) {
645 'type' => 'Line item',
646 'description' => $_->desc( $cust_main->locale ).
647 ( $_->sdate && $_->edate
648 ? ' '. time2str('%d-%b-%Y', $_->sdate).
649 ' To '. time2str('%d-%b-%Y', $_->edate)
652 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
653 'date' => $cust_bill->_date,
654 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
656 foreach $cust_bill->cust_bill_pkg;
664 'description' => 'Invoice #'. $_->display_invnum,
665 'amount' => sprintf('%.2f', $_->charged ),
667 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
669 foreach $cust_main->cust_bill;
675 'description' => 'Payment', #XXX type
676 'amount' => sprintf('%.2f', 0 - $_->paid ),
678 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
680 foreach $cust_main->cust_pay;
684 'description' => 'Credit', #more info?
685 'amount' => sprintf('%.2f', 0 -$_->amount ),
687 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
689 foreach $cust_main->cust_credit;
693 'description' => 'Refund', #more info? type, like payment?
694 'amount' => $_->refund,
696 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
698 foreach $cust_main->cust_refund;
700 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
702 $return{'history'} = \@history;
710 my $session = _cache->get($p->{'session_id'})
711 or return { 'error' => "Can't resume session" }; #better error message
713 my $custnum = $session->{'custnum'}
714 or return { 'error' => "no customer record" };
716 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
717 or return { 'error' => "unknown custnum $custnum" };
719 my $new = new FS::cust_main { $cust_main->hash };
721 $new->set( $_ => $p->{$_} )
722 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
724 if ( exists($p->{address1}) ) {
725 my $bill_location = FS::cust_location->new({
726 map { $_ => $p->{$_} } @location_editable_fields
728 # if this is unchanged from before, cust_main::replace will ignore it
729 $new->set('bill_location' => $bill_location);
732 if ( exists($p->{ship_address1}) ) {
733 my $ship_location = FS::cust_location->new({
734 map { $_ => $p->{"ship_$_"} } @location_editable_fields
736 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
737 # Selfservice unfortunately tries to indicate "same as billing
738 # address" by sending all fields empty. Did this ever work?
739 $ship_location = $cust_main->bill_location;
741 $new->set('ship_location' => $ship_location);
743 # but if it hasn't been passed in at all, leave ship_location alone--
744 # DON'T change it to match bill_location.
747 if (exists($p->{'payby'})) {
748 $p->{'payby'} =~ /^([A-Z]{4})$/
749 or return { 'error' => "illegal_payby " . $p->{'payby'} };
753 my $conf = new FS::Conf;
755 if ( $payby =~ /^(CARD|DCRD)$/ ) {
757 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
759 if ( $new->payinfo eq $cust_main->paymask ) {
760 $new->payinfo($cust_main->payinfo);
762 $new->payinfo($p->{'payinfo'});
765 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
767 if ( $conf->exists('selfservice-onfile_require_cvv') ){
768 return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
771 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
774 $p->{'payinfo1'} =~ /^([\dx]+)$/
775 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
777 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
778 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
780 $payinfo = $payinfo1. '@'. $payinfo2;
782 $new->payinfo( ($payinfo eq $cust_main->paymask)
783 ? $cust_main->payinfo
787 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
789 } elsif ( $payby =~ /^(BILL)$/ ) {
791 } elsif ( $payby ) { #notyet ready
792 return { 'error' => "unknown payby $payby" };
796 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
797 #false laziness with httemplate/edit/process/cust_main.cgi
798 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
799 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
801 @invoicing_list = $cust_main->invoicing_list;
804 my $error = $new->replace($cust_main, \@invoicing_list);
805 return { 'error' => $error } if $error;
808 return { 'error' => '' };
813 my $session = _cache->get($p->{'session_id'})
814 or return { 'error' => "Can't resume session" }; #better error message
820 my $conf = new FS::Conf;
821 use vars qw($payment_info); #cache for performance
822 unless ( $payment_info ) {
824 my %states = map { $_->state => 1 }
825 qsearch('cust_main_county', {
826 'country' => $conf->config('countrydefault') || 'US'
829 my %cust_paybys = map { $_ => 1 }
830 map { FS::payby->payby2payment($_) }
831 $conf->config('signup_server-payby');
833 my @cust_paybys = keys %cust_paybys;
837 #list all counties/states/countries
838 'cust_main_county' =>
839 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
841 #shortcut for one-country folks
843 [ sort { $a cmp $b } keys %states ],
845 'card_types' => card_types(),
847 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
848 'require_cvv' => $conf->exists('selfservice-require_cvv'),
849 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
851 'paytypes' => [ @FS::cust_main::paytypes ],
853 'paybys' => [ $conf->config('signup_server-payby') ],
854 'cust_paybys' => \@cust_paybys,
856 'stateid_label' => FS::Msgcat::_gettext('stateid'),
857 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
859 'show_ss' => $conf->exists('show_ss'),
860 'show_stateid' => $conf->exists('show_stateid'),
861 'show_paystate' => $conf->exists('show_bankstate'),
863 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
865 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
874 my %return = %$payment_info;
876 my $custnum = $session->{'custnum'};
878 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
879 or return { 'error' => "unknown custnum $custnum" };
881 $return{'hide_payment_fields'} = [
883 my $pg = payment_gateway($cust_main, $_);
884 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
885 } @{ $return{cust_paybys} }
888 $return{balance} = $cust_main->balance; #XXX pkg-balances?
890 $return{payname} = $cust_main->payname
891 || ( $cust_main->first. ' '. $cust_main->get('last') );
893 $return{$_} = $cust_main->bill_location->get($_)
894 for qw(address1 address2 city state zip);
896 $return{payby} = $cust_main->payby;
897 $return{stateid_state} = $cust_main->stateid_state;
899 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
900 $return{card_type} = cardtype($cust_main->payinfo);
901 $return{payinfo} = $cust_main->paymask;
903 @return{'month', 'year'} = $cust_main->paydate_monthyear;
907 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
908 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
909 $return{payinfo1} = $payinfo1;
910 $return{payinfo2} = $payinfo2;
911 $return{paytype} = $cust_main->paytype;
912 $return{paystate} = $cust_main->paystate;
913 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
916 if ( $conf->config('prepayment_discounts-credit_type') ) {
918 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
921 #doubleclick protection
923 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
924 $return{paybatch} = $return{payunique}; #back compat
926 return { 'error' => '',
932 #some false laziness with httemplate/process/payment.cgi - look there for
933 #ACH and CVV support stuff
935 sub validate_payment {
938 my $session = _cache->get($p->{'session_id'})
939 or return { 'error' => "Can't resume session" }; #better error message
941 my $custnum = $session->{'custnum'};
943 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
944 or return { 'error' => "unknown custnum $custnum" };
946 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
947 or return { 'error' => gettext('illegal_amount') };
949 return { error => 'Amount must be greater than 0' } unless $amount > 0;
951 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
952 #changing the hidden form values
953 my $conf = new FS::Conf;
954 my $fee_display = $conf->config('selfservice_process-display') || 'add';
955 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
956 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
957 if ( $fee_display eq 'add'
959 and ! $fee_skip_first || scalar($cust_main->cust_pay)
962 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
963 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
966 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
967 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
968 my $discount_term = $1;
970 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
971 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
974 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
975 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
978 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
979 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
982 $payunique = $paybatch if ! length($payunique) && length($paybatch);
984 $p->{'payby'} ||= 'CARD';
985 $p->{'payby'} =~ /^([A-Z]{4})$/
986 or return { 'error' => "illegal_payby " . $p->{'payby'} };
989 #false laziness w/process/payment.cgi
992 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
994 $p->{'payinfo1'} =~ /^([\dx]+)$/
995 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
997 $p->{'payinfo2'} =~ /^([\dx]+)$/
998 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1000 $payinfo = $payinfo1. '@'. $payinfo2;
1002 $payinfo = $cust_main->payinfo
1003 if $cust_main->paymask eq $payinfo;
1005 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1007 $payinfo = $p->{'payinfo'};
1011 #more intelligent matching will be needed here if you change
1012 #card_masking_method and don't remove existing paymasks
1013 if ( $cust_main->paymask eq $payinfo ) {
1014 $payinfo = $cust_main->payinfo;
1018 $payinfo =~ s/\D//g;
1019 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1020 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1024 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1025 return { 'error' => gettext('unknown_card_type') }
1026 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1028 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1029 if ( cardtype($payinfo) eq 'American Express card' ) {
1030 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1031 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1034 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1035 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1038 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1039 return { 'error' => 'CVV2 is required' };
1040 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1041 return { 'error' => 'CVV2 is required' };
1045 die "unknown payby $payby";
1048 my %payby2fields = (
1049 'CARD' => [ qw( paystart_month paystart_year payissue payip
1050 address1 address2 city state zip country ) ],
1051 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1055 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1058 'cust_main' => $cust_main, #XXX or just custnum??
1059 'amount' => sprintf('%.2f', $amount),
1061 'payinfo' => $payinfo,
1062 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1063 'card_type' => $card_type,
1064 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1065 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1066 'month' => $p->{'month'},
1067 'year' => $p->{'year'},
1068 'payname' => $payname,
1069 'payunique' => $payunique,
1070 'paybatch' => $paybatch,
1071 'paycvv' => $paycvv,
1072 'payname' => $payname,
1073 'discount_term' => $discount_term,
1074 'pkgnum' => $session->{'pkgnum'},
1075 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1085 my $validate = validate_payment($p);
1086 return $validate if $validate->{'error'};
1088 my $conf = new FS::Conf;
1089 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1090 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1092 +{ map { $_=>$validate->{$_} }
1093 qw( card_type paymask payname paydate_pretty month year amount
1094 address1 address2 city state zip country
1100 sub process_stored_payment {
1103 my $session_id = $p->{'session_id'};
1105 my $payment_info = _cache->get( "payment_$session_id" )
1106 or return { 'error' => "Can't resume session" }; #better error message
1108 do_process_payment($payment_info);
1112 sub process_payment {
1115 my $payment_info = validate_payment($p);
1116 return $payment_info if $payment_info->{'error'};
1118 do_process_payment($payment_info);
1122 sub do_process_payment {
1123 my $validate = shift;
1125 my $cust_main = $validate->{'cust_main'};
1127 my $amount = delete $validate->{'amount'};
1130 my $payby = delete $validate->{'payby'};
1132 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1135 'paynum_ref' => \$paynum,
1138 return { 'error' => $error } if $error;
1140 #no error, so order the fee package if applicable...
1141 my $conf = new FS::Conf;
1142 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1143 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1145 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1147 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1149 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1150 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1153 #and generate an invoice for it now too
1154 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1155 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1160 $cust_main->apply_payments;
1162 if ( $validate->{'save'} ) {
1163 my $new = new FS::cust_main { $cust_main->hash };
1164 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1165 $new->set( $_ => $validate->{$_} )
1166 foreach qw( payname paystart_month paystart_year payissue payip );
1167 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1169 my $bill_location = FS::cust_location->new({
1170 map { $_ => $validate->{$_} }
1171 qw(address1 address2 city state country zip)
1173 $new->set('bill_location' => $bill_location);
1174 # but don't allow the service address to change this way.
1176 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1177 $new->set( $_ => $validate->{$_} )
1178 foreach qw( payname payip paytype paystate
1179 stateid stateid_state );
1180 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1182 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1183 $new->set( 'paydate' => $validate->{'paydate'} );
1184 my $error = $new->replace($cust_main);
1186 #no, this causes customers to process their payments again
1187 #return { 'error' => $error };
1188 #XXX just warn verosely for now so i can figure out how these happen in
1189 # the first place, eventually should redirect them to the "change
1190 #address" page but indicate the payment did process??
1191 delete($validate->{'payinfo'}); #don't want to log this!
1192 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1193 "NEW: ". Dumper($new)."\n".
1194 "OLD: ". Dumper($cust_main)."\n".
1195 "PACKET: ". Dumper($validate)."\n";
1203 my $receipt_html = '';
1205 # currently supported for realtime CC only; send receipt data to SS
1206 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1209 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1212 <TD ALIGN="right">Payment#</TD>
1213 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1217 <TD ALIGN="right">Date</TD>
1219 <TD BGCOLOR="#FFFFFF"><B>! .
1220 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1226 <TD ALIGN="right">Amount</TD>
1227 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1232 <TD ALIGN="right">Payment method</TD>
1233 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1246 'amount' => sprintf('%.2f', $cust_pay->paid),
1247 'date' => $cust_pay->_date,
1248 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1249 'time_pretty' => time2str('%T', $cust_pay->_date),
1250 'auth_num' => $cust_pay->auth,
1251 'order_num' => $cust_pay->order_number,
1252 'receipt_html' => $receipt_html,
1259 'receipt_html' => '',
1266 sub realtime_collect {
1269 my $session = _cache->get($p->{'session_id'})
1270 or return { 'error' => "Can't resume session" }; #better error message
1272 my $custnum = $session->{'custnum'};
1274 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1275 or return { 'error' => "unknown custnum $custnum" };
1278 if ( $p->{'amount'} ) {
1279 $amount = $p->{'amount'};
1281 elsif ( $session->{'pkgnum'} ) {
1282 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1285 $amount = $cust_main->balance;
1288 my $error = $cust_main->realtime_collect(
1289 'method' => $p->{'method'},
1290 'amount' => $amount,
1291 'pkgnum' => $session->{'pkgnum'},
1292 'session_id' => $p->{'session_id'},
1296 return { 'error' => $error } unless ref( $error );
1298 return { 'error' => '', amount => $amount, %$error };
1301 sub start_thirdparty {
1303 my $session = _cache->get($p->{'session_id'})
1304 or return { 'error' => "Can't resume session" }; #better error message
1305 my $custnum = $session->{'custnum'};
1306 my $cust_main = FS::cust_main->by_key($custnum);
1308 my $amount = $p->{'amount'}
1309 or return { error => 'no amount' };
1311 my $result = $cust_main->create_payment(
1312 'method' => $p->{'method'},
1313 'amount' => $p->{'amount'},
1314 'pkgnum' => $session->{'pkgnum'},
1315 'session_id' => $p->{'session_id'},
1318 if ( ref($result) ) { # hashref or error
1321 return { error => $result };
1325 sub finish_thirdparty {
1327 my $session_id = delete $p->{'session_id'};
1328 my $session = _cache->get($session_id)
1329 or return { 'error' => "Can't resume session" };
1330 my $custnum = $session->{'custnum'};
1331 my $cust_main = FS::cust_main->by_key($custnum);
1333 if ( $p->{_cancel} ) {
1334 # customer backed out of making a payment
1335 return $cust_main->cancel_payment( $session_id );
1337 my $result = $cust_main->execute_payment( $session_id, %$p );
1338 if ( ref($result) ) {
1341 return { error => $result };
1345 sub process_payment_order_pkg {
1348 my $hr = process_payment($p);
1349 return $hr if $hr->{'error'};
1354 sub process_payment_order_renew {
1357 my $hr = process_payment($p);
1358 return $hr if $hr->{'error'};
1363 sub process_prepay {
1367 my $session = _cache->get($p->{'session_id'})
1368 or return { 'error' => "Can't resume session" }; #better error message
1372 my $custnum = $session->{'custnum'};
1374 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1375 or return { 'error' => "unknown custnum $custnum" };
1377 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1378 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1386 return { 'error' => $error } if $error;
1388 return { 'error' => '',
1389 'amount' => $amount,
1390 'seconds' => $seconds,
1391 'duration' => duration_exact($seconds),
1392 'upbytes' => $upbytes,
1393 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1394 'downbytes' => $downbytes,
1395 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1396 'totalbytes'=> $totalbytes,
1397 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1404 my $session = _cache->get($p->{'session_id'})
1405 or return { 'error' => "Can't resume session" }; #better error message
1407 my $custnum = $session->{'custnum'};
1409 my $invnum = $p->{'invnum'};
1411 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1412 'custnum' => $custnum } )
1413 or return { 'error' => "Can't find invnum" };
1417 return { 'error' => '',
1418 'invnum' => $invnum,
1419 'invoice_text' => join('', $cust_bill->print_text ),
1420 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1427 my $session = _cache->get($p->{'session_id'})
1428 or return { 'error' => "Can't resume session" }; #better error message
1430 my $custnum = $session->{'custnum'};
1432 my $invnum = $p->{'invnum'};
1434 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1435 'custnum' => $custnum } )
1436 or return { 'error' => "Can't find invnum" };
1440 return { 'error' => '',
1441 'invnum' => $invnum,
1442 'invoice_pdf' => $cust_bill->print_pdf({
1443 'unsquelch_cdr' => 1,
1444 'locale' => $p->{'locale'},
1450 sub legacy_invoice {
1452 my $session = _cache->get($p->{'session_id'})
1453 or return { 'error' => "Can't resume session" }; #better error message
1455 my $custnum = $session->{'custnum'};
1457 my $legacyinvnum = $p->{'legacyinvnum'};
1460 'legacyinvnum' => $legacyinvnum,
1461 'custnum' => $custnum,
1464 my $legacy_cust_bill =
1465 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1466 || qsearchs('legacy_cust_bill', \%hash )
1467 or return { 'error' => "Can't find legacyinvnum" };
1471 return { 'error' => '',
1472 'legacyinvnum' => $legacyinvnum,
1473 'legacyid' => $legacy_cust_bill->legacyid,
1474 'invoice_html' => $legacy_cust_bill->content_html,
1479 sub legacy_invoice_pdf {
1481 my $session = _cache->get($p->{'session_id'})
1482 or return { 'error' => "Can't resume session" }; #better error message
1484 my $custnum = $session->{'custnum'};
1486 my $legacyinvnum = $p->{'legacyinvnum'};
1488 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1489 'legacyinvnum' => $legacyinvnum,
1490 'custnum' => $custnum,
1491 }) or return { 'error' => "Can't find legacyinvnum" };
1495 return { 'error' => '',
1496 'legacyinvnum' => $legacyinvnum,
1497 'legacyid' => $legacy_cust_bill->legacyid,
1498 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1506 #sessioning for this? how do we get the session id to the backend invoice
1507 # template so it can add it to the link, blah
1510 if ( $p->{'invnum'} ) {
1511 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1512 or return { 'error' => 'unknown invnum' };
1513 $agentnum = $cust_bill->cust_main->agentnum;
1516 my $templatename = $p->{'template'} || $p->{'templatename'};
1518 #false laziness-ish w/view/cust_bill-logo.cgi
1520 my $conf = new FS::Conf;
1521 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1522 $templatename = "_$1";
1527 my $filename = "logo$templatename.png";
1529 return { 'error' => '',
1530 'logo' => $conf->config_binary($filename, $agentnum),
1531 'content_type' => 'image/png', #should allow gif, jpg too
1538 my $session = _cache->get($p->{'session_id'})
1539 or return { 'error' => "Can't resume session" }; #better error message
1541 my $custnum = $session->{'custnum'};
1543 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1544 or return { 'error' => "unknown custnum $custnum" };
1546 my $conf = new FS::Conf;
1548 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1550 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1554 return { 'error' => '',
1555 'balance' => $cust_main->balance,
1558 my $owed = $_->owed;
1560 +{ 'invnum' => $_->invnum,
1561 '_date' => $_->_date,
1562 'date' => time2str("%b %o, %Y", $_->_date),
1563 'date_short' => time2str("%m-%d-%Y", $_->_date),
1564 'previous' => sprintf('%.2f', ($_->previous)[0]),
1565 'charged' => sprintf('%.2f', $_->charged),
1566 'owed' => sprintf('%.2f', $owed),
1567 'balance' => sprintf('%.2f', $balance),
1572 'legacy_invoices' => [
1574 +{ 'legacyinvnum' => $_->legacyinvnum,
1575 'legacyid' => $_->legacyid,
1576 '_date' => $_->_date,
1577 'date' => time2str("%b %o, %Y", $_->_date),
1578 'date_short' => time2str("%m-%d-%Y", $_->_date),
1579 'charged' => sprintf('%.2f', $_->charged),
1580 'has_content' => ( length($_->content_pdf)
1581 || length($_->content_html) ),
1591 my $session = _cache->get($p->{'session_id'})
1592 or return { 'error' => "Can't resume session" }; #better error message
1594 my $custnum = $session->{'custnum'};
1596 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1597 or return { 'error' => "unknown custnum $custnum" };
1599 my @errors = $cust_main->cancel( 'quiet'=>1 );
1601 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1603 return { 'error' => $error };
1610 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1611 return { 'error' => $session } if $context eq 'error';
1613 my $search = { 'custnum' => $custnum };
1614 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1615 my $cust_main = qsearchs('cust_main', $search )
1616 or return { 'error' => "unknown custnum $custnum" };
1618 my $conf = new FS::Conf;
1619 my $immutable = $conf->exists('selfservice_immutable-package');
1621 # the duplication below is necessary:
1622 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1623 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1624 # non-backwards-compatible change breaking the software of anyone using the API
1625 # instead of the stock selfservice
1626 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1627 if( $conf->exists('selfservice_server-view-wholesale') ) {
1628 return { 'svcnum' => $session->{'svcnum'},
1629 'custnum' => $custnum,
1630 'cust_pkg' => [ map {
1632 immutable => $immutable,
1633 part_pkg => [ map $_->hashref, $_->part_pkg ],
1635 [ map $_->hashref, $_->available_part_svc ],
1637 [ map { my $ref = { $_->hash,
1638 label => [ $_->label ],
1640 $ref->{_password} = $_->svc_x->_password
1641 if $context eq 'agent'
1642 && $conf->exists('agent-showpasswords')
1643 && $_->part_svc->svcdb eq 'svc_acct';
1648 } $cust_main->cust_pkg
1651 small_custview( $cust_main, $conf->config('countrydefault') ),
1652 'wholesale_view' => 1,
1653 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1654 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1655 'lnp' => $conf->exists('svc_phone-lnp'),
1659 { 'svcnum' => $session->{'svcnum'},
1660 'custnum' => $custnum,
1661 'cust_pkg' => [ map {
1662 my $primary_cust_svc = $_->primary_cust_svc;
1665 immutable => $immutable,
1666 pkg_label => $_->pkg_locale,
1667 status => $_->status,
1668 statuscolor => $_->statuscolor,
1670 [ map { $_->hashref }
1671 grep { $_->selfservice_access ne 'hidden' }
1672 $_->available_part_svc
1675 [ map { my $ref = { $_->hash,
1676 label => [ $_->label ],
1678 $ref->{_password} = $_->svc_x->_password
1679 if $context eq 'agent'
1680 && $conf->exists('agent-showpasswords')
1681 && $_->part_svc->svcdb eq 'svc_acct';
1682 $ref->{svchash} = { $_->svc_x->hash } if
1683 $_->part_svc->svcdb eq 'svc_phone';
1684 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1685 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1688 grep { $_->part_svc->selfservice_access ne 'hidden' }
1693 ? { $primary_cust_svc->hash,
1694 label => [ $primary_cust_svc->label ],
1695 finger => $primary_cust_svc->svc_x->finger, #uuh
1696 $primary_cust_svc->part_svc->hash,
1700 } $cust_main->ncancelled_pkgs
1703 small_custview( $cust_main, $conf->config('countrydefault') ),
1704 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1712 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1713 return { 'error' => $session } if $context eq 'error';
1715 my $conf = new FS::Conf;
1717 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1718 my $search = { 'custnum' => $custnum };
1719 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1720 my $cust_main = qsearchs('cust_main', $search )
1721 or return { 'error' => "unknown custnum $custnum" };
1723 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1724 if ( ! $pkgnum && $p->{'svcnum'} ) {
1725 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1726 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1730 my @cust_pkg_usage = ();
1731 foreach my $cust_pkg ( $p->{'ncancelled'}
1732 ? $cust_main->ncancelled_pkgs
1733 : $cust_main->unsuspended_pkgs ) {
1734 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1735 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1736 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1739 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1742 foreach (@cust_pkg_usage) {
1743 my $part = $_->part_pkg_usage;
1744 my $tag = $part->description . ($part->shared ? 1 : 0);
1745 my $row = $usage_pools{$tag}
1746 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1747 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1748 $row->[2] += $part->minutes; # minutes total
1750 } # otherwise just leave them empty
1752 if ( $p->{'svcdb'} ) {
1753 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1755 : ref($p->{'svcdb'}) eq 'ARRAY'
1756 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1757 : { $p->{'svcdb'} => 1 };
1758 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1761 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1764 my @svcs; # stuff to return to the client
1765 foreach my $cust_svc (@cust_svc) {
1766 my $svc_x = $cust_svc->svc_x;
1767 my($label, $value) = $cust_svc->label;
1768 my $part_svc = $cust_svc->part_svc;
1769 my $svcdb = $part_svc->svcdb;
1770 my $cust_pkg = $cust_svc->cust_pkg;
1771 my $part_pkg = $cust_pkg->part_pkg;
1774 'svcnum' => $cust_svc->svcnum,
1775 'display_svcnum' => $cust_svc->display_svcnum,
1779 'pkg_label' => $cust_pkg->pkg_locale,
1780 'pkg_status' => $cust_pkg->status,
1781 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1784 # would it make sense to put this in a svc_* method?
1786 if ( $svcdb eq 'svc_acct' ) {
1787 foreach (qw(username email finger seconds)) {
1788 $hash{$_} = $svc_x->$_;
1794 'upbytes' => display_bytecount($svc_x->upbytes),
1795 'downbytes' => display_bytecount($svc_x->downbytes),
1796 'totalbytes' => display_bytecount($svc_x->totalbytes),
1798 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1799 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1800 'recharge_upbytes' =>
1801 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1802 'recharge_downbytes' =>
1803 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1804 'recharge_totalbytes' =>
1805 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1810 } elsif ( $svcdb eq 'svc_dsl' ) {
1812 $hash{'phonenum'} = $svc_x->phonenum;
1813 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1814 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1815 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1818 $hash{'name'} = $cust_main->name;
1820 # no usage to hide here
1822 } elsif ( $svcdb eq 'svc_phone' ) {
1824 # could potentially show lots of things...
1825 $hash{'outbound'} = 1;
1826 $hash{'inbound'} = 0;
1827 if ( $part_pkg->plan eq 'voip_inbound' ) {
1828 $hash{'outbound'} = 0;
1829 $hash{'inbound'} = 1;
1830 } elsif ( $part_pkg->option('selfservice_inbound_format')
1831 or $conf->config('selfservice-default_inbound_cdr_format')
1833 $hash{'inbound'} = 1;
1835 foreach (qw(inbound outbound)) {
1836 # hmm...we can't filter by status here, because there might
1837 # not be cdr_terminations at all. have to go by date.
1838 # find all since the last bill date.
1839 # XXX cdr types? we are going to need them.
1841 my $sum_cdr = $svc_x->sum_cdrs(
1842 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1843 'begin' => ($cust_pkg->last_bill || 0),
1845 'disable_charged_party' => 1,
1847 $hash{$_} = $sum_cdr->hashref;
1850 } # not hiding usage
1854 } # foreach $cust_svc
1857 'svcnum' => $session->{'svcnum'},
1858 'custnum' => $custnum,
1859 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1860 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1863 map { $usage_pools{$_} }
1867 'hide_usage' => $hide_usage,
1872 sub _customer_svc_x {
1873 my($custnum, $svcnum, $table) = (shift, shift, shift);
1874 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1876 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1877 my $search = " AND custnum = $1";
1878 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1881 'table' => ($table || 'svc_acct'),
1882 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1883 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1884 #'LEFT JOIN cust_main USING ( custnum ) ',
1885 'hashref' => $hashref,
1886 'extra_sql' => $search, #important
1891 sub svc_status_html {
1894 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1895 return { 'error' => $session } if $context eq 'error';
1897 #XXX only svc_dsl for now
1898 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1899 or return { 'error' => "Service not found" };
1901 my $html = $svc_x->getstatus_html;
1903 return { 'html' => $html };
1907 sub svc_status_hash {
1910 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1911 return { 'error' => $session } if $context eq 'error';
1913 #XXX only svc_acct for now
1914 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1915 or return { 'error' => "Service not found" };
1917 my ( $html, $hashref ) = $svc_x->export_getstatus;
1922 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1923 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1924 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1925 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1926 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1929 my( $p, $method ) = @_;
1931 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1932 return { 'error' => $session } if $context eq 'error';
1934 #XXX only svc_acct for now
1935 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1936 or return { 'error' => "Service not found" };
1938 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1940 my $error = $svc_x->$method($p); #$p? returns error?
1941 return { 'error' => $error } if $error;
1943 return {}; #? { 'error' => '' }
1947 sub acct_forward_info {
1950 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1951 return { 'error' => $session } if $context eq 'error';
1953 my $svc_forward = _customer_svc_x( $custnum,
1954 { 'srcsvc' => $p->{'svcnum'} },
1957 or return { 'error' => '',
1961 return { 'error' => '',
1962 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1967 sub process_acct_forward {
1969 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1970 return { 'error' => $session } if $context eq 'error';
1972 my $old = _customer_svc_x( $custnum,
1973 { 'srcsvc' => $p->{'svcnum'} },
1977 if ( $p->{'dst'} eq '' ) {
1979 my $error = $old->delete;
1980 return { 'error' => $error };
1982 return { 'error' => '' };
1985 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1986 'dst' => $p->{'dst'},
1991 $new->svcnum($old->svcnum);
1992 my $cust_svc = $old->cust_svc;
1993 $new->svcpart($old->svcpart);
1994 $new->pkgnuym($old->pkgnum);
1995 $error = $new->replace($old);
1997 my $conf = new FS::Conf;
1998 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2000 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2001 or return { 'error' => 'No service' }; #how would we even get here?
2003 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2005 $error = $new->insert;
2008 return { 'error' => $error };
2012 sub list_dsl_devices {
2015 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2016 return { 'error' => $session } if $context eq 'error';
2018 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2019 or return { 'error' => "Service not found" };
2022 'devices' => [ map {
2023 +{ 'mac_addr' => $_->mac_addr };
2024 } $svc_dsl->dsl_device
2030 sub add_dsl_device {
2033 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2034 return { 'error' => $session } if $context eq 'error';
2036 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2037 or return { 'error' => "Service not found" };
2039 return { 'error' => 'No MAC address supplied' }
2040 unless length($p->{'mac_addr'});
2042 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2043 'mac_addr' => scalar($p->{'mac_addr'}),
2045 my $error = $dsl_device->insert;
2046 return { 'error' => $error };
2050 sub delete_dsl_device {
2053 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2054 return { 'error' => $session } if $context eq 'error';
2056 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2057 or return { 'error' => "Service not found" };
2059 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2060 'mac_addr' => scalar($p->{'mac_addr'}),
2063 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2065 my $error = $dsl_device->delete;
2066 return { 'error' => $error };
2072 _usage_details( \&_port_graph, $p,
2073 'svcdb' => 'svc_port',
2078 my($svc_port, $begin, $end) = @_;
2080 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2081 push @usage, { 'png' => $pngOrError };
2085 sub _list_svc_usage {
2086 my($svc_acct, $begin, $end) = @_;
2088 foreach my $part_export (
2089 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2090 qw( sqlradius sqlradius_withdomain )
2092 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2097 sub list_svc_usage {
2098 _usage_details(\&_list_svc_usage, @_);
2101 sub _list_support_usage {
2102 my($svc_acct, $begin, $end) = @_;
2104 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2105 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2107 push @usage, { 'seconds' => $_->seconds,
2108 'support' => $_->support,
2109 '_date' => $_->_date,
2110 'id' => $_->transaction_id,
2111 'creator' => $_->creator,
2112 'subject' => $_->subject,
2113 'status' => $_->status,
2114 'ticketid' => $_->ticketid,
2120 sub list_support_usage {
2121 _usage_details(\&_list_support_usage, @_);
2124 sub _list_cdr_usage {
2125 # XXX CDR type support...
2126 # XXX any way to do a paged search on this?
2127 # we have to return the results all at once...
2128 my($svc_phone, $begin, $end, %opt) = @_;
2129 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2130 $svc_phone->get_cdrs(
2133 'disable_charged_party' => 1,
2138 sub list_cdr_usage {
2140 _usage_details( \&_list_cdr_usage, $p,
2141 'svcdb' => 'svc_phone',
2145 sub _usage_details {
2146 my($callback, $p, %opt) = @_;
2147 my $conf = FS::Conf->new;
2149 if ( $conf->exists('selfservice_hide-usage') ) {
2150 return { 'error' => 'Viewing usage is not allowed.' };
2153 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2154 return { 'error' => $session } if $context eq 'error';
2156 my $search = { 'svcnum' => $p->{'svcnum'} };
2157 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2159 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2161 my $svc_x = qsearchs( $svcdb, $search );
2162 return { 'error' => 'No service selected in list_svc_usage' }
2165 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2166 my $freq = $cust_pkg->part_pkg->freq;
2169 if ( $svcdb eq 'svc_phone' ) {
2171 if ( $p->{inbound} ) {
2172 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2173 || $conf->config('selfservice-default_inbound_cdr_format')
2174 || 'source_default';
2175 $callback_opt{inbound} = 1;
2177 $format = $cust_pkg->part_pkg->option('selfservice_format')
2178 || $conf->config('selfservice-default_cdr_format')
2182 $callback_opt{format} = $format;
2183 $callback_opt{use_clid} = 1;
2184 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2187 my $start = $cust_pkg->setup;
2188 #my $end = $cust_pkg->bill; # or time?
2191 unless ( $p->{beginning} ) {
2192 $p->{beginning} = $cust_pkg->last_bill;
2193 $p->{ending} = $end;
2196 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2197 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2199 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2203 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2204 # ugly kludge, I know
2205 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2206 if (defined $delete_col) {
2207 delete($_->[$delete_col]) foreach ($header, @usage);
2211 #kinda false laziness with FS::cust_main::bill, but perhaps
2212 #we should really change this bit to DateTime and DateTime::Duration
2214 #change this bit to use Date::Manip? CAREFUL with timezones (see
2215 # mailing list archive)
2216 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2217 (localtime($p->{ending}) )[0,1,2,3,4,5];
2218 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2219 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2221 if ( $freq =~ /^\d+$/ ) {
2223 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2225 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2226 } elsif ( $freq =~ /^(\d+)w$/ ) {
2228 $nmday += $weeks * 7;
2229 $pmday -= $weeks * 7;
2230 } elsif ( $freq =~ /^(\d+)d$/ ) {
2234 } elsif ( $freq =~ /^(\d+)h$/ ) {
2239 return { 'error' => "unparsable frequency: ". $freq };
2242 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2243 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2247 'svcnum' => $p->{svcnum},
2248 'beginning' => $p->{beginning},
2249 'ending' => $p->{ending},
2250 'inbound' => $p->{inbound},
2251 'previous' => ($previous > $start) ? $previous : $start,
2252 'next' => ($next < $end) ? $next : $end,
2253 'header' => $header,
2261 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2262 return { 'error' => $session } if $context eq 'error';
2264 my $search = { 'custnum' => $custnum };
2265 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2266 my $cust_main = qsearchs('cust_main', $search )
2267 or return { 'error' => "unknown custnum $custnum" };
2269 my $status = $cust_main->status;
2270 #false laziness w/ClientAPI/Signup.pm
2272 my $cust_pkg = new FS::cust_pkg ( {
2273 'custnum' => $custnum,
2274 'pkgpart' => $p->{'pkgpart'},
2276 my $error = $cust_pkg->check;
2277 return { 'error' => $error } if $error;
2280 unless ( $p->{'svcpart'} eq 'none' ) {
2284 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2286 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2287 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2288 $svcdb = $part_svc->svcdb;
2290 $svcdb = 'svc_acct';
2292 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2295 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2296 'svc_domain' => [ qw( domain ) ],
2297 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2298 'svc_external' => [ qw( id title ) ],
2299 'svc_pbx' => [ qw( id title ) ],
2302 my $svc_x = "FS::$svcdb"->new( {
2303 'svcpart' => $svcpart,
2304 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2307 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2310 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2311 my $acct_snarf = new FS::acct_snarf ( {
2312 'machine' => $p->{"snarf_machine$snarfnum"},
2313 'protocol' => $p->{"snarf_protocol$snarfnum"},
2314 'username' => $p->{"snarf_username$snarfnum"},
2315 '_password' => $p->{"snarf_password$snarfnum"},
2318 push @acct_snarf, $acct_snarf;
2320 $svc_x->child_objects( \@acct_snarf );
2323 my $y = $svc_x->setdefault; # arguably should be in new method
2324 return { 'error' => $y } if $y && !ref($y);
2326 $error = $svc_x->check;
2327 return { 'error' => $error } if $error;
2334 tie my %hash, 'Tie::RefHash';
2335 %hash = ( $cust_pkg => \@svc );
2337 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2338 return { 'error' => $error } if $error;
2340 my $conf = new FS::Conf;
2341 if ( $conf->exists('signup_server-realtime') ) {
2343 my $bill_error = _do_bop_realtime( $cust_main, $status );
2346 $cust_pkg->cancel('quiet'=>1);
2349 $cust_pkg->reexport;
2353 $cust_pkg->reexport;
2356 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2358 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2365 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2366 return { 'error' => $session } if $context eq 'error';
2368 my $conf = new FS::Conf;
2369 my $immutable = $conf->exists('selfservice_immutable-package');
2370 return { 'error' => "Package modification disabled" } if $immutable;
2372 my $search = { 'custnum' => $custnum };
2373 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2374 my $cust_main = qsearchs('cust_main', $search )
2375 or return { 'error' => "unknown custnum $custnum" };
2377 my $status = $cust_main->status;
2378 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2379 or return { 'error' => "unknown package $p->{pkgnum}" };
2381 #if someone does need self-service package change of suspended packages,
2382 # figure out how to be more discriminating
2383 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2384 if $cust_pkg->status eq 'suspended';
2387 my $error = FS::cust_pkg::order( $custnum,
2393 if ( $conf->exists('signup_server-realtime') ) {
2395 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2398 $newpkg[0]->suspend;
2401 $newpkg[0]->reexport;
2405 $newpkg[0]->reexport;
2408 return { error => '', pkgnum => $cust_pkg->pkgnum };
2412 sub order_recharge {
2415 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2416 return { 'error' => $session } if $context eq 'error';
2418 my $search = { 'custnum' => $custnum };
2419 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2420 my $cust_main = qsearchs('cust_main', $search )
2421 or return { 'error' => "unknown custnum $custnum" };
2423 my $status = $cust_main->status;
2424 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2425 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2427 my $svc_x = $cust_svc->svc_x;
2428 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2431 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2432 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2433 recharge_totalbytes );
2434 my $amount = $part_pkg->option('recharge_amount', 1);
2436 my ($l, $v, $d) = $cust_svc->label; # blah
2437 my $pkg = "Recharge $v";
2439 my $bill_error = $cust_main->charge($amount, $pkg,
2440 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2441 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2442 $part_pkg->taxclass); #meh
2444 my $conf = new FS::Conf;
2445 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2447 $bill_error = _do_bop_realtime( $cust_main, $status );
2452 my $error = $svc_x->recharge (\%vhash);
2453 return { 'error' => $error } if $error;
2457 my $error = $bill_error;
2458 $error ||= $svc_x->recharge (\%vhash);
2459 return { 'error' => $error } if $error;
2462 return { error => '', svc => $cust_svc->part_svc->svc };
2466 sub _do_bop_realtime {
2467 my ($cust_main, $status, %opt) = @_;
2469 my $old_balance = $cust_main->balance;
2471 my $bill_error = $cust_main->bill
2472 || $cust_main->apply_payments_and_credits;
2474 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2475 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2477 if ( $cust_main->balance > $old_balance
2478 && $cust_main->balance > 0
2479 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2480 || $status eq 'suspended'
2484 unless ( $opt{'no_credit'} ) {
2485 #this makes sense. credit is "un-doing" the invoice
2486 my $conf = new FS::Conf;
2487 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2488 'self-service decline',
2489 reason_type=>$conf->config('signup_credit_type'),
2491 $cust_main->apply_credits( 'order' => 'newest' );
2494 return { 'error' => '_decline', 'bill_error' => $bill_error };
2503 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2504 return { 'error' => $session } if $context eq 'error';
2506 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2507 or return { 'error' => "unknown custnum $custnum" };
2509 my @cust_pkg = sort { $a->bill <=> $b->bill }
2510 grep { $_->part_pkg->freq ne '0' }
2511 $cust_main->ncancelled_pkgs;
2513 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2515 my $total = $cust_main->balance;
2518 my $bill = $_->bill;
2519 $total += $_->part_pkg->base_recur($_, \$bill);
2520 my $renew_date = $_->part_pkg->add_freq($_->bill);
2522 'pkgnum' => $_->pkgnum,
2523 'amount' => sprintf('%.2f', $total),
2524 'bill_date' => $_->bill,
2525 'bill_date_pretty' => time2str('%x', $_->bill),
2526 'renew_date' => $renew_date,
2527 'renew_date_pretty' => time2str('%x', $renew_date),
2528 'expire_date' => $_->expire,
2529 'expire_date_pretty' => time2str('%x', $_->expire),
2534 return { 'dates' => \@array };
2538 sub payment_info_renew_info {
2540 my $renew_info = renew_info($p);
2541 my $payment_info = payment_info($p);
2542 return { %$renew_info,
2550 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2551 return { 'error' => $session } if $context eq 'error';
2553 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2554 or return { 'error' => "unknown custnum $custnum" };
2556 my $date = $p->{'date'};
2560 #freeside-daily -n -d $date fs_daily $custnum
2561 $cust_main->bill_and_collect( 'time' => $date,
2562 'invoice_time' => $now,
2563 'actual_time' => $now,
2564 'check_freq' => '1d',
2567 return { 'error' => '' };
2573 my $session = _cache->get($p->{'session_id'})
2574 or return { 'error' => "Can't resume session" }; #better error message
2576 my $custnum = $session->{'custnum'};
2578 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2579 or return { 'error' => "unknown custnum $custnum" };
2581 my $conf = new FS::Conf;
2583 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2584 or return { 'error' => 'Permission denied' };
2586 my $pkgnum = $p->{'pkgnum'};
2588 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2589 'pkgnum' => $pkgnum, } )
2590 or return { 'error' => "unknown pkgnum $pkgnum" };
2592 my $error = $cust_pkg->suspend(reason => $reasonnum);
2593 return { 'error' => $error };
2599 my $session = _cache->get($p->{'session_id'})
2600 or return { 'error' => "Can't resume session" }; #better error message
2602 my $custnum = $session->{'custnum'};
2604 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2605 or return { 'error' => "unknown custnum $custnum" };
2607 my $pkgnum = $p->{'pkgnum'};
2609 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2610 'pkgnum' => $pkgnum, } )
2611 or return { 'error' => "unknown pkgnum $pkgnum" };
2613 my $error = $cust_pkg->cancel('quiet' => 1);
2614 return { 'error' => $error };
2618 sub provision_phone {
2621 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2623 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2624 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2625 return { 'error' => $session } if $context eq 'error';
2627 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2628 return { 'error' => 'service not found' } unless $svc_phone;
2629 return { 'error' => 'invalid svcnum' }
2630 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2632 $svc_phone->email($p->{'email'})
2633 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2634 $svc_phone->forwarddst($p->{'forwarddst'})
2635 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2636 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2637 return { 'error' => $svc_phone->replace };
2641 unless($p->{'lnp'}) {
2642 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2643 $p->{'lnp_status'} = "portingin";
2644 return _provision( 'FS::svc_phone',
2645 [qw(lnp_desired_due_date lnp_other_provider
2646 lnp_other_provider_account phonenum countrycode lnp_status)],
2647 [qw(phonenum countrycode)],
2654 unless (scalar(@bulkdid)) {
2655 return _provision( 'FS::svc_phone',
2656 [qw(phonenum countrycode)],
2657 [qw(phonenum countrycode)],
2663 # bulk DID order case
2665 foreach my $did ( @bulkdid ) {
2666 $did =~ s/[^0-9]//g;
2667 $error = _provision( 'FS::svc_phone',
2668 [qw(phonenum countrycode)],
2669 [qw(phonenum countrycode)],
2671 'pkgnum' => $p->{'pkgnum'},
2672 'svcpart' => $p->{'svcpart'},
2674 'countrycode' => $p->{'countrycode'},
2675 'session_id' => $p->{'session_id'},
2678 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2680 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2683 sub provision_acct {
2685 warn "provision_acct called\n"
2688 return { 'error' => gettext('passwords_dont_match') }
2689 if $p->{'_password'} ne $p->{'_password2'};
2690 return { 'error' => gettext('empty_password') }
2691 unless length($p->{'_password'});
2693 if ($p->{'domsvc'}) {
2694 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2695 qw ( svcpart pkgnum ) );
2696 return { 'error' => gettext('invalid_domain') }
2697 unless ($domains{$p->{'domsvc'}});
2700 warn "provision_acct calling _provision\n"
2702 _provision( 'FS::svc_acct',
2703 [qw(username _password domsvc)],
2704 [qw(username _password domsvc)],
2710 sub provision_external {
2712 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2713 _provision( 'FS::svc_external',
2722 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2723 warn "_provision called for $class\n"
2726 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2727 return { 'error' => $session } if $context eq 'error';
2729 my $search = { 'custnum' => $custnum };
2730 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2731 my $cust_main = qsearchs('cust_main', $search )
2732 or return { 'error' => "unknown custnum $custnum" };
2734 my $pkgnum = $p->{'pkgnum'};
2736 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2738 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2739 'pkgnum' => $pkgnum,
2741 or return { 'error' => "unknown pkgnum $pkgnum" };
2743 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2745 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2746 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2748 warn "creating $class record\n"
2750 my $svc_x = $class->new( {
2751 'pkgnum' => $p->{'pkgnum'},
2752 'svcpart' => $p->{'svcpart'},
2753 map { $_ => $p->{$_} } @$fields
2755 warn "inserting $class record\n"
2757 my $error = $svc_x->insert;
2760 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2762 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2765 my $return = { 'svc' => $part_svc->svc,
2767 map { $_ => $svc_x->get($_) } @$return_fields
2769 warn "_provision returning ". Dumper($return). "\n"
2778 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2779 return { 'error' => $session } if $context eq 'error';
2781 my $search = { 'custnum' => $custnum };
2782 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2783 my $cust_main = qsearchs('cust_main', $search )
2784 or return { 'error' => "unknown custnum $custnum" };
2786 my $pkgnum = $p->{'pkgnum'};
2788 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2789 'pkgnum' => $pkgnum,
2791 or return { 'error' => "unknown pkgnum $pkgnum" };
2793 my $svcpart = $p->{'svcpart'};
2795 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2796 'svcpart' => $svcpart, } )
2797 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2798 my $part_svc = $pkg_svc->part_svc;
2800 my $conf = new FS::Conf;
2803 'svc' => $part_svc->svc,
2804 'svcdb' => $part_svc->svcdb,
2805 'pkgnum' => $pkgnum,
2806 'svcpart' => $svcpart,
2807 'custnum' => $custnum,
2809 'security_phrase' => 0, #XXX !
2810 'svc_acct_pop' => [], #XXX !
2812 'init_popstate' => '',
2817 small_custview( $cust_main, $conf->config('countrydefault') ),
2821 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2822 && $ret->{'svcdb'} eq 'svc_phone') {
2823 $ret->{'svcnum'} = $p->{'svcnum'};
2824 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2825 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2826 $ret->{'email'} = $svc_phone->email;
2827 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2834 sub unprovision_svc {
2837 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2838 return { 'error' => $session } if $context eq 'error';
2840 my $search = { 'custnum' => $custnum };
2841 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2842 my $cust_main = qsearchs('cust_main', $search )
2843 or return { 'error' => "unknown custnum $custnum" };
2845 my $svcnum = $p->{'svcnum'};
2847 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2848 or return { 'error' => "unknown svcnum $svcnum" };
2850 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2851 unless $cust_svc->cust_pkg->custnum == $custnum;
2853 my $conf = new FS::Conf;
2855 return { 'svc' => $cust_svc->part_svc->svc,
2856 'error' => $cust_svc->cancel,
2858 small_custview( $cust_main, $conf->config('countrydefault') ),
2863 sub myaccount_passwd {
2865 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2866 return { 'error' => $session } if $context eq 'error';
2868 return { 'error' => "New passwords don't match." }
2869 if $p->{'new_password'} ne $p->{'new_password2'};
2871 return { 'error' => 'Enter new password' }
2872 unless length($p->{'new_password'});
2874 #my $search = { 'custnum' => $custnum };
2875 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2876 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2877 my $search = " AND custnum = $1";
2878 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2880 my $svc_acct = qsearchs( {
2881 'table' => 'svc_acct',
2882 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2883 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2884 'LEFT JOIN cust_main USING ( custnum ) ',
2885 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2886 'extra_sql' => $search, #important
2888 or return { 'error' => "Service not found" };
2892 my $conf = new FS::Conf;
2894 return { 'error' => 'Incorrect current password.' }
2895 if ( exists($p->{'old_password'})
2896 || $conf->exists('selfservice-password_change_oldpass')
2898 && ! $svc_acct->check_password($p->{'old_password'});
2900 $error = 'Password too short.'
2901 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2902 $error = 'Password too long.'
2903 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2905 $svc_acct->set_password($p->{'new_password'});
2906 $error ||= $svc_acct->replace();
2908 #regular pw change in self-service should change contact pw too, otherwise its
2909 #way too confusing. hell its confusing they're separate at all, but alas.
2910 #need to support the "ISP provides email that's used as a contact email" case
2912 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2913 if ( $contact && $contact->custnum == $custnum ) {
2914 #svc_acct was successful but this one returns an error? "shouldn't happen"
2915 $error ||= $contact->change_password($p->{'new_password'});
2918 my($label, $value) = $svc_acct->cust_svc->label;
2920 return { 'error' => $error,
2927 # sub contact_passwd {
2929 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2930 # return { 'error' => $session } if $context eq 'error';
2932 # return { 'error' => 'Not logged in as a contact.' }
2933 # unless $session->{'contactnum'};
2935 # return { 'error' => "New passwords don't match." }
2936 # if $p->{'new_password'} ne $p->{'new_password2'};
2938 # return { 'error' => 'Enter new password' }
2939 # unless length($p->{'new_password'});
2941 # #my $search = { 'custnum' => $custnum };
2942 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2943 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2944 # my $search = " AND selfservice_access IS NOT NULL ".
2945 # " AND selfservice_access = 'Y' ".
2946 # " AND ( disabled IS NULL OR disabled = '' )".
2947 # " AND custnum IS NOT NULL AND custnum = $1";
2948 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2950 # my $contact = qsearchs( {
2951 # 'table' => 'contact',
2952 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2953 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2954 # 'extra_sql' => $search, #important
2956 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2957 # # deleted since then?
2961 # # use these svc_acct length restrictions??
2962 # my $conf = new FS::Conf;
2963 # $error = 'Password too short.'
2964 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2965 # $error = 'Password too long.'
2966 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2968 # $error ||= $contact->change_password($p->{'new_password'});
2970 # return { 'error' => $error, };
2977 my $info = skin_info($p);
2979 my $conf = new FS::Conf;
2980 my $verification = $conf->config('selfservice-password_reset_verification')
2981 or return { %$info, 'error' => 'Password resets disabled' };
2986 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2988 $contact = FS::contact->by_selfservice_email($p->{'email'});
2990 $cust_main = $contact->cust_main if $contact;
2992 #also look for an svc_acct, otherwise it would be super confusing
2994 my($username, $domain) = split('@', $p->{'email'});
2995 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2996 if ( $svc_domain ) {
2997 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2998 'domsvc' => $svc_domain->svcnum }
3001 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3002 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3004 #precaution: don't change svc_acct password not part of the same
3005 # customer as contact
3006 $svc_acct = '' if ! $cust_pkg
3007 || $cust_pkg->custnum != $cust_main->custnum;
3012 return { %$info, 'error' => 'Email address not found' }
3013 unless $contact || $svc_acct;
3015 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3017 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3018 or return { %$info, 'error' => 'Account not found' };
3020 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3021 'domsvc' => $svc_domain->svcnum }
3023 or return { %$info, 'error' => 'Account not found' };
3025 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3026 or return { %$info, 'error' => 'Account not found' };
3028 $cust_main = $cust_pkg->cust_main;
3033 'email' => sub { 1; },
3035 my( $p, $cust_main ) = @_;
3036 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3037 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3040 my( $p, $cust_main ) = @_;
3041 my $cust_pay = qsearchs({
3042 'table' => 'cust_pay',
3043 'hashref' => { 'custnum' => $cust_main->custnum },
3044 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3048 $p->{'amount'} == $cust_pay->paid;
3051 my( $p, $cust_main ) = @_;
3052 $p->{'zip'} eq $cust_main->zip
3053 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3057 foreach my $verify ( split(',', $verification) ) {
3059 &{ $verify{$verify} }( $p, $cust_main )
3060 or return { %$info, 'error' => 'Account not found' };
3064 #okay, we're verified
3068 my $error = $contact->send_reset_email(
3069 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3073 return { %$info, 'error' => $error }; #????
3076 } elsif ( $svc_acct ) {
3078 #create a unique session
3080 my $reset_session = {
3081 'svcnum' => $svc_acct->svcnum,
3085 my $timeout = '1 hour'; #?
3087 my $reset_session_id;
3089 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3090 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3093 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3097 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3098 $cust_main->agentnum);
3099 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3100 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3102 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3103 my $error = $msg_template->send( 'cust_main' => $cust_main,
3104 'object' => $svc_acct,
3105 'substitutions' => {
3106 'session_id' => $reset_session_id,
3110 return { %$info, 'error' => $error }; #????
3115 return { %$info, 'error' => '' };
3118 sub check_reset_passwd {
3121 my $conf = new FS::Conf;
3122 my $verification = $conf->config('selfservice-password_reset_verification')
3123 or return { 'error' => 'Password resets disabled' };
3125 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3126 or return { 'error' => "Can't resume session" }; #better error message
3128 if ( $reset_session->{'svcnum'} ) {
3130 my $svcnum = $reset_session->{'svcnum'};
3132 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3133 or return { 'error' => "Service not found" };
3135 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3136 my $info = skin_info($p);
3140 'session_id' => $p->{'session_id'},
3141 'username' => $svc_acct->username,
3144 } elsif ( $reset_session->{'contactnum'} ) {
3146 my $contactnum = $reset_session->{'contactnum'};
3148 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3149 or return { 'error' => "Contact not found" };
3151 my @contact_email = $contact->contact_email;
3152 return { 'error' => 'No contact email' } unless @contact_email;
3154 $p->{'agentnum'} = $contact->cust_main->agentnum;
3155 my $info = skin_info($p);
3159 'session_id' => $p->{'session_id'},
3160 'email' => $contact_email[0]->email, #the first?
3165 return { 'error' => 'No svcnum or contactnum in session' }; #??
3171 sub process_reset_passwd {
3174 my $conf = new FS::Conf;
3175 my $verification = $conf->config('selfservice-password_reset_verification')
3176 or return { 'error' => 'Password resets disabled' };
3178 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3179 or return { 'error' => "Can't resume session" }; #better error message
3184 if ( $reset_session->{'svcnum'} ) {
3186 my $svcnum = $reset_session->{'svcnum'};
3188 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3189 or return { 'error' => "Service not found" };
3191 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3192 $info ||= skin_info($p);
3197 if ( $reset_session->{'contactnum'} ) {
3199 my $contactnum = $reset_session->{'contactnum'};
3201 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3202 or return { 'error' => "Contact not found" };
3204 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3205 $info ||= skin_info($p);
3209 return { %$info, 'error' => "New passwords don't match." }
3210 if $p->{'new_password'} ne $p->{'new_password2'};
3212 return { %$info, 'error' => 'Enter new password' }
3213 unless length($p->{'new_password'});
3217 $svc_acct->set_password($p->{'new_password'});
3218 my $error = $svc_acct->replace();
3220 return { %$info, 'error' => $error } if $error;
3222 #my($label, $value) = $svc_acct->cust_svc->label;
3223 #return { 'error' => $error,
3224 # #'label' => $label,
3225 # #'value' => $value,
3232 my $error = $contact->change_password($p->{'new_password'});
3234 return { %$info, 'error' => $error }; # if $error;
3238 #password changed ,so remove session, don't want it reused
3239 _cache->remove($p->{'session_id'});
3241 return { %$info, 'error' => '' };
3247 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3248 return { 'error' => $session } if $context eq 'error';
3251 if ( $session->{'pkgnum'} ) {
3253 #tickets for specific service with pkg-balances on
3254 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3255 'pkgnum' => $session->{'pkgnum'} })
3256 or return { 'error' => 'unknown package' };
3257 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3258 push @tickets, $cust_svc->tickets( $p->{status} );
3263 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3264 or return { 'error' => "unknown custnum $custnum" };
3266 @tickets = $cust_main->tickets( $p->{status} );
3269 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3270 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3271 my $conf = new FS::Conf;
3272 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3276 ($a->{'_selfservice_priority'} eq '') <=>
3277 ($b->{'_selfservice_priority'} eq '')
3280 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3286 +{ tickets => \@tickets };
3293 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3294 return { 'error' => $session } if $context eq 'error';
3296 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3297 FS::TicketSystem->init();
3299 my $conf = new FS::Conf;
3300 my $queue = $p->{'queue'}
3301 || $conf->config('ticket_system-selfservice_queueid')
3302 || $conf->config('ticket_system-default_queueid');
3304 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3305 my $err_or_ticket = FS::TicketSystem->create_ticket(
3306 '', #create RT session based on FS CurrentUser (fs_selfservice)
3308 'custnum' => $custnum,
3309 'svcnum' => $session->{'svcnum'},
3310 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3313 if ( ref($err_or_ticket) ) {
3314 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3316 return { 'error' => '',
3317 'ticket_id' => $err_or_ticket->id,
3320 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3322 return { 'error' => $err_or_ticket };
3330 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3331 return { 'error' => $session } if $context eq 'error';
3333 return { error => 'requested format not implemented' }
3334 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3336 my $conf = new FS::Conf;
3337 my $age_threshold = 0;
3338 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3339 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3341 my $search = { 'custnum' => $custnum };
3342 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3343 my $cust_main = qsearchs('cust_main', $search )
3344 or return { 'error' => "unknown custnum $custnum" };
3346 # does it make more sense to just run one sql query for this instead of all the
3347 # insanity below? would increase performance greately for large data sets?
3349 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3350 my @part_svc = $cust_pkg->part_svc;
3351 foreach my $part_svc ( @part_svc ) {
3352 if($part_svc->svcdb eq 'svc_phone'){
3353 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3354 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3355 push @svc_phone, $cust_pkg_svc->svc_x
3356 if $cust_pkg_svc->date_inserted >= $age_threshold;
3364 my($xls_r,$xls_c) = (0,0);
3367 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3368 if($p->{'format'} eq 'csv') {
3369 $csv = new Text::CSV_XS { 'always_quote' => 1,
3372 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3373 $content .= $csv->string;
3375 elsif($p->{'format'} eq 'xls') {
3376 my $XLS1 = new IO::Scalar \$content;
3377 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3378 or return { 'error' => "Error opening .xls file: $!" };
3379 $xls = $xls_workbook->add_worksheet('DIDs');
3380 foreach ( @fields ) {
3381 $xls->write(0,$xls_c++,$_);
3386 foreach my $svc_phone ( @svc_phone ) {
3387 my @cols = map { $svc_phone->$_ } @fields;
3388 if($p->{'format'} eq 'csv') {
3389 return { 'error' => 'Unable to create CSV' }
3390 unless $csv->combine(@cols);
3391 $content .= $csv->string;
3393 elsif($p->{'format'} eq 'xls') {
3396 $xls->write($xls_r,$xls_c++,$_);
3402 $xls_workbook->close() if $p->{'format'} eq 'xls';
3404 { content => $content, format => $p->{'format'}, };
3409 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3410 return { 'error' => $session } if $context eq 'error';
3412 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3413 # FS::TicketSystem->init();
3414 # return { 'error' => 'get_ticket configuration error' }
3415 # if $FS::TicketSystem::system ne 'RT_Internal';
3417 # check existence and ownership as part of this
3418 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3419 my $rt_session = FS::TicketSystem->session('');
3420 my $Ticket = FS::TicketSystem->get_ticket_object(
3422 ticket_id => $p->{'ticket_id'},
3425 return { 'error' => 'ticket not found' } if !$Ticket;
3427 if ( length( $p->{'subject'} || '' ) ) {
3429 if ( $p->{'subject'} ne $Ticket->Subject ) {
3430 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3431 return { 'error' => "unable to set subject: $msg" } if !$val;
3435 if(length($p->{'reply'})) {
3436 my @err_or_res = FS::TicketSystem->correspond_ticket(
3438 'ticket_id' => $p->{'ticket_id'},
3439 'content' => $p->{'reply'},
3442 return { 'error' => 'unable to reply to ticket' }
3443 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3446 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3447 my $err_or_ticket = FS::TicketSystem->get_ticket(
3449 'ticket_id' => $p->{'ticket_id'},
3452 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3453 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3455 return { 'error' => $err_or_ticket };
3458 my @custs = @{$err_or_ticket->{'custs'}};
3459 my @txns = @{$err_or_ticket->{'txns'}};
3462 # superseded by check in get_ticket_object
3463 #return { 'error' => 'invalid ticket requested' }
3464 #unless grep($_ eq $custnum, @custs);
3466 foreach my $txn ( @txns ) {
3467 push @filtered_txns, $txn
3468 if ($txn->{'type'} eq 'EmailRecord'
3469 || $txn->{'type'} eq 'Correspond'
3470 || $txn->{'type'} eq 'Create');
3473 warn "$me get_ticket: successful: \n"
3475 return { 'error' => '',
3476 'transactions' => \@filtered_txns,
3477 'ticket_fields' => $err_or_ticket->{'fields'},
3478 'ticket_id' => $p->{'ticket_id'},
3482 sub adjust_ticket_priority {
3484 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3485 return { 'error' => $session } if $context eq 'error';
3487 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3488 # FS::TicketSystem->init;
3489 my $ss_priority = FS::TicketSystem->selfservice_priority;
3491 return { 'error' => 'adjust_ticket_priority configuration error' }
3492 if $FS::TicketSystem::system ne 'RT_Internal'
3495 my $values = $p->{'values'}; #hashref, id => priority value
3498 foreach my $id (keys %$values) {
3499 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3500 my $Ticket = FS::TicketSystem->get_ticket_object('',
3502 'custnum' => $custnum,
3505 $ticket_error{$id} = 'ticket not found';
3509 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3510 # We're not going to implement it for RT_External.
3511 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3512 my $new_value = $values->{$id};
3513 next if $old_value eq $new_value;
3515 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3517 # AddCustomFieldValue works fine (replacing any existing value) if it's
3518 # a single-valued custom field, which it should be. If it's not, you're
3519 # doing something wrong.
3521 if ( length($new_value) ) {
3522 ($val, $msg) = $Ticket->AddCustomFieldValue(
3523 Field => $ss_priority,
3524 Value => $new_value,
3528 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3529 Field => $ss_priority,
3530 Value => $old_value,
3534 $ticket_error{$id} = $msg if !$val;
3535 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3537 return { 'error' => '',
3538 'ticket_error' => \%ticket_error,
3539 %{ customer_info($p) } # send updated customer info back
3545 sub _custoragent_session_custnum {
3548 my($context, $session, $custnum);
3549 if ( $p->{'session_id'} ) {
3551 $context = 'customer';
3552 $session = _cache->get($p->{'session_id'})
3553 or return ( 'error' => "Can't resume session" ); #better error message
3554 $custnum = $session->{'custnum'};
3556 } elsif ( $p->{'agent_session_id'} ) {
3559 my $agent_cache = new FS::ClientAPI_SessionCache( {
3560 'namespace' => 'FS::ClientAPI::Agent',
3562 $session = $agent_cache->get($p->{'agent_session_id'})
3563 or return ( 'error' => "Can't resume session" ); #better error message
3564 $custnum = $p->{'custnum'};
3568 return ( 'error' => "Can't resume session" ); #better error message
3571 ($context, $session, $custnum);