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 if ( $p->{'session_id'} ) {
312 _cache->remove($p->{'session_id'});
313 return { %{ skin_info($p) }, 'error' => '' };
315 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
322 my($context, $session, $custnum) = _custoragent_session_custnum($p);
323 return { 'error' => $session } if $context eq 'error';
325 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
326 or return { 'error' => "Service not found" };
328 $session->{'svcnum'} = $svc_acct->svcnum;
330 my $conf = new FS::Conf;
331 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
332 _cache->set( $p->{'session_id'}, $session, $timeout );
334 return { 'error' => '' };
338 sub payment_gateway {
340 # takes a cust_main and a cust_payby entry, returns the payment_gateway
341 my $conf = new FS::Conf;
342 my $cust_main = shift;
343 my $cust_payby = shift;
344 my $gatewaynum = $conf->config('selfservice-payment_gateway');
346 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
347 die "configured gatewaynum $gatewaynum not found!" if !$pg;
351 return '' if ! FS::payby->realtime($cust_payby);
352 my $pg = $cust_main->agent->payment_gateway(
353 'method' => FS::payby->payby2bop($cust_payby),
363 my $conf = new FS::Conf;
365 my $info = skin_info($p);
367 use vars qw( $cust_paybys ); #cache for performance
368 unless ( $cust_paybys ) {
370 my %cust_paybys = map { $_ => 1 }
371 map { FS::payby->payby2payment($_) }
372 $conf->config('signup_server-payby');
374 $cust_paybys = [ keys %cust_paybys ];
377 $info->{'cust_paybys'} = $cust_paybys;
379 my($context, $session, $custnum) = _custoragent_session_custnum($p);
380 return { 'error' => $session } if $context eq 'error';
382 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
383 or return { 'error' => "unknown custnum $custnum" };
385 $info->{'hide_payment_fields'} = [
387 my $pg = payment_gateway($cust_main, $_);
388 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
389 } @{ $info->{cust_paybys} }
392 $info->{'self_suspend_reason'} =
393 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
395 $info->{'edit_ticket_subject'} =
396 $conf->exists('ticket_system-selfservice_edit_subject') &&
397 $cust_main->edit_subject;
399 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
402 'custnum' => $custnum,
403 'access_pkgnum' => $session->{'pkgnum'},
404 'access_svcnum' => $session->{'svcnum'},
411 my($context, $session, $custnum) = _custoragent_session_custnum($p);
412 return { 'error' => $session } if $context eq 'error';
416 my $conf = new FS::Conf;
417 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
419 # if ( $FS::TicketSystem::system ) {
420 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
421 # FS::TicketSystem->init();
424 if ( $custnum ) { #customer record
426 %return = ( %return, %{ customer_info_short($p) } );
428 #redundant with customer_info_short, but we need it for several things below
429 my $search = { 'custnum' => $custnum };
430 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
431 my $cust_main = qsearchs('cust_main', $search )
432 or return { 'error' => "unknown custnum $custnum" };
434 my $list_tickets = list_tickets($p);
435 $return{'tickets'} = $list_tickets->{'tickets'};
437 if ( $session->{'pkgnum'} ) {
438 #XXX open invoices in the pkg-balances case
442 invnum => $_->invnum,
443 date => time2str("%b %o, %Y", $_->_date),
446 } $cust_main->open_cust_bill;
447 $return{open_invoices} = \@open;
449 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
450 my $sth = dbh->prepare($sql) or die dbh->errstr;
451 $sth->execute($custnum) or die $sth->errstr;
452 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
453 $return{'last_invoice_date_pretty'} =
454 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
457 #customer_info_short always has nobalance on..
458 $return{small_custview} =
459 small_custview( $cust_main,
460 $return{countrydefault},
461 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
464 $return{has_ship_address} = $cust_main->has_ship_address;
465 $return{status} = $cust_main->status;
466 $return{statuscolor} = $cust_main->statuscolor;
468 # compatibility: some places in selfservice use this to determine
469 # if there's a ship address
470 if ( $return{has_ship_address} ) {
471 $return{ship_last} = $cust_main->last;
472 $return{ship_first} = $cust_main->first;
475 if (scalar($conf->config('support_packages'))) {
476 my @support_services = ();
477 foreach ($cust_main->support_services) {
478 my $seconds = $_->svc_x->seconds || 0;
479 my $time_remaining = (($seconds < 0) ? '-' : '' ).
480 int(abs($seconds)/3600)."h".
481 sprintf("%02d",(abs($seconds)%3600)/60)."m";
482 my $cust_pkg = $_->cust_pkg;
485 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
486 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
487 push @support_services, { svcnum => $_->svcnum,
488 time => $time_remaining,
493 $return{support_services} = \@support_services;
496 if ( $conf->config('prepayment_discounts-credit_type') ) {
498 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
501 } elsif ( $session->{'svcnum'} ) { #no customer record
503 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
504 or die "unknown svcnum";
505 $return{name} = $svc_acct->email;
509 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
513 return { 'error' => '',
514 'custnum' => $custnum,
520 sub customer_info_short {
523 my($context, $session, $custnum) = _custoragent_session_custnum($p);
524 return { 'error' => $session } if $context eq 'error';
528 my $conf = new FS::Conf;
530 if ( $custnum ) { #customer record
532 my $search = { 'custnum' => $custnum };
533 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
534 my $cust_main = qsearchs('cust_main', $search )
535 or return { 'error' => "unknown custnum $custnum" };
537 $return{display_custnum} = $cust_main->display_custnum;
539 if ( $session->{'pkgnum'} ) {
540 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
541 #next_bill_date from cust_pkg?
543 $return{balance} = $cust_main->balance;
544 $return{next_bill_date} = $cust_main->next_bill_date;
545 $return{next_bill_date_pretty} =
546 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
550 $return{countrydefault} = scalar($conf->config('countrydefault'));
552 $return{small_custview} =
553 small_custview( $cust_main,
554 $return{countrydefault},
558 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
560 $return{payby} = $cust_main->payby;
562 #none of these are terribly expensive if we want 'em...
563 for (@cust_main_editable_fields) {
564 $return{$_} = $cust_main->get($_);
566 #maybe a little more expensive, but it should be cached by now
567 for (@location_editable_fields) {
568 $return{$_} = $cust_main->bill_location->get($_);
569 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
572 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
573 $return{payinfo} = $cust_main->paymask;
574 @return{'month', 'year'} = $cust_main->paydate_monthyear;
577 my @invoicing_list = $cust_main->invoicing_list;
578 $return{'invoicing_list'} =
579 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
580 $return{'postal_invoicing'} =
581 0 < ( grep { $_ eq 'POST' } @invoicing_list );
583 if ( $session->{'svcnum'} ) {
584 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
585 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
586 $return{'svcnum'} = $session->{'svcnum'};
589 } elsif ( $session->{'svcnum'} ) { #no customer record
591 #uuh, not supproted yet... die?
592 return { 'error' => 'customer_info_short not yet supported as agent' };
596 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
600 return { 'error' => '',
601 'custnum' => $custnum,
606 sub billing_history {
609 my($context, $session, $custnum) = _custoragent_session_custnum($p);
610 return { 'error' => $session } if $context eq 'error';
612 return { 'error' => 'No customer' } unless $custnum;
614 my $search = { 'custnum' => $custnum };
615 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
616 my $cust_main = qsearchs('cust_main', $search )
617 or return { 'error' => "unknown custnum $custnum" };
621 if ( $session->{'pkgnum'} ) {
622 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
623 #next_bill_date from cust_pkg?
624 return { 'error' => 'No history for package' };
627 $return{balance} = $cust_main->balance;
628 $return{next_bill_date} = $cust_main->next_bill_date;
629 $return{next_bill_date_pretty} =
630 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
635 my $conf = new FS::Conf;
637 if ( $conf->exists('selfservice-billing_history-line_items') ) {
639 foreach my $cust_bill ( $cust_main->cust_bill ) {
642 'type' => 'Line item',
643 'description' => $_->desc( $cust_main->locale ).
644 ( $_->sdate && $_->edate
645 ? ' '. time2str('%d-%b-%Y', $_->sdate).
646 ' To '. time2str('%d-%b-%Y', $_->edate)
649 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
650 'date' => $cust_bill->_date,
651 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
653 foreach $cust_bill->cust_bill_pkg;
661 'description' => 'Invoice #'. $_->display_invnum,
662 'amount' => sprintf('%.2f', $_->charged ),
664 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
666 foreach $cust_main->cust_bill;
672 'description' => 'Payment', #XXX type
673 'amount' => sprintf('%.2f', 0 - $_->paid ),
675 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
677 foreach $cust_main->cust_pay;
681 'description' => 'Credit', #more info?
682 'amount' => sprintf('%.2f', 0 -$_->amount ),
684 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
686 foreach $cust_main->cust_credit;
690 'description' => 'Refund', #more info? type, like payment?
691 'amount' => $_->refund,
693 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
695 foreach $cust_main->cust_refund;
697 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
699 $return{'history'} = \@history;
707 my $session = _cache->get($p->{'session_id'})
708 or return { 'error' => "Can't resume session" }; #better error message
710 my $custnum = $session->{'custnum'}
711 or return { 'error' => "no customer record" };
713 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
714 or return { 'error' => "unknown custnum $custnum" };
716 my $new = new FS::cust_main { $cust_main->hash };
718 $new->set( $_ => $p->{$_} )
719 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
721 if ( exists($p->{address1}) ) {
722 my $bill_location = FS::cust_location->new({
723 map { $_ => $p->{$_} } @location_editable_fields
725 # if this is unchanged from before, cust_main::replace will ignore it
726 $new->set('bill_location' => $bill_location);
729 if ( exists($p->{ship_address1}) ) {
730 my $ship_location = FS::cust_location->new({
731 map { $_ => $p->{"ship_$_"} } @location_editable_fields
733 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
734 # Selfservice unfortunately tries to indicate "same as billing
735 # address" by sending all fields empty. Did this ever work?
736 $ship_location = $cust_main->bill_location;
738 $new->set('ship_location' => $ship_location);
740 # but if it hasn't been passed in at all, leave ship_location alone--
741 # DON'T change it to match bill_location.
744 if (exists($p->{'payby'})) {
745 $p->{'payby'} =~ /^([A-Z]{4})$/
746 or return { 'error' => "illegal_payby " . $p->{'payby'} };
750 my $conf = new FS::Conf;
752 if ( $payby =~ /^(CARD|DCRD)$/ ) {
754 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
756 if ( $new->payinfo eq $cust_main->paymask ) {
757 $new->payinfo($cust_main->payinfo);
759 $new->payinfo($p->{'payinfo'});
762 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
764 if ( $conf->exists('selfservice-onfile_require_cvv') ){
765 return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
768 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
771 $p->{'payinfo1'} =~ /^([\dx]+)$/
772 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
774 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
775 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
777 $payinfo = $payinfo1. '@'. $payinfo2;
779 $new->payinfo( ($payinfo eq $cust_main->paymask)
780 ? $cust_main->payinfo
784 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
786 } elsif ( $payby =~ /^(BILL)$/ ) {
788 } elsif ( $payby ) { #notyet ready
789 return { 'error' => "unknown payby $payby" };
793 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
794 #false laziness with httemplate/edit/process/cust_main.cgi
795 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
796 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
798 @invoicing_list = $cust_main->invoicing_list;
801 my $error = $new->replace($cust_main, \@invoicing_list);
802 return { 'error' => $error } if $error;
805 return { 'error' => '' };
810 my $session = _cache->get($p->{'session_id'})
811 or return { 'error' => "Can't resume session" }; #better error message
817 my $conf = new FS::Conf;
818 use vars qw($payment_info); #cache for performance
819 unless ( $payment_info ) {
821 my %states = map { $_->state => 1 }
822 qsearch('cust_main_county', {
823 'country' => $conf->config('countrydefault') || 'US'
826 my %cust_paybys = map { $_ => 1 }
827 map { FS::payby->payby2payment($_) }
828 $conf->config('signup_server-payby');
830 my @cust_paybys = keys %cust_paybys;
834 #list all counties/states/countries
835 'cust_main_county' =>
836 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
838 #shortcut for one-country folks
840 [ sort { $a cmp $b } keys %states ],
842 'card_types' => card_types(),
844 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
845 'require_cvv' => $conf->exists('selfservice-require_cvv'),
846 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
848 'paytypes' => [ @FS::cust_main::paytypes ],
850 'paybys' => [ $conf->config('signup_server-payby') ],
851 'cust_paybys' => \@cust_paybys,
853 'stateid_label' => FS::Msgcat::_gettext('stateid'),
854 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
856 'show_ss' => $conf->exists('show_ss'),
857 'show_stateid' => $conf->exists('show_stateid'),
858 'show_paystate' => $conf->exists('show_bankstate'),
860 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
862 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
871 my %return = %$payment_info;
873 my $custnum = $session->{'custnum'};
875 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
876 or return { 'error' => "unknown custnum $custnum" };
878 $return{'hide_payment_fields'} = [
880 my $pg = payment_gateway($cust_main, $_);
881 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
882 } @{ $return{cust_paybys} }
885 $return{balance} = $cust_main->balance; #XXX pkg-balances?
887 $return{payname} = $cust_main->payname
888 || ( $cust_main->first. ' '. $cust_main->get('last') );
890 $return{$_} = $cust_main->bill_location->get($_)
891 for qw(address1 address2 city state zip);
893 $return{payby} = $cust_main->payby;
894 $return{stateid_state} = $cust_main->stateid_state;
896 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
897 $return{card_type} = cardtype($cust_main->payinfo);
898 $return{payinfo} = $cust_main->paymask;
900 @return{'month', 'year'} = $cust_main->paydate_monthyear;
904 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
905 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
906 $return{payinfo1} = $payinfo1;
907 $return{payinfo2} = $payinfo2;
908 $return{paytype} = $cust_main->paytype;
909 $return{paystate} = $cust_main->paystate;
910 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
913 if ( $conf->config('prepayment_discounts-credit_type') ) {
915 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
918 #doubleclick protection
920 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
921 $return{paybatch} = $return{payunique}; #back compat
923 return { 'error' => '',
929 #some false laziness with httemplate/process/payment.cgi - look there for
930 #ACH and CVV support stuff
932 sub validate_payment {
935 my $session = _cache->get($p->{'session_id'})
936 or return { 'error' => "Can't resume session" }; #better error message
938 my $custnum = $session->{'custnum'};
940 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
941 or return { 'error' => "unknown custnum $custnum" };
943 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
944 or return { 'error' => gettext('illegal_amount') };
946 return { error => 'Amount must be greater than 0' } unless $amount > 0;
948 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
949 #changing the hidden form values
950 my $conf = new FS::Conf;
951 my $fee_display = $conf->config('selfservice_process-display') || 'add';
952 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
953 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
954 if ( $fee_display eq 'add'
956 and ! $fee_skip_first || scalar($cust_main->cust_pay)
959 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
960 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
963 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
964 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
965 my $discount_term = $1;
967 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
968 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
971 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
972 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
975 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
976 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
979 $payunique = $paybatch if ! length($payunique) && length($paybatch);
981 $p->{'payby'} ||= 'CARD';
982 $p->{'payby'} =~ /^([A-Z]{4})$/
983 or return { 'error' => "illegal_payby " . $p->{'payby'} };
986 #false laziness w/process/payment.cgi
989 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
991 $p->{'payinfo1'} =~ /^([\dx]+)$/
992 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
994 $p->{'payinfo2'} =~ /^([\dx]+)$/
995 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
997 $payinfo = $payinfo1. '@'. $payinfo2;
999 $payinfo = $cust_main->payinfo
1000 if $cust_main->paymask eq $payinfo;
1002 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1004 $payinfo = $p->{'payinfo'};
1008 #more intelligent matching will be needed here if you change
1009 #card_masking_method and don't remove existing paymasks
1010 if ( $cust_main->paymask eq $payinfo ) {
1011 $payinfo = $cust_main->payinfo;
1015 $payinfo =~ s/\D//g;
1016 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1017 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1021 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1022 return { 'error' => gettext('unknown_card_type') }
1023 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1025 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1026 if ( cardtype($payinfo) eq 'American Express card' ) {
1027 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1028 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1031 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1032 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1035 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1036 return { 'error' => 'CVV2 is required' };
1037 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1038 return { 'error' => 'CVV2 is required' };
1042 die "unknown payby $payby";
1045 my %payby2fields = (
1046 'CARD' => [ qw( paystart_month paystart_year payissue payip
1047 address1 address2 city state zip country ) ],
1048 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1052 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1055 'cust_main' => $cust_main, #XXX or just custnum??
1056 'amount' => sprintf('%.2f', $amount),
1058 'payinfo' => $payinfo,
1059 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1060 'card_type' => $card_type,
1061 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1062 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1063 'month' => $p->{'month'},
1064 'year' => $p->{'year'},
1065 'payname' => $payname,
1066 'payunique' => $payunique,
1067 'paybatch' => $paybatch,
1068 'paycvv' => $paycvv,
1069 'payname' => $payname,
1070 'discount_term' => $discount_term,
1071 'pkgnum' => $session->{'pkgnum'},
1072 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1082 my $validate = validate_payment($p);
1083 return $validate if $validate->{'error'};
1085 my $conf = new FS::Conf;
1086 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1087 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1089 +{ map { $_=>$validate->{$_} }
1090 qw( card_type paymask payname paydate_pretty month year amount
1091 address1 address2 city state zip country
1097 sub process_stored_payment {
1100 my $session_id = $p->{'session_id'};
1102 my $payment_info = _cache->get( "payment_$session_id" )
1103 or return { 'error' => "Can't resume session" }; #better error message
1105 do_process_payment($payment_info);
1109 sub process_payment {
1112 my $payment_info = validate_payment($p);
1113 return $payment_info if $payment_info->{'error'};
1115 do_process_payment($payment_info);
1119 sub do_process_payment {
1120 my $validate = shift;
1122 my $cust_main = $validate->{'cust_main'};
1124 my $amount = delete $validate->{'amount'};
1127 my $payby = delete $validate->{'payby'};
1129 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1132 'paynum_ref' => \$paynum,
1135 return { 'error' => $error } if $error;
1137 #no error, so order the fee package if applicable...
1138 my $conf = new FS::Conf;
1139 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1140 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1142 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1144 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1146 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1147 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1150 #and generate an invoice for it now too
1151 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1152 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1157 $cust_main->apply_payments;
1159 if ( $validate->{'save'} ) {
1160 my $new = new FS::cust_main { $cust_main->hash };
1161 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1162 $new->set( $_ => $validate->{$_} )
1163 foreach qw( payname paystart_month paystart_year payissue payip );
1164 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1166 my $bill_location = FS::cust_location->new({
1167 map { $_ => $validate->{$_} }
1168 qw(address1 address2 city state country zip)
1170 $new->set('bill_location' => $bill_location);
1171 # but don't allow the service address to change this way.
1173 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1174 $new->set( $_ => $validate->{$_} )
1175 foreach qw( payname payip paytype paystate
1176 stateid stateid_state );
1177 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1179 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1180 $new->set( 'paydate' => $validate->{'paydate'} );
1181 my $error = $new->replace($cust_main);
1183 #no, this causes customers to process their payments again
1184 #return { 'error' => $error };
1185 #XXX just warn verosely for now so i can figure out how these happen in
1186 # the first place, eventually should redirect them to the "change
1187 #address" page but indicate the payment did process??
1188 delete($validate->{'payinfo'}); #don't want to log this!
1189 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1190 "NEW: ". Dumper($new)."\n".
1191 "OLD: ". Dumper($cust_main)."\n".
1192 "PACKET: ". Dumper($validate)."\n";
1200 my $receipt_html = '';
1202 # currently supported for realtime CC only; send receipt data to SS
1203 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1206 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1209 <TD ALIGN="right">Payment#</TD>
1210 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1214 <TD ALIGN="right">Date</TD>
1216 <TD BGCOLOR="#FFFFFF"><B>! .
1217 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1223 <TD ALIGN="right">Amount</TD>
1224 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1229 <TD ALIGN="right">Payment method</TD>
1230 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1243 'amount' => sprintf('%.2f', $cust_pay->paid),
1244 'date' => $cust_pay->_date,
1245 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1246 'time_pretty' => time2str('%T', $cust_pay->_date),
1247 'auth_num' => $cust_pay->auth,
1248 'order_num' => $cust_pay->order_number,
1249 'receipt_html' => $receipt_html,
1256 'receipt_html' => '',
1263 sub realtime_collect {
1266 my $session = _cache->get($p->{'session_id'})
1267 or return { 'error' => "Can't resume session" }; #better error message
1269 my $custnum = $session->{'custnum'};
1271 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1272 or return { 'error' => "unknown custnum $custnum" };
1275 if ( $p->{'amount'} ) {
1276 $amount = $p->{'amount'};
1278 elsif ( $session->{'pkgnum'} ) {
1279 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1282 $amount = $cust_main->balance;
1285 my $error = $cust_main->realtime_collect(
1286 'method' => $p->{'method'},
1287 'amount' => $amount,
1288 'pkgnum' => $session->{'pkgnum'},
1289 'session_id' => $p->{'session_id'},
1293 return { 'error' => $error } unless ref( $error );
1295 return { 'error' => '', amount => $amount, %$error };
1298 sub start_thirdparty {
1300 my $session = _cache->get($p->{'session_id'})
1301 or return { 'error' => "Can't resume session" }; #better error message
1302 my $custnum = $session->{'custnum'};
1303 my $cust_main = FS::cust_main->by_key($custnum);
1305 my $amount = $p->{'amount'}
1306 or return { error => 'no amount' };
1308 my $result = $cust_main->create_payment(
1309 'method' => $p->{'method'},
1310 'amount' => $p->{'amount'},
1311 'pkgnum' => $session->{'pkgnum'},
1312 'session_id' => $p->{'session_id'},
1315 if ( ref($result) ) { # hashref or error
1318 return { error => $result };
1322 sub finish_thirdparty {
1324 my $session_id = delete $p->{'session_id'};
1325 my $session = _cache->get($session_id)
1326 or return { 'error' => "Can't resume session" };
1327 my $custnum = $session->{'custnum'};
1328 my $cust_main = FS::cust_main->by_key($custnum);
1330 if ( $p->{_cancel} ) {
1331 # customer backed out of making a payment
1332 return $cust_main->cancel_payment( $session_id );
1334 my $result = $cust_main->execute_payment( $session_id, %$p );
1335 if ( ref($result) ) {
1338 return { error => $result };
1342 sub process_payment_order_pkg {
1345 my $hr = process_payment($p);
1346 return $hr if $hr->{'error'};
1351 sub process_payment_order_renew {
1354 my $hr = process_payment($p);
1355 return $hr if $hr->{'error'};
1360 sub process_prepay {
1364 my $session = _cache->get($p->{'session_id'})
1365 or return { 'error' => "Can't resume session" }; #better error message
1369 my $custnum = $session->{'custnum'};
1371 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1372 or return { 'error' => "unknown custnum $custnum" };
1374 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1375 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1383 return { 'error' => $error } if $error;
1385 return { 'error' => '',
1386 'amount' => $amount,
1387 'seconds' => $seconds,
1388 'duration' => duration_exact($seconds),
1389 'upbytes' => $upbytes,
1390 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1391 'downbytes' => $downbytes,
1392 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1393 'totalbytes'=> $totalbytes,
1394 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1401 my $session = _cache->get($p->{'session_id'})
1402 or return { 'error' => "Can't resume session" }; #better error message
1404 my $custnum = $session->{'custnum'};
1406 my $invnum = $p->{'invnum'};
1408 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1409 'custnum' => $custnum } )
1410 or return { 'error' => "Can't find invnum" };
1414 return { 'error' => '',
1415 'invnum' => $invnum,
1416 'invoice_text' => join('', $cust_bill->print_text ),
1417 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1424 my $session = _cache->get($p->{'session_id'})
1425 or return { 'error' => "Can't resume session" }; #better error message
1427 my $custnum = $session->{'custnum'};
1429 my $invnum = $p->{'invnum'};
1431 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1432 'custnum' => $custnum } )
1433 or return { 'error' => "Can't find invnum" };
1437 return { 'error' => '',
1438 'invnum' => $invnum,
1439 'invoice_pdf' => $cust_bill->print_pdf({
1440 'unsquelch_cdr' => 1,
1441 'locale' => $p->{'locale'},
1447 sub legacy_invoice {
1449 my $session = _cache->get($p->{'session_id'})
1450 or return { 'error' => "Can't resume session" }; #better error message
1452 my $custnum = $session->{'custnum'};
1454 my $legacyinvnum = $p->{'legacyinvnum'};
1457 'legacyinvnum' => $legacyinvnum,
1458 'custnum' => $custnum,
1461 my $legacy_cust_bill =
1462 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1463 || qsearchs('legacy_cust_bill', \%hash )
1464 or return { 'error' => "Can't find legacyinvnum" };
1468 return { 'error' => '',
1469 'legacyinvnum' => $legacyinvnum,
1470 'legacyid' => $legacy_cust_bill->legacyid,
1471 'invoice_html' => $legacy_cust_bill->content_html,
1476 sub legacy_invoice_pdf {
1478 my $session = _cache->get($p->{'session_id'})
1479 or return { 'error' => "Can't resume session" }; #better error message
1481 my $custnum = $session->{'custnum'};
1483 my $legacyinvnum = $p->{'legacyinvnum'};
1485 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1486 'legacyinvnum' => $legacyinvnum,
1487 'custnum' => $custnum,
1488 }) or return { 'error' => "Can't find legacyinvnum" };
1492 return { 'error' => '',
1493 'legacyinvnum' => $legacyinvnum,
1494 'legacyid' => $legacy_cust_bill->legacyid,
1495 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1503 #sessioning for this? how do we get the session id to the backend invoice
1504 # template so it can add it to the link, blah
1507 if ( $p->{'invnum'} ) {
1508 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1509 or return { 'error' => 'unknown invnum' };
1510 $agentnum = $cust_bill->cust_main->agentnum;
1513 my $templatename = $p->{'template'} || $p->{'templatename'};
1515 #false laziness-ish w/view/cust_bill-logo.cgi
1517 my $conf = new FS::Conf;
1518 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1519 $templatename = "_$1";
1524 my $filename = "logo$templatename.png";
1526 return { 'error' => '',
1527 'logo' => $conf->config_binary($filename, $agentnum),
1528 'content_type' => 'image/png', #should allow gif, jpg too
1535 my $session = _cache->get($p->{'session_id'})
1536 or return { 'error' => "Can't resume session" }; #better error message
1538 my $custnum = $session->{'custnum'};
1540 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1541 or return { 'error' => "unknown custnum $custnum" };
1543 my $conf = new FS::Conf;
1545 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1547 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1551 return { 'error' => '',
1552 'balance' => $cust_main->balance,
1555 my $owed = $_->owed;
1557 +{ 'invnum' => $_->invnum,
1558 '_date' => $_->_date,
1559 'date' => time2str("%b %o, %Y", $_->_date),
1560 'date_short' => time2str("%m-%d-%Y", $_->_date),
1561 'previous' => sprintf('%.2f', ($_->previous)[0]),
1562 'charged' => sprintf('%.2f', $_->charged),
1563 'owed' => sprintf('%.2f', $owed),
1564 'balance' => sprintf('%.2f', $balance),
1569 'legacy_invoices' => [
1571 +{ 'legacyinvnum' => $_->legacyinvnum,
1572 'legacyid' => $_->legacyid,
1573 '_date' => $_->_date,
1574 'date' => time2str("%b %o, %Y", $_->_date),
1575 'date_short' => time2str("%m-%d-%Y", $_->_date),
1576 'charged' => sprintf('%.2f', $_->charged),
1577 'has_content' => ( length($_->content_pdf)
1578 || length($_->content_html) ),
1588 my $session = _cache->get($p->{'session_id'})
1589 or return { 'error' => "Can't resume session" }; #better error message
1591 my $custnum = $session->{'custnum'};
1593 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1594 or return { 'error' => "unknown custnum $custnum" };
1596 my @errors = $cust_main->cancel( 'quiet'=>1 );
1598 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1600 return { 'error' => $error };
1607 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1608 return { 'error' => $session } if $context eq 'error';
1610 my $search = { 'custnum' => $custnum };
1611 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1612 my $cust_main = qsearchs('cust_main', $search )
1613 or return { 'error' => "unknown custnum $custnum" };
1615 my $conf = new FS::Conf;
1617 # the duplication below is necessary:
1618 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1619 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1620 # non-backwards-compatible change breaking the software of anyone using the API
1621 # instead of the stock selfservice
1622 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1623 if( $conf->exists('selfservice_server-view-wholesale') ) {
1624 return { 'svcnum' => $session->{'svcnum'},
1625 'custnum' => $custnum,
1626 'cust_pkg' => [ map {
1628 part_pkg => [ map $_->hashref, $_->part_pkg ],
1630 [ map $_->hashref, $_->available_part_svc ],
1632 [ map { my $ref = { $_->hash,
1633 label => [ $_->label ],
1635 $ref->{_password} = $_->svc_x->_password
1636 if $context eq 'agent'
1637 && $conf->exists('agent-showpasswords')
1638 && $_->part_svc->svcdb eq 'svc_acct';
1643 } $cust_main->cust_pkg
1646 small_custview( $cust_main, $conf->config('countrydefault') ),
1647 'wholesale_view' => 1,
1648 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1649 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1650 'lnp' => $conf->exists('svc_phone-lnp'),
1654 { 'svcnum' => $session->{'svcnum'},
1655 'custnum' => $custnum,
1656 'cust_pkg' => [ map {
1657 my $primary_cust_svc = $_->primary_cust_svc;
1660 pkg_label => $_->pkg_locale,
1661 status => $_->status,
1662 statuscolor => $_->statuscolor,
1664 [ map { $_->hashref }
1665 grep { $_->selfservice_access ne 'hidden' }
1666 $_->available_part_svc
1669 [ map { my $ref = { $_->hash,
1670 label => [ $_->label ],
1672 $ref->{_password} = $_->svc_x->_password
1673 if $context eq 'agent'
1674 && $conf->exists('agent-showpasswords')
1675 && $_->part_svc->svcdb eq 'svc_acct';
1676 $ref->{svchash} = { $_->svc_x->hash } if
1677 $_->part_svc->svcdb eq 'svc_phone';
1678 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1679 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1682 grep { $_->part_svc->selfservice_access ne 'hidden' }
1687 ? { $primary_cust_svc->hash,
1688 label => [ $primary_cust_svc->label ],
1689 finger => $primary_cust_svc->svc_x->finger, #uuh
1690 $primary_cust_svc->part_svc->hash,
1694 } $cust_main->ncancelled_pkgs
1697 small_custview( $cust_main, $conf->config('countrydefault') ),
1698 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1706 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1707 return { 'error' => $session } if $context eq 'error';
1709 my $search = { 'custnum' => $custnum };
1710 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1711 my $cust_main = qsearchs('cust_main', $search )
1712 or return { 'error' => "unknown custnum $custnum" };
1714 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1715 if ( ! $pkgnum && $p->{'svcnum'} ) {
1716 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1717 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1721 my @cust_pkg_usage = ();
1722 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1723 foreach my $cust_pkg ( $p->{'ncancelled'}
1724 ? $cust_main->ncancelled_pkgs
1725 : $cust_main->unsuspended_pkgs ) {
1726 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1727 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1728 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1731 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1733 foreach (@cust_pkg_usage) {
1734 my $part = $_->part_pkg_usage;
1735 my $tag = $part->description . ($part->shared ? 1 : 0);
1736 my $row = $usage_pools{$tag}
1737 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1738 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1739 $row->[2] += $part->minutes; # minutes total
1742 if ( $p->{'svcdb'} ) {
1743 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1745 : ref($p->{'svcdb'}) eq 'ARRAY'
1746 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1747 : { $p->{'svcdb'} => 1 };
1748 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1751 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1754 my $conf = new FS::Conf;
1757 'svcnum' => $session->{'svcnum'},
1758 'custnum' => $custnum,
1759 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1760 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1763 my $svc_x = $_->svc_x;
1764 my($label, $value) = $_->label;
1765 my $part_svc = $_->part_svc;
1766 my $svcdb = $part_svc->svcdb;
1767 my $cust_pkg = $_->cust_pkg;
1768 my $part_pkg = $cust_pkg->part_pkg;
1771 'svcnum' => $_->svcnum,
1772 'display_svcnum' => $_->display_svcnum,
1776 'pkg_label' => $cust_pkg->pkg_locale,
1777 'pkg_status' => $cust_pkg->status,
1778 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1781 if ( $svcdb eq 'svc_acct' ) {
1784 'username' => $svc_x->username,
1785 'email' => $svc_x->email,
1786 'finger' => $svc_x->finger,
1787 'seconds' => $svc_x->seconds,
1788 'upbytes' => display_bytecount($svc_x->upbytes),
1789 'downbytes' => display_bytecount($svc_x->downbytes),
1790 'totalbytes' => display_bytecount($svc_x->totalbytes),
1792 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1793 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1794 'recharge_upbytes' =>
1795 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1796 'recharge_downbytes' =>
1797 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1798 'recharge_totalbytes' =>
1799 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1803 } elsif ( $svcdb eq 'svc_dsl' ) {
1804 $hash{'phonenum'} = $svc_x->phonenum;
1805 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1806 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1807 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1810 $hash{'name'} = $cust_main->name;
1812 } elsif ( $svcdb eq 'svc_phone' ) {
1813 # could potentially show lots of things...
1814 $hash{'outbound'} = 1;
1815 $hash{'inbound'} = 0;
1816 if ( $part_pkg->plan eq 'voip_inbound' ) {
1817 $hash{'outbound'} = 0;
1818 $hash{'inbound'} = 1;
1819 } elsif ( $part_pkg->option('selfservice_inbound_format')
1820 or $conf->config('selfservice-default_inbound_cdr_format')
1822 $hash{'inbound'} = 1;
1824 foreach (qw(inbound outbound)) {
1825 # hmm...we can't filter by status here, because there might
1826 # not be cdr_terminations at all. have to go by date.
1827 # find all since the last bill date.
1828 # XXX cdr types? we are going to need them.
1830 my $sum_cdr = $svc_x->sum_cdrs(
1831 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1832 'begin' => ($cust_pkg->last_bill || 0),
1834 'disable_charged_party' => 1,
1836 $hash{$_} = $sum_cdr->hashref;
1841 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1852 map { $usage_pools{$_} }
1860 sub _customer_svc_x {
1861 my($custnum, $svcnum, $table) = (shift, shift, shift);
1862 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1864 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1865 my $search = " AND custnum = $1";
1866 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1869 'table' => ($table || 'svc_acct'),
1870 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1871 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1872 #'LEFT JOIN cust_main USING ( custnum ) ',
1873 'hashref' => $hashref,
1874 'extra_sql' => $search, #important
1879 sub svc_status_html {
1882 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1883 return { 'error' => $session } if $context eq 'error';
1885 #XXX only svc_dsl for now
1886 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1887 or return { 'error' => "Service not found" };
1889 my $html = $svc_x->getstatus_html;
1891 return { 'html' => $html };
1895 sub svc_status_hash {
1898 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1899 return { 'error' => $session } if $context eq 'error';
1901 #XXX only svc_acct for now
1902 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1903 or return { 'error' => "Service not found" };
1905 my ( $html, $hashref ) = $svc_x->export_getstatus;
1910 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1911 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1912 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1913 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1914 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1917 my( $p, $method ) = @_;
1919 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1920 return { 'error' => $session } if $context eq 'error';
1922 #XXX only svc_acct for now
1923 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1924 or return { 'error' => "Service not found" };
1926 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1928 my $error = $svc_x->$method($p); #$p? returns error?
1929 return { 'error' => $error } if $error;
1931 return {}; #? { 'error' => '' }
1935 sub acct_forward_info {
1938 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1939 return { 'error' => $session } if $context eq 'error';
1941 my $svc_forward = _customer_svc_x( $custnum,
1942 { 'srcsvc' => $p->{'svcnum'} },
1945 or return { 'error' => '',
1949 return { 'error' => '',
1950 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1955 sub process_acct_forward {
1957 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1958 return { 'error' => $session } if $context eq 'error';
1960 my $old = _customer_svc_x( $custnum,
1961 { 'srcsvc' => $p->{'svcnum'} },
1965 if ( $p->{'dst'} eq '' ) {
1967 my $error = $old->delete;
1968 return { 'error' => $error };
1970 return { 'error' => '' };
1973 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1974 'dst' => $p->{'dst'},
1979 $new->svcnum($old->svcnum);
1980 my $cust_svc = $old->cust_svc;
1981 $new->svcpart($old->svcpart);
1982 $new->pkgnuym($old->pkgnum);
1983 $error = $new->replace($old);
1985 my $conf = new FS::Conf;
1986 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1988 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1989 or return { 'error' => 'No service' }; #how would we even get here?
1991 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1993 $error = $new->insert;
1996 return { 'error' => $error };
2000 sub list_dsl_devices {
2003 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2004 return { 'error' => $session } if $context eq 'error';
2006 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2007 or return { 'error' => "Service not found" };
2010 'devices' => [ map {
2011 +{ 'mac_addr' => $_->mac_addr };
2012 } $svc_dsl->dsl_device
2018 sub add_dsl_device {
2021 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2022 return { 'error' => $session } if $context eq 'error';
2024 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2025 or return { 'error' => "Service not found" };
2027 return { 'error' => 'No MAC address supplied' }
2028 unless length($p->{'mac_addr'});
2030 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2031 'mac_addr' => scalar($p->{'mac_addr'}),
2033 my $error = $dsl_device->insert;
2034 return { 'error' => $error };
2038 sub delete_dsl_device {
2041 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2042 return { 'error' => $session } if $context eq 'error';
2044 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2045 or return { 'error' => "Service not found" };
2047 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2048 'mac_addr' => scalar($p->{'mac_addr'}),
2051 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2053 my $error = $dsl_device->delete;
2054 return { 'error' => $error };
2060 _usage_details( \&_port_graph, $p,
2061 'svcdb' => 'svc_port',
2066 my($svc_port, $begin, $end) = @_;
2068 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2069 push @usage, { 'png' => $pngOrError };
2073 sub _list_svc_usage {
2074 my($svc_acct, $begin, $end) = @_;
2076 foreach my $part_export (
2077 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2078 qw( sqlradius sqlradius_withdomain )
2080 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2085 sub list_svc_usage {
2086 _usage_details(\&_list_svc_usage, @_);
2089 sub _list_support_usage {
2090 my($svc_acct, $begin, $end) = @_;
2092 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2093 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2095 push @usage, { 'seconds' => $_->seconds,
2096 'support' => $_->support,
2097 '_date' => $_->_date,
2098 'id' => $_->transaction_id,
2099 'creator' => $_->creator,
2100 'subject' => $_->subject,
2101 'status' => $_->status,
2102 'ticketid' => $_->ticketid,
2108 sub list_support_usage {
2109 _usage_details(\&_list_support_usage, @_);
2112 sub _list_cdr_usage {
2113 # XXX CDR type support...
2114 # XXX any way to do a paged search on this?
2115 # we have to return the results all at once...
2116 my($svc_phone, $begin, $end, %opt) = @_;
2117 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2118 $svc_phone->get_cdrs(
2121 'disable_charged_party' => 1,
2126 sub list_cdr_usage {
2128 _usage_details( \&_list_cdr_usage, $p,
2129 'svcdb' => 'svc_phone',
2133 sub _usage_details {
2134 my($callback, $p, %opt) = @_;
2135 my $conf = FS::Conf->new;
2137 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2138 return { 'error' => $session } if $context eq 'error';
2140 my $search = { 'svcnum' => $p->{'svcnum'} };
2141 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2143 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2145 my $svc_x = qsearchs( $svcdb, $search );
2146 return { 'error' => 'No service selected in list_svc_usage' }
2149 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2150 my $freq = $cust_pkg->part_pkg->freq;
2153 if ( $svcdb eq 'svc_phone' ) {
2155 if ( $p->{inbound} ) {
2156 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2157 || $conf->config('selfservice-default_inbound_cdr_format')
2158 || 'source_default';
2159 $callback_opt{inbound} = 1;
2161 $format = $cust_pkg->part_pkg->option('selfservice_format')
2162 || $conf->config('selfservice-default_cdr_format')
2166 $callback_opt{format} = $format;
2167 $callback_opt{use_clid} = 1;
2168 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2171 my $start = $cust_pkg->setup;
2172 #my $end = $cust_pkg->bill; # or time?
2175 unless ( $p->{beginning} ) {
2176 $p->{beginning} = $cust_pkg->last_bill;
2177 $p->{ending} = $end;
2180 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2181 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2183 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2187 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2188 # ugly kludge, I know
2189 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2190 if (defined $delete_col) {
2191 delete($_->[$delete_col]) foreach ($header, @usage);
2195 #kinda false laziness with FS::cust_main::bill, but perhaps
2196 #we should really change this bit to DateTime and DateTime::Duration
2198 #change this bit to use Date::Manip? CAREFUL with timezones (see
2199 # mailing list archive)
2200 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2201 (localtime($p->{ending}) )[0,1,2,3,4,5];
2202 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2203 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2205 if ( $freq =~ /^\d+$/ ) {
2207 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2209 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2210 } elsif ( $freq =~ /^(\d+)w$/ ) {
2212 $nmday += $weeks * 7;
2213 $pmday -= $weeks * 7;
2214 } elsif ( $freq =~ /^(\d+)d$/ ) {
2218 } elsif ( $freq =~ /^(\d+)h$/ ) {
2223 return { 'error' => "unparsable frequency: ". $freq };
2226 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2227 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2231 'svcnum' => $p->{svcnum},
2232 'beginning' => $p->{beginning},
2233 'ending' => $p->{ending},
2234 'inbound' => $p->{inbound},
2235 'previous' => ($previous > $start) ? $previous : $start,
2236 'next' => ($next < $end) ? $next : $end,
2237 'header' => $header,
2245 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2246 return { 'error' => $session } if $context eq 'error';
2248 my $search = { 'custnum' => $custnum };
2249 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2250 my $cust_main = qsearchs('cust_main', $search )
2251 or return { 'error' => "unknown custnum $custnum" };
2253 my $status = $cust_main->status;
2254 #false laziness w/ClientAPI/Signup.pm
2256 my $cust_pkg = new FS::cust_pkg ( {
2257 'custnum' => $custnum,
2258 'pkgpart' => $p->{'pkgpart'},
2260 my $error = $cust_pkg->check;
2261 return { 'error' => $error } if $error;
2264 unless ( $p->{'svcpart'} eq 'none' ) {
2268 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2270 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2271 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2272 $svcdb = $part_svc->svcdb;
2274 $svcdb = 'svc_acct';
2276 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2279 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2280 'svc_domain' => [ qw( domain ) ],
2281 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2282 'svc_external' => [ qw( id title ) ],
2283 'svc_pbx' => [ qw( id title ) ],
2286 my $svc_x = "FS::$svcdb"->new( {
2287 'svcpart' => $svcpart,
2288 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2291 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2294 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2295 my $acct_snarf = new FS::acct_snarf ( {
2296 'machine' => $p->{"snarf_machine$snarfnum"},
2297 'protocol' => $p->{"snarf_protocol$snarfnum"},
2298 'username' => $p->{"snarf_username$snarfnum"},
2299 '_password' => $p->{"snarf_password$snarfnum"},
2302 push @acct_snarf, $acct_snarf;
2304 $svc_x->child_objects( \@acct_snarf );
2307 my $y = $svc_x->setdefault; # arguably should be in new method
2308 return { 'error' => $y } if $y && !ref($y);
2310 $error = $svc_x->check;
2311 return { 'error' => $error } if $error;
2318 tie my %hash, 'Tie::RefHash';
2319 %hash = ( $cust_pkg => \@svc );
2321 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2322 return { 'error' => $error } if $error;
2324 my $conf = new FS::Conf;
2325 if ( $conf->exists('signup_server-realtime') ) {
2327 my $bill_error = _do_bop_realtime( $cust_main, $status );
2330 $cust_pkg->cancel('quiet'=>1);
2333 $cust_pkg->reexport;
2337 $cust_pkg->reexport;
2340 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2342 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2349 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2350 return { 'error' => $session } if $context eq 'error';
2352 my $search = { 'custnum' => $custnum };
2353 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2354 my $cust_main = qsearchs('cust_main', $search )
2355 or return { 'error' => "unknown custnum $custnum" };
2357 my $status = $cust_main->status;
2358 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2359 or return { 'error' => "unknown package $p->{pkgnum}" };
2361 #if someone does need self-service package change of suspended packages,
2362 # figure out how to be more discriminating
2363 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2364 if $cust_pkg->status eq 'suspended';
2367 my $error = FS::cust_pkg::order( $custnum,
2373 my $conf = new FS::Conf;
2374 if ( $conf->exists('signup_server-realtime') ) {
2376 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2379 $newpkg[0]->suspend;
2382 $newpkg[0]->reexport;
2386 $newpkg[0]->reexport;
2389 return { error => '', pkgnum => $cust_pkg->pkgnum };
2393 sub order_recharge {
2396 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2397 return { 'error' => $session } if $context eq 'error';
2399 my $search = { 'custnum' => $custnum };
2400 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2401 my $cust_main = qsearchs('cust_main', $search )
2402 or return { 'error' => "unknown custnum $custnum" };
2404 my $status = $cust_main->status;
2405 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2406 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2408 my $svc_x = $cust_svc->svc_x;
2409 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2412 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2413 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2414 recharge_totalbytes );
2415 my $amount = $part_pkg->option('recharge_amount', 1);
2417 my ($l, $v, $d) = $cust_svc->label; # blah
2418 my $pkg = "Recharge $v";
2420 my $bill_error = $cust_main->charge($amount, $pkg,
2421 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2422 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2423 $part_pkg->taxclass); #meh
2425 my $conf = new FS::Conf;
2426 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2428 $bill_error = _do_bop_realtime( $cust_main, $status );
2433 my $error = $svc_x->recharge (\%vhash);
2434 return { 'error' => $error } if $error;
2438 my $error = $bill_error;
2439 $error ||= $svc_x->recharge (\%vhash);
2440 return { 'error' => $error } if $error;
2443 return { error => '', svc => $cust_svc->part_svc->svc };
2447 sub _do_bop_realtime {
2448 my ($cust_main, $status, %opt) = @_;
2450 my $old_balance = $cust_main->balance;
2452 my $bill_error = $cust_main->bill
2453 || $cust_main->apply_payments_and_credits;
2455 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2456 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2458 if ( $cust_main->balance > $old_balance
2459 && $cust_main->balance > 0
2460 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2461 || $status eq 'suspended'
2465 unless ( $opt{'no_credit'} ) {
2466 #this makes sense. credit is "un-doing" the invoice
2467 my $conf = new FS::Conf;
2468 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2469 'self-service decline',
2470 reason_type=>$conf->config('signup_credit_type'),
2472 $cust_main->apply_credits( 'order' => 'newest' );
2475 return { 'error' => '_decline', 'bill_error' => $bill_error };
2484 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2485 return { 'error' => $session } if $context eq 'error';
2487 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2488 or return { 'error' => "unknown custnum $custnum" };
2490 my @cust_pkg = sort { $a->bill <=> $b->bill }
2491 grep { $_->part_pkg->freq ne '0' }
2492 $cust_main->ncancelled_pkgs;
2494 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2496 my $total = $cust_main->balance;
2499 my $bill = $_->bill;
2500 $total += $_->part_pkg->base_recur($_, \$bill);
2501 my $renew_date = $_->part_pkg->add_freq($_->bill);
2503 'pkgnum' => $_->pkgnum,
2504 'amount' => sprintf('%.2f', $total),
2505 'bill_date' => $_->bill,
2506 'bill_date_pretty' => time2str('%x', $_->bill),
2507 'renew_date' => $renew_date,
2508 'renew_date_pretty' => time2str('%x', $renew_date),
2509 'expire_date' => $_->expire,
2510 'expire_date_pretty' => time2str('%x', $_->expire),
2515 return { 'dates' => \@array };
2519 sub payment_info_renew_info {
2521 my $renew_info = renew_info($p);
2522 my $payment_info = payment_info($p);
2523 return { %$renew_info,
2531 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2532 return { 'error' => $session } if $context eq 'error';
2534 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2535 or return { 'error' => "unknown custnum $custnum" };
2537 my $date = $p->{'date'};
2541 #freeside-daily -n -d $date fs_daily $custnum
2542 $cust_main->bill_and_collect( 'time' => $date,
2543 'invoice_time' => $now,
2544 'actual_time' => $now,
2545 'check_freq' => '1d',
2548 return { 'error' => '' };
2554 my $session = _cache->get($p->{'session_id'})
2555 or return { 'error' => "Can't resume session" }; #better error message
2557 my $custnum = $session->{'custnum'};
2559 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2560 or return { 'error' => "unknown custnum $custnum" };
2562 my $conf = new FS::Conf;
2564 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2565 or return { 'error' => 'Permission denied' };
2567 my $pkgnum = $p->{'pkgnum'};
2569 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2570 'pkgnum' => $pkgnum, } )
2571 or return { 'error' => "unknown pkgnum $pkgnum" };
2573 my $error = $cust_pkg->suspend(reason => $reasonnum);
2574 return { 'error' => $error };
2580 my $session = _cache->get($p->{'session_id'})
2581 or return { 'error' => "Can't resume session" }; #better error message
2583 my $custnum = $session->{'custnum'};
2585 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2586 or return { 'error' => "unknown custnum $custnum" };
2588 my $pkgnum = $p->{'pkgnum'};
2590 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2591 'pkgnum' => $pkgnum, } )
2592 or return { 'error' => "unknown pkgnum $pkgnum" };
2594 my $error = $cust_pkg->cancel('quiet' => 1);
2595 return { 'error' => $error };
2599 sub provision_phone {
2602 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2604 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2605 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2606 return { 'error' => $session } if $context eq 'error';
2608 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2609 return { 'error' => 'service not found' } unless $svc_phone;
2610 return { 'error' => 'invalid svcnum' }
2611 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2613 $svc_phone->email($p->{'email'})
2614 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2615 $svc_phone->forwarddst($p->{'forwarddst'})
2616 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2617 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2618 return { 'error' => $svc_phone->replace };
2622 unless($p->{'lnp'}) {
2623 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2624 $p->{'lnp_status'} = "portingin";
2625 return _provision( 'FS::svc_phone',
2626 [qw(lnp_desired_due_date lnp_other_provider
2627 lnp_other_provider_account phonenum countrycode lnp_status)],
2628 [qw(phonenum countrycode)],
2635 unless (scalar(@bulkdid)) {
2636 return _provision( 'FS::svc_phone',
2637 [qw(phonenum countrycode)],
2638 [qw(phonenum countrycode)],
2644 # bulk DID order case
2646 foreach my $did ( @bulkdid ) {
2647 $did =~ s/[^0-9]//g;
2648 $error = _provision( 'FS::svc_phone',
2649 [qw(phonenum countrycode)],
2650 [qw(phonenum countrycode)],
2652 'pkgnum' => $p->{'pkgnum'},
2653 'svcpart' => $p->{'svcpart'},
2655 'countrycode' => $p->{'countrycode'},
2656 'session_id' => $p->{'session_id'},
2659 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2661 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2664 sub provision_acct {
2666 warn "provision_acct called\n"
2669 return { 'error' => gettext('passwords_dont_match') }
2670 if $p->{'_password'} ne $p->{'_password2'};
2671 return { 'error' => gettext('empty_password') }
2672 unless length($p->{'_password'});
2674 if ($p->{'domsvc'}) {
2675 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2676 qw ( svcpart pkgnum ) );
2677 return { 'error' => gettext('invalid_domain') }
2678 unless ($domains{$p->{'domsvc'}});
2681 warn "provision_acct calling _provision\n"
2683 _provision( 'FS::svc_acct',
2684 [qw(username _password domsvc)],
2685 [qw(username _password domsvc)],
2691 sub provision_external {
2693 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2694 _provision( 'FS::svc_external',
2703 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2704 warn "_provision called for $class\n"
2707 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2708 return { 'error' => $session } if $context eq 'error';
2710 my $search = { 'custnum' => $custnum };
2711 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2712 my $cust_main = qsearchs('cust_main', $search )
2713 or return { 'error' => "unknown custnum $custnum" };
2715 my $pkgnum = $p->{'pkgnum'};
2717 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2719 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2720 'pkgnum' => $pkgnum,
2722 or return { 'error' => "unknown pkgnum $pkgnum" };
2724 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2726 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2727 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2729 warn "creating $class record\n"
2731 my $svc_x = $class->new( {
2732 'pkgnum' => $p->{'pkgnum'},
2733 'svcpart' => $p->{'svcpart'},
2734 map { $_ => $p->{$_} } @$fields
2736 warn "inserting $class record\n"
2738 my $error = $svc_x->insert;
2741 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2743 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2746 my $return = { 'svc' => $part_svc->svc,
2748 map { $_ => $svc_x->get($_) } @$return_fields
2750 warn "_provision returning ". Dumper($return). "\n"
2759 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2760 return { 'error' => $session } if $context eq 'error';
2762 my $search = { 'custnum' => $custnum };
2763 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2764 my $cust_main = qsearchs('cust_main', $search )
2765 or return { 'error' => "unknown custnum $custnum" };
2767 my $pkgnum = $p->{'pkgnum'};
2769 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2770 'pkgnum' => $pkgnum,
2772 or return { 'error' => "unknown pkgnum $pkgnum" };
2774 my $svcpart = $p->{'svcpart'};
2776 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2777 'svcpart' => $svcpart, } )
2778 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2779 my $part_svc = $pkg_svc->part_svc;
2781 my $conf = new FS::Conf;
2784 'svc' => $part_svc->svc,
2785 'svcdb' => $part_svc->svcdb,
2786 'pkgnum' => $pkgnum,
2787 'svcpart' => $svcpart,
2788 'custnum' => $custnum,
2790 'security_phrase' => 0, #XXX !
2791 'svc_acct_pop' => [], #XXX !
2793 'init_popstate' => '',
2798 small_custview( $cust_main, $conf->config('countrydefault') ),
2802 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2803 && $ret->{'svcdb'} eq 'svc_phone') {
2804 $ret->{'svcnum'} = $p->{'svcnum'};
2805 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2806 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2807 $ret->{'email'} = $svc_phone->email;
2808 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2815 sub unprovision_svc {
2818 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2819 return { 'error' => $session } if $context eq 'error';
2821 my $search = { 'custnum' => $custnum };
2822 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2823 my $cust_main = qsearchs('cust_main', $search )
2824 or return { 'error' => "unknown custnum $custnum" };
2826 my $svcnum = $p->{'svcnum'};
2828 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2829 or return { 'error' => "unknown svcnum $svcnum" };
2831 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2832 unless $cust_svc->cust_pkg->custnum == $custnum;
2834 my $conf = new FS::Conf;
2836 return { 'svc' => $cust_svc->part_svc->svc,
2837 'error' => $cust_svc->cancel,
2839 small_custview( $cust_main, $conf->config('countrydefault') ),
2844 sub myaccount_passwd {
2846 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2847 return { 'error' => $session } if $context eq 'error';
2849 return { 'error' => "New passwords don't match." }
2850 if $p->{'new_password'} ne $p->{'new_password2'};
2852 return { 'error' => 'Enter new password' }
2853 unless length($p->{'new_password'});
2855 #my $search = { 'custnum' => $custnum };
2856 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2857 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2858 my $search = " AND custnum = $1";
2859 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2861 my $svc_acct = qsearchs( {
2862 'table' => 'svc_acct',
2863 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2864 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2865 'LEFT JOIN cust_main USING ( custnum ) ',
2866 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2867 'extra_sql' => $search, #important
2869 or return { 'error' => "Service not found" };
2873 my $conf = new FS::Conf;
2875 return { 'error' => 'Incorrect current password.' }
2876 if ( exists($p->{'old_password'})
2877 || $conf->exists('selfservice-password_change_oldpass')
2879 && ! $svc_acct->check_password($p->{'old_password'});
2881 $error = 'Password too short.'
2882 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2883 $error = 'Password too long.'
2884 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2886 $svc_acct->set_password($p->{'new_password'});
2887 $error ||= $svc_acct->replace();
2889 #regular pw change in self-service should change contact pw too, otherwise its
2890 #way too confusing. hell its confusing they're separate at all, but alas.
2891 #need to support the "ISP provides email that's used as a contact email" case
2893 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2894 if ( $contact && $contact->custnum == $custnum ) {
2895 #svc_acct was successful but this one returns an error? "shouldn't happen"
2896 $error ||= $contact->change_password($p->{'new_password'});
2899 my($label, $value) = $svc_acct->cust_svc->label;
2901 return { 'error' => $error,
2908 # sub contact_passwd {
2910 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2911 # return { 'error' => $session } if $context eq 'error';
2913 # return { 'error' => 'Not logged in as a contact.' }
2914 # unless $session->{'contactnum'};
2916 # return { 'error' => "New passwords don't match." }
2917 # if $p->{'new_password'} ne $p->{'new_password2'};
2919 # return { 'error' => 'Enter new password' }
2920 # unless length($p->{'new_password'});
2922 # #my $search = { 'custnum' => $custnum };
2923 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2924 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2925 # my $search = " AND selfservice_access IS NOT NULL ".
2926 # " AND selfservice_access = 'Y' ".
2927 # " AND ( disabled IS NULL OR disabled = '' )".
2928 # " AND custnum IS NOT NULL AND custnum = $1";
2929 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2931 # my $contact = qsearchs( {
2932 # 'table' => 'contact',
2933 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2934 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2935 # 'extra_sql' => $search, #important
2937 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2938 # # deleted since then?
2942 # # use these svc_acct length restrictions??
2943 # my $conf = new FS::Conf;
2944 # $error = 'Password too short.'
2945 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2946 # $error = 'Password too long.'
2947 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2949 # $error ||= $contact->change_password($p->{'new_password'});
2951 # return { 'error' => $error, };
2958 my $info = skin_info($p);
2960 my $conf = new FS::Conf;
2961 my $verification = $conf->config('selfservice-password_reset_verification')
2962 or return { %$info, 'error' => 'Password resets disabled' };
2967 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2969 $contact = FS::contact->by_selfservice_email($p->{'email'});
2971 $cust_main = $contact->cust_main if $contact;
2973 #also look for an svc_acct, otherwise it would be super confusing
2975 my($username, $domain) = split('@', $p->{'email'});
2976 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2977 if ( $svc_domain ) {
2978 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2979 'domsvc' => $svc_domain->svcnum }
2982 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2983 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
2985 #precaution: don't change svc_acct password not part of the same
2986 # customer as contact
2987 $svc_acct = '' if ! $cust_pkg
2988 || $cust_pkg->custnum != $cust_main->custnum;
2993 return { %$info, 'error' => 'Email address not found' }
2994 unless $contact || $svc_acct;
2996 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
2998 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2999 or return { %$info, 'error' => 'Account not found' };
3001 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3002 'domsvc' => $svc_domain->svcnum }
3004 or return { %$info, 'error' => 'Account not found' };
3006 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3007 or return { %$info, 'error' => 'Account not found' };
3009 $cust_main = $cust_pkg->cust_main;
3014 'email' => sub { 1; },
3016 my( $p, $cust_main ) = @_;
3017 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3018 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3021 my( $p, $cust_main ) = @_;
3022 my $cust_pay = qsearchs({
3023 'table' => 'cust_pay',
3024 'hashref' => { 'custnum' => $cust_main->custnum },
3025 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3029 $p->{'amount'} == $cust_pay->paid;
3032 my( $p, $cust_main ) = @_;
3033 $p->{'zip'} eq $cust_main->zip
3034 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3038 foreach my $verify ( split(',', $verification) ) {
3040 &{ $verify{$verify} }( $p, $cust_main )
3041 or return { %$info, 'error' => 'Account not found' };
3045 #okay, we're verified
3049 my $error = $contact->send_reset_email(
3050 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3054 return { %$info, 'error' => $error }; #????
3057 } elsif ( $svc_acct ) {
3059 #create a unique session
3061 my $reset_session = {
3062 'svcnum' => $svc_acct->svcnum,
3066 my $timeout = '1 hour'; #?
3068 my $reset_session_id;
3070 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3071 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3074 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3078 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3079 $cust_main->agentnum);
3080 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3081 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3083 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3084 my $error = $msg_template->send( 'cust_main' => $cust_main,
3085 'object' => $svc_acct,
3086 'substitutions' => {
3087 'session_id' => $reset_session_id,
3091 return { %$info, 'error' => $error }; #????
3096 return { %$info, 'error' => '' };
3099 sub check_reset_passwd {
3102 my $conf = new FS::Conf;
3103 my $verification = $conf->config('selfservice-password_reset_verification')
3104 or return { 'error' => 'Password resets disabled' };
3106 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3107 or return { 'error' => "Can't resume session" }; #better error message
3109 if ( $reset_session->{'svcnum'} ) {
3111 my $svcnum = $reset_session->{'svcnum'};
3113 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3114 or return { 'error' => "Service not found" };
3116 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3117 my $info = skin_info($p);
3121 'session_id' => $p->{'session_id'},
3122 'username' => $svc_acct->username,
3125 } elsif ( $reset_session->{'contactnum'} ) {
3127 my $contactnum = $reset_session->{'contactnum'};
3129 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3130 or return { 'error' => "Contact not found" };
3132 my @contact_email = $contact->contact_email;
3133 return { 'error' => 'No contact email' } unless @contact_email;
3135 $p->{'agentnum'} = $contact->cust_main->agentnum;
3136 my $info = skin_info($p);
3140 'session_id' => $p->{'session_id'},
3141 'email' => $contact_email[0]->email, #the first?
3146 return { 'error' => 'No svcnum or contactnum in session' }; #??
3152 sub process_reset_passwd {
3155 my $conf = new FS::Conf;
3156 my $verification = $conf->config('selfservice-password_reset_verification')
3157 or return { 'error' => 'Password resets disabled' };
3159 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3160 or return { 'error' => "Can't resume session" }; #better error message
3165 if ( $reset_session->{'svcnum'} ) {
3167 my $svcnum = $reset_session->{'svcnum'};
3169 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3170 or return { 'error' => "Service not found" };
3172 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3173 $info ||= skin_info($p);
3178 if ( $reset_session->{'contactnum'} ) {
3180 my $contactnum = $reset_session->{'contactnum'};
3182 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3183 or return { 'error' => "Contact not found" };
3185 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3186 $info ||= skin_info($p);
3190 return { %$info, 'error' => "New passwords don't match." }
3191 if $p->{'new_password'} ne $p->{'new_password2'};
3193 return { %$info, 'error' => 'Enter new password' }
3194 unless length($p->{'new_password'});
3198 $svc_acct->set_password($p->{'new_password'});
3199 my $error = $svc_acct->replace();
3201 return { %$info, 'error' => $error } if $error;
3203 #my($label, $value) = $svc_acct->cust_svc->label;
3204 #return { 'error' => $error,
3205 # #'label' => $label,
3206 # #'value' => $value,
3213 my $error = $contact->change_password($p->{'new_password'});
3215 return { %$info, 'error' => $error }; # if $error;
3219 #password changed ,so remove session, don't want it reused
3220 _cache->remove($p->{'session_id'});
3222 return { %$info, 'error' => '' };
3228 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3229 return { 'error' => $session } if $context eq 'error';
3232 if ( $session->{'pkgnum'} ) {
3234 #tickets for specific service with pkg-balances on
3235 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3236 'pkgnum' => $session->{'pkgnum'} })
3237 or return { 'error' => 'unknown package' };
3238 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3239 push @tickets, $cust_svc->tickets( $p->{status} );
3244 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3245 or return { 'error' => "unknown custnum $custnum" };
3247 @tickets = $cust_main->tickets( $p->{status} );
3250 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3251 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3252 my $conf = new FS::Conf;
3253 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3257 ($a->{'_selfservice_priority'} eq '') <=>
3258 ($b->{'_selfservice_priority'} eq '')
3261 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3267 +{ tickets => \@tickets };
3274 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3275 return { 'error' => $session } if $context eq 'error';
3277 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3278 FS::TicketSystem->init();
3280 my $conf = new FS::Conf;
3281 my $queue = $p->{'queue'}
3282 || $conf->config('ticket_system-selfservice_queueid')
3283 || $conf->config('ticket_system-default_queueid');
3285 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3286 my $err_or_ticket = FS::TicketSystem->create_ticket(
3287 '', #create RT session based on FS CurrentUser (fs_selfservice)
3289 'custnum' => $custnum,
3290 'svcnum' => $session->{'svcnum'},
3291 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3294 if ( ref($err_or_ticket) ) {
3295 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3297 return { 'error' => '',
3298 'ticket_id' => $err_or_ticket->id,
3301 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3303 return { 'error' => $err_or_ticket };
3311 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3312 return { 'error' => $session } if $context eq 'error';
3314 return { error => 'requested format not implemented' }
3315 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3317 my $conf = new FS::Conf;
3318 my $age_threshold = 0;
3319 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3320 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3322 my $search = { 'custnum' => $custnum };
3323 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3324 my $cust_main = qsearchs('cust_main', $search )
3325 or return { 'error' => "unknown custnum $custnum" };
3327 # does it make more sense to just run one sql query for this instead of all the
3328 # insanity below? would increase performance greately for large data sets?
3330 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3331 my @part_svc = $cust_pkg->part_svc;
3332 foreach my $part_svc ( @part_svc ) {
3333 if($part_svc->svcdb eq 'svc_phone'){
3334 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3335 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3336 push @svc_phone, $cust_pkg_svc->svc_x
3337 if $cust_pkg_svc->date_inserted >= $age_threshold;
3345 my($xls_r,$xls_c) = (0,0);
3348 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3349 if($p->{'format'} eq 'csv') {
3350 $csv = new Text::CSV_XS { 'always_quote' => 1,
3353 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3354 $content .= $csv->string;
3356 elsif($p->{'format'} eq 'xls') {
3357 my $XLS1 = new IO::Scalar \$content;
3358 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3359 or return { 'error' => "Error opening .xls file: $!" };
3360 $xls = $xls_workbook->add_worksheet('DIDs');
3361 foreach ( @fields ) {
3362 $xls->write(0,$xls_c++,$_);
3367 foreach my $svc_phone ( @svc_phone ) {
3368 my @cols = map { $svc_phone->$_ } @fields;
3369 if($p->{'format'} eq 'csv') {
3370 return { 'error' => 'Unable to create CSV' }
3371 unless $csv->combine(@cols);
3372 $content .= $csv->string;
3374 elsif($p->{'format'} eq 'xls') {
3377 $xls->write($xls_r,$xls_c++,$_);
3383 $xls_workbook->close() if $p->{'format'} eq 'xls';
3385 { content => $content, format => $p->{'format'}, };
3390 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3391 return { 'error' => $session } if $context eq 'error';
3393 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3394 # FS::TicketSystem->init();
3395 # return { 'error' => 'get_ticket configuration error' }
3396 # if $FS::TicketSystem::system ne 'RT_Internal';
3398 # check existence and ownership as part of this
3399 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3400 my $rt_session = FS::TicketSystem->session('');
3401 my $Ticket = FS::TicketSystem->get_ticket_object(
3403 ticket_id => $p->{'ticket_id'},
3406 return { 'error' => 'ticket not found' } if !$Ticket;
3408 if ( length( $p->{'subject'} || '' ) ) {
3410 if ( $p->{'subject'} ne $Ticket->Subject ) {
3411 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3412 return { 'error' => "unable to set subject: $msg" } if !$val;
3416 if(length($p->{'reply'})) {
3417 my @err_or_res = FS::TicketSystem->correspond_ticket(
3419 'ticket_id' => $p->{'ticket_id'},
3420 'content' => $p->{'reply'},
3423 return { 'error' => 'unable to reply to ticket' }
3424 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3427 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3428 my $err_or_ticket = FS::TicketSystem->get_ticket(
3430 'ticket_id' => $p->{'ticket_id'},
3433 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3434 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3436 return { 'error' => $err_or_ticket };
3439 my @custs = @{$err_or_ticket->{'custs'}};
3440 my @txns = @{$err_or_ticket->{'txns'}};
3443 # superseded by check in get_ticket_object
3444 #return { 'error' => 'invalid ticket requested' }
3445 #unless grep($_ eq $custnum, @custs);
3447 foreach my $txn ( @txns ) {
3448 push @filtered_txns, $txn
3449 if ($txn->{'type'} eq 'EmailRecord'
3450 || $txn->{'type'} eq 'Correspond'
3451 || $txn->{'type'} eq 'Create');
3454 warn "$me get_ticket: successful: \n"
3456 return { 'error' => '',
3457 'transactions' => \@filtered_txns,
3458 'ticket_fields' => $err_or_ticket->{'fields'},
3459 'ticket_id' => $p->{'ticket_id'},
3463 sub adjust_ticket_priority {
3465 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3466 return { 'error' => $session } if $context eq 'error';
3468 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3469 # FS::TicketSystem->init;
3470 my $ss_priority = FS::TicketSystem->selfservice_priority;
3472 return { 'error' => 'adjust_ticket_priority configuration error' }
3473 if $FS::TicketSystem::system ne 'RT_Internal'
3476 my $values = $p->{'values'}; #hashref, id => priority value
3479 foreach my $id (keys %$values) {
3480 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3481 my $Ticket = FS::TicketSystem->get_ticket_object('',
3483 'custnum' => $custnum,
3486 $ticket_error{$id} = 'ticket not found';
3490 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3491 # We're not going to implement it for RT_External.
3492 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3493 my $new_value = $values->{$id};
3494 next if $old_value eq $new_value;
3496 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3498 # AddCustomFieldValue works fine (replacing any existing value) if it's
3499 # a single-valued custom field, which it should be. If it's not, you're
3500 # doing something wrong.
3502 if ( length($new_value) ) {
3503 ($val, $msg) = $Ticket->AddCustomFieldValue(
3504 Field => $ss_priority,
3505 Value => $new_value,
3509 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3510 Field => $ss_priority,
3511 Value => $old_value,
3515 $ticket_error{$id} = $msg if !$val;
3516 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3518 return { 'error' => '',
3519 'ticket_error' => \%ticket_error,
3520 %{ customer_info($p) } # send updated customer info back
3526 sub _custoragent_session_custnum {
3529 my($context, $session, $custnum);
3530 if ( $p->{'session_id'} ) {
3532 $context = 'customer';
3533 $session = _cache->get($p->{'session_id'})
3534 or return ( 'error' => "Can't resume session" ); #better error message
3535 $custnum = $session->{'custnum'};
3537 } elsif ( $p->{'agent_session_id'} ) {
3540 my $agent_cache = new FS::ClientAPI_SessionCache( {
3541 'namespace' => 'FS::ClientAPI::Agent',
3543 $session = $agent_cache->get($p->{'agent_session_id'})
3544 or return ( 'error' => "Can't resume session" ); #better error message
3545 $custnum = $p->{'custnum'};
3549 return ( 'error' => "Can't resume session" ); #better error message
3552 ($context, $session, $custnum);