1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
51 $me = '[FS::ClientAPI::MyAccount]';
53 use vars qw( @cust_main_editable_fields @location_editable_fields );
54 @cust_main_editable_fields = qw(
55 first last company daytime night fax mobile
57 payby payinfo payname paystart_month paystart_year payissue payip
58 ss paytype paystate stateid stateid_state
60 @location_editable_fields = qw(
61 address1 address2 city county state zip country
65 BEGIN { #preload to reduce time customer_info takes
66 if ( $FS::TicketSystem::system ) {
67 warn "$me: initializing ticket system\n" if $DEBUG;
68 FS::TicketSystem->init();
73 $cache ||= new FS::ClientAPI_SessionCache( {
74 'namespace' => 'FS::ClientAPI::MyAccount',
81 my($context, $session, $custnum) = _custoragent_session_custnum($p);
82 #return { 'error' => $session } if $context eq 'error';
85 if ( $context eq 'customer' ) {
87 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
90 $sth->execute($custnum) or die $sth->errstr;
92 $agentnum = $sth->fetchrow_arrayref->[0]
93 or die "no agentnum for custnum $custnum";
95 #} elsif ( $context eq 'agent' ) {
96 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
99 $p->{'agentnum'} = $agentnum;
101 my $conf = new FS::Conf;
103 #false laziness w/Signup.pm
105 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
107 if ( $skin_info_cache_agent ) {
109 warn "$me loading cached skin info for agentnum $agentnum\n"
114 warn "$me populating skin info cache for agentnum $agentnum\n"
117 $skin_info_cache_agent = {
118 'agentnum' => $agentnum,
119 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
120 qw( company_name date_format ) ),
121 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
122 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
123 text_color link_color vlink_color hlink_color alink_color
124 font title_color title_align title_size menu_bgcolor menu_fontsize
127 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
128 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
129 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
131 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
132 qw( title_left_image title_right_image
133 menu_top_image menu_body_image menu_bottom_image
136 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
137 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
138 qw( head body_header body_footer company_address ) ),
139 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
142 services.php Services
143 services.php My Services
144 services_new.php Order a new service
147 personal.php Personal Information
148 password.php Change Password
151 payment_cc.php Credit Card Payment
152 payment_ach.php Electronic Check Payment
153 payment_paypal.php PayPal Payment
154 payment_webpay.php Webpay Payments
157 usage_data.php Data usage
158 usage_cdr.php Call usage
160 tickets.php Help Desk
161 tickets.php Open Tickets
162 tickets_resolved.php Resolved Tickets
163 ticket_create.php Create a new ticket
171 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
175 #{ %$skin_info_cache_agent };
176 $skin_info_cache_agent;
183 my $conf = new FS::Conf;
187 'phone_login' => $conf->exists('selfservice_server-phone_login'),
188 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
189 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
190 'banner_image_md5' =>
191 md5_hex($conf->config_binary('selfservice-login_banner_image')),
198 sub login_banner_image {
200 my $conf = new FS::Conf;
201 my $image = $conf->config_binary('selfservice-login_banner_image');
203 'md5' => md5_hex($image),
208 #false laziness w/FS::ClientAPI::passwd::passwd
212 my $conf = new FS::Conf;
216 if ( $p->{'domain'} eq 'svc_phone'
217 && $conf->exists('selfservice_server-phone_login') ) {
219 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
220 return { error => 'Number not found.' } unless $svc_phone;
223 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
224 #return { error => 'Only primary user may log in.' }
225 # if $conf->exists('selfservice_server-primary_only')
226 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
228 return { error => 'Incorrect PIN.' }
229 unless $svc_phone->check_pin($p->{'password'});
233 } elsif ( $p->{email}
234 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
237 return { error => 'Incorrect contact password.' }
238 unless $contact->authenticate_password($p->{'password'});
240 $session->{'custnum'} = $contact->custnum;
244 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
246 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
247 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
249 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
250 'domsvc' => $svc_domain->svcnum, }
252 return { error => 'User not found.' } unless $svc_acct;
254 if($conf->exists('selfservice_server-login_svcpart')) {
255 my @svcpart = $conf->config('selfservice_server-login_svcpart');
256 my $svcpart = $svc_acct->cust_svc->svcpart;
257 return { error => 'Invalid user.' }
258 unless grep($_ eq $svcpart, @svcpart);
261 return { error => 'Incorrect password.' }
262 unless $svc_acct->check_password($p->{'password'});
270 $session->{'svcnum'} = $svc_x->svcnum;
272 my $cust_svc = $svc_x->cust_svc;
273 my $cust_pkg = $cust_svc->cust_pkg;
275 my $cust_main = $cust_pkg->cust_main;
276 $session->{'custnum'} = $cust_main->custnum;
277 if ( $conf->exists('pkg-balances') ) {
278 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
279 $cust_main->ncancelled_pkgs;
280 $session->{'pkgnum'} = $cust_pkg->pkgnum
281 if scalar(@cust_pkg) > 1;
285 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
286 #return { error => 'Only primary user may log in.' }
287 # if $conf->exists('selfservice_server-primary_only')
288 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
289 my $part_pkg = $cust_pkg->part_pkg;
290 return { error => 'Only primary user may log in.' }
291 if $conf->exists('selfservice_server-primary_only')
292 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
298 $session_id = sha512_hex(time(). {}. rand(). $$)
299 } until ( ! defined _cache->get($session_id) ); #just in case
301 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
302 _cache->set( $session_id, $session, $timeout );
304 return { 'error' => '',
305 'session_id' => $session_id,
311 if ( $p->{'session_id'} ) {
312 _cache->remove($p->{'session_id'});
313 return { %{ skin_info($p) }, 'error' => '' };
315 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
322 my($context, $session, $custnum) = _custoragent_session_custnum($p);
323 return { 'error' => $session } if $context eq 'error';
325 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
326 or return { 'error' => "Service not found" };
328 $session->{'svcnum'} = $svc_acct->svcnum;
330 my $conf = new FS::Conf;
331 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
332 _cache->set( $p->{'session_id'}, $session, $timeout );
334 return { 'error' => '' };
338 sub payment_gateway {
340 # takes a cust_main and a cust_payby entry, returns the payment_gateway
341 my $conf = new FS::Conf;
342 my $cust_main = shift;
343 my $cust_payby = shift;
344 my $gatewaynum = $conf->config('selfservice-payment_gateway');
346 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
347 die "configured gatewaynum $gatewaynum not found!" if !$pg;
351 return '' if ! FS::payby->realtime($cust_payby);
352 my $pg = $cust_main->agent->payment_gateway(
353 'method' => FS::payby->payby2bop($cust_payby),
363 my $conf = new FS::Conf;
365 my $info = skin_info($p);
367 use vars qw( $cust_paybys ); #cache for performance
368 unless ( $cust_paybys ) {
370 my %cust_paybys = map { $_ => 1 }
371 map { FS::payby->payby2payment($_) }
372 $conf->config('signup_server-payby');
374 $cust_paybys = [ keys %cust_paybys ];
377 $info->{'cust_paybys'} = $cust_paybys;
379 my($context, $session, $custnum) = _custoragent_session_custnum($p);
380 return { 'error' => $session } if $context eq 'error';
382 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
383 or return { 'error' => "unknown custnum $custnum" };
385 $info->{'hide_payment_fields'} = [
387 my $pg = payment_gateway($cust_main, $_);
388 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
389 } @{ $info->{cust_paybys} }
392 $info->{'self_suspend_reason'} =
393 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
395 $info->{'edit_ticket_subject'} =
396 $conf->exists('ticket_system-selfservice_edit_subject') &&
397 $cust_main->edit_subject;
399 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
402 'custnum' => $custnum,
403 'access_pkgnum' => $session->{'pkgnum'},
404 'access_svcnum' => $session->{'svcnum'},
411 my($context, $session, $custnum) = _custoragent_session_custnum($p);
412 return { 'error' => $session } if $context eq 'error';
416 my $conf = new FS::Conf;
417 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
419 # if ( $FS::TicketSystem::system ) {
420 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
421 # FS::TicketSystem->init();
424 if ( $custnum ) { #customer record
426 %return = ( %return, %{ customer_info_short($p) } );
428 #redundant with customer_info_short, but we need it for several things below
429 my $search = { 'custnum' => $custnum };
430 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
431 my $cust_main = qsearchs('cust_main', $search )
432 or return { 'error' => "unknown custnum $custnum" };
434 my $list_tickets = list_tickets($p);
435 $return{'tickets'} = $list_tickets->{'tickets'};
437 if ( $session->{'pkgnum'} ) {
438 #XXX open invoices in the pkg-balances case
442 invnum => $_->invnum,
443 date => time2str("%b %o, %Y", $_->_date),
446 } $cust_main->open_cust_bill;
447 $return{open_invoices} = \@open;
449 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
450 my $sth = dbh->prepare($sql) or die dbh->errstr;
451 $sth->execute($custnum) or die $sth->errstr;
452 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
453 $return{'last_invoice_date_pretty'} =
454 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
457 #customer_info_short always has nobalance on..
458 $return{small_custview} =
459 small_custview( $cust_main,
460 $return{countrydefault},
461 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
464 $return{has_ship_address} = $cust_main->has_ship_address;
465 $return{status} = $cust_main->status;
466 $return{statuscolor} = $cust_main->statuscolor;
468 # compatibility: some places in selfservice use this to determine
469 # if there's a ship address
470 if ( $return{has_ship_address} ) {
471 $return{ship_last} = $cust_main->last;
472 $return{ship_first} = $cust_main->first;
475 if (scalar($conf->config('support_packages'))) {
476 my @support_services = ();
477 foreach ($cust_main->support_services) {
478 my $seconds = $_->svc_x->seconds || 0;
479 my $time_remaining = (($seconds < 0) ? '-' : '' ).
480 int(abs($seconds)/3600)."h".
481 sprintf("%02d",(abs($seconds)%3600)/60)."m";
482 my $cust_pkg = $_->cust_pkg;
485 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
486 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
487 push @support_services, { svcnum => $_->svcnum,
488 time => $time_remaining,
493 $return{support_services} = \@support_services;
496 if ( $conf->config('prepayment_discounts-credit_type') ) {
498 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
501 } elsif ( $session->{'svcnum'} ) { #no customer record
503 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
504 or die "unknown svcnum";
505 $return{name} = $svc_acct->email;
509 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
513 return { 'error' => '',
514 'custnum' => $custnum,
520 sub customer_info_short {
523 my($context, $session, $custnum) = _custoragent_session_custnum($p);
524 return { 'error' => $session } if $context eq 'error';
528 my $conf = new FS::Conf;
530 if ( $custnum ) { #customer record
532 my $search = { 'custnum' => $custnum };
533 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
534 my $cust_main = qsearchs('cust_main', $search )
535 or return { 'error' => "unknown custnum $custnum" };
537 $return{display_custnum} = $cust_main->display_custnum;
539 if ( $session->{'pkgnum'} ) {
540 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
541 #next_bill_date from cust_pkg?
543 $return{balance} = $cust_main->balance;
544 $return{next_bill_date} = $cust_main->next_bill_date;
545 $return{next_bill_date_pretty} =
546 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
550 $return{countrydefault} = scalar($conf->config('countrydefault'));
552 $return{small_custview} =
553 small_custview( $cust_main,
554 $return{countrydefault},
558 $return{first} = $cust_main->first;
559 $return{'last'} = $cust_main->get('last');
560 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
562 $return{payby} = $cust_main->payby;
564 #none of these are terribly expensive if we want 'em...
565 for (@cust_main_editable_fields) {
566 $return{$_} = $cust_main->get($_);
568 #maybe a little more expensive, but it should be cached by now
569 for (@location_editable_fields) {
570 $return{$_} = $cust_main->bill_location->get($_)
571 if $cust_main->bill_locationnum;
572 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
573 if $cust_main->ship_locationnum;
576 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
577 $return{payinfo} = $cust_main->paymask;
578 @return{'month', 'year'} = $cust_main->paydate_monthyear;
581 my @invoicing_list = $cust_main->invoicing_list;
582 $return{'invoicing_list'} =
583 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
584 $return{'postal_invoicing'} =
585 0 < ( grep { $_ eq 'POST' } @invoicing_list );
587 if ( $session->{'svcnum'} ) {
588 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
589 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
590 $return{'svcnum'} = $session->{'svcnum'};
593 } elsif ( $session->{'svcnum'} ) { #no customer record
595 #uuh, not supproted yet... die?
596 return { 'error' => 'customer_info_short not yet supported as agent' };
600 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
604 return { 'error' => '',
605 'custnum' => $custnum,
610 sub billing_history {
613 my($context, $session, $custnum) = _custoragent_session_custnum($p);
614 return { 'error' => $session } if $context eq 'error';
616 return { 'error' => 'No customer' } unless $custnum;
618 my $search = { 'custnum' => $custnum };
619 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
620 my $cust_main = qsearchs('cust_main', $search )
621 or return { 'error' => "unknown custnum $custnum" };
625 if ( $session->{'pkgnum'} ) {
626 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
627 #next_bill_date from cust_pkg?
628 return { 'error' => 'No history for package' };
631 $return{balance} = $cust_main->balance;
632 $return{next_bill_date} = $cust_main->next_bill_date;
633 $return{next_bill_date_pretty} =
634 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
639 my $conf = new FS::Conf;
641 if ( $conf->exists('selfservice-billing_history-line_items') ) {
643 foreach my $cust_bill ( $cust_main->cust_bill ) {
646 'type' => 'Line item',
647 'description' => $_->desc( $cust_main->locale ).
648 ( $_->sdate && $_->edate
649 ? ' '. time2str('%d-%b-%Y', $_->sdate).
650 ' To '. time2str('%d-%b-%Y', $_->edate)
653 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
654 'date' => $cust_bill->_date,
655 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
657 foreach $cust_bill->cust_bill_pkg;
665 'description' => 'Invoice #'. $_->display_invnum,
666 'amount' => sprintf('%.2f', $_->charged ),
668 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
670 foreach $cust_main->cust_bill;
676 'description' => 'Payment', #XXX type
677 'amount' => sprintf('%.2f', 0 - $_->paid ),
679 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
681 foreach $cust_main->cust_pay;
685 'description' => 'Credit', #more info?
686 'amount' => sprintf('%.2f', 0 -$_->amount ),
688 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
690 foreach $cust_main->cust_credit;
694 'description' => 'Refund', #more info? type, like payment?
695 'amount' => $_->refund,
697 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
699 foreach $cust_main->cust_refund;
701 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
703 $return{'history'} = \@history;
711 my $session = _cache->get($p->{'session_id'})
712 or return { 'error' => "Can't resume session" }; #better error message
714 my $custnum = $session->{'custnum'}
715 or return { 'error' => "no customer record" };
717 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
718 or return { 'error' => "unknown custnum $custnum" };
720 my $new = new FS::cust_main { $cust_main->hash };
722 $new->set( $_ => $p->{$_} )
723 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
725 if ( exists($p->{address1}) ) {
726 my $bill_location = FS::cust_location->new({
727 map { $_ => $p->{$_} } @location_editable_fields
729 # if this is unchanged from before, cust_main::replace will ignore it
730 $new->set('bill_location' => $bill_location);
733 if ( exists($p->{ship_address1}) ) {
734 my $ship_location = FS::cust_location->new({
735 map { $_ => $p->{"ship_$_"} } @location_editable_fields
737 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
738 # Selfservice unfortunately tries to indicate "same as billing
739 # address" by sending all fields empty. Did this ever work?
740 $ship_location = $cust_main->bill_location;
742 $new->set('ship_location' => $ship_location);
744 # but if it hasn't been passed in at all, leave ship_location alone--
745 # DON'T change it to match bill_location.
748 if (exists($p->{'payby'})) {
749 $p->{'payby'} =~ /^([A-Z]{4})$/
750 or return { 'error' => "illegal_payby " . $p->{'payby'} };
754 my $conf = new FS::Conf;
756 if ( $payby =~ /^(CARD|DCRD)$/ ) {
758 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
760 if ( $new->payinfo eq $cust_main->paymask ) {
761 $new->payinfo($cust_main->payinfo);
763 $new->payinfo($p->{'payinfo'});
766 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
768 if ( $conf->exists('selfservice-onfile_require_cvv') ){
769 return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
772 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
775 $p->{'payinfo1'} =~ /^([\dx]+)$/
776 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
778 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
779 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
781 $payinfo = $payinfo1. '@'. $payinfo2;
783 $new->payinfo( ($payinfo eq $cust_main->paymask)
784 ? $cust_main->payinfo
788 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
790 } elsif ( $payby =~ /^(BILL)$/ ) {
792 } elsif ( $payby ) { #notyet ready
793 return { 'error' => "unknown payby $payby" };
797 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
798 #false laziness with httemplate/edit/process/cust_main.cgi
799 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
800 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
802 @invoicing_list = $cust_main->invoicing_list;
805 my $error = $new->replace($cust_main, \@invoicing_list);
806 return { 'error' => $error } if $error;
809 return { 'error' => '' };
814 my $session = _cache->get($p->{'session_id'})
815 or return { 'error' => "Can't resume session" }; #better error message
821 my $conf = new FS::Conf;
822 use vars qw($payment_info); #cache for performance
823 unless ( $payment_info ) {
825 my %states = map { $_->state => 1 }
826 qsearch('cust_main_county', {
827 'country' => $conf->config('countrydefault') || 'US'
830 my %cust_paybys = map { $_ => 1 }
831 map { FS::payby->payby2payment($_) }
832 $conf->config('signup_server-payby');
834 my @cust_paybys = keys %cust_paybys;
838 #list all counties/states/countries
839 'cust_main_county' =>
840 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
842 #shortcut for one-country folks
844 [ sort { $a cmp $b } keys %states ],
846 'card_types' => card_types(),
848 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
849 'require_cvv' => $conf->exists('selfservice-require_cvv'),
850 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
852 'paytypes' => [ @FS::cust_main::paytypes ],
854 'paybys' => [ $conf->config('signup_server-payby') ],
855 'cust_paybys' => \@cust_paybys,
857 'stateid_label' => FS::Msgcat::_gettext('stateid'),
858 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
860 'show_ss' => $conf->exists('show_ss'),
861 'show_stateid' => $conf->exists('show_stateid'),
862 'show_paystate' => $conf->exists('show_bankstate'),
864 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
866 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
875 my %return = %$payment_info;
877 my $custnum = $session->{'custnum'};
879 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
880 or return { 'error' => "unknown custnum $custnum" };
882 $return{'hide_payment_fields'} = [
884 my $pg = payment_gateway($cust_main, $_);
885 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
886 } @{ $return{cust_paybys} }
889 $return{balance} = $cust_main->balance; #XXX pkg-balances?
891 $return{payname} = $cust_main->payname
892 || ( $cust_main->first. ' '. $cust_main->get('last') );
894 $return{$_} = $cust_main->bill_location->get($_)
895 for qw(address1 address2 city state zip);
897 $return{payby} = $cust_main->payby;
898 $return{stateid_state} = $cust_main->stateid_state;
900 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
901 $return{card_type} = cardtype($cust_main->payinfo);
902 $return{payinfo} = $cust_main->paymask;
904 @return{'month', 'year'} = $cust_main->paydate_monthyear;
908 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
909 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
910 $return{payinfo1} = $payinfo1;
911 $return{payinfo2} = $payinfo2;
912 $return{paytype} = $cust_main->paytype;
913 $return{paystate} = $cust_main->paystate;
914 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
917 if ( $conf->config('prepayment_discounts-credit_type') ) {
919 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
922 #doubleclick protection
924 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
925 $return{paybatch} = $return{payunique}; #back compat
927 return { 'error' => '',
933 #some false laziness with httemplate/process/payment.cgi - look there for
934 #ACH and CVV support stuff
936 sub validate_payment {
939 my $session = _cache->get($p->{'session_id'})
940 or return { 'error' => "Can't resume session" }; #better error message
942 my $custnum = $session->{'custnum'};
944 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
945 or return { 'error' => "unknown custnum $custnum" };
947 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
948 or return { 'error' => gettext('illegal_amount') };
950 return { error => 'Amount must be greater than 0' } unless $amount > 0;
952 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
953 #changing the hidden form values
954 my $conf = new FS::Conf;
955 my $fee_display = $conf->config('selfservice_process-display') || 'add';
956 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
957 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
958 if ( $fee_display eq 'add'
960 and ! $fee_skip_first || scalar($cust_main->cust_pay)
963 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
964 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
967 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
968 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
969 my $discount_term = $1;
971 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
972 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
975 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
976 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
979 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
980 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
983 $payunique = $paybatch if ! length($payunique) && length($paybatch);
985 $p->{'payby'} ||= 'CARD';
986 $p->{'payby'} =~ /^([A-Z]{4})$/
987 or return { 'error' => "illegal_payby " . $p->{'payby'} };
990 #false laziness w/process/payment.cgi
993 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
995 $p->{'payinfo1'} =~ /^([\dx]+)$/
996 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
998 $p->{'payinfo2'} =~ /^([\dx]+)$/
999 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1001 $payinfo = $payinfo1. '@'. $payinfo2;
1003 $payinfo = $cust_main->payinfo
1004 if $cust_main->paymask eq $payinfo;
1006 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1008 $payinfo = $p->{'payinfo'};
1012 #more intelligent matching will be needed here if you change
1013 #card_masking_method and don't remove existing paymasks
1014 if ( $cust_main->paymask eq $payinfo ) {
1015 $payinfo = $cust_main->payinfo;
1019 $payinfo =~ s/\D//g;
1020 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1021 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1025 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1026 return { 'error' => gettext('unknown_card_type') }
1027 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1029 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1030 if ( cardtype($payinfo) eq 'American Express card' ) {
1031 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1032 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1035 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1036 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1039 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1040 return { 'error' => 'CVV2 is required' };
1041 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1042 return { 'error' => 'CVV2 is required' };
1046 die "unknown payby $payby";
1049 my %payby2fields = (
1050 'CARD' => [ qw( paystart_month paystart_year payissue payip
1051 address1 address2 city state zip country ) ],
1052 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1056 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1059 'cust_main' => $cust_main, #XXX or just custnum??
1060 'amount' => sprintf('%.2f', $amount),
1062 'payinfo' => $payinfo,
1063 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1064 'card_type' => $card_type,
1065 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1066 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1067 'month' => $p->{'month'},
1068 'year' => $p->{'year'},
1069 'payname' => $payname,
1070 'payunique' => $payunique,
1071 'paybatch' => $paybatch,
1072 'paycvv' => $paycvv,
1073 'payname' => $payname,
1074 'discount_term' => $discount_term,
1075 'pkgnum' => $session->{'pkgnum'},
1076 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1086 my $validate = validate_payment($p);
1087 return $validate if $validate->{'error'};
1089 my $conf = new FS::Conf;
1090 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1091 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1093 +{ map { $_=>$validate->{$_} }
1094 qw( card_type paymask payname paydate_pretty month year amount
1095 address1 address2 city state zip country
1101 sub process_stored_payment {
1104 my $session_id = $p->{'session_id'};
1106 my $payment_info = _cache->get( "payment_$session_id" )
1107 or return { 'error' => "Can't resume session" }; #better error message
1109 do_process_payment($payment_info);
1113 sub process_payment {
1116 my $payment_info = validate_payment($p);
1117 return $payment_info if $payment_info->{'error'};
1119 do_process_payment($payment_info);
1123 sub do_process_payment {
1124 my $validate = shift;
1126 my $cust_main = $validate->{'cust_main'};
1128 my $amount = delete $validate->{'amount'};
1131 my $payby = delete $validate->{'payby'};
1133 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1136 'paynum_ref' => \$paynum,
1139 return { 'error' => $error } if $error;
1141 #no error, so order the fee package if applicable...
1142 my $conf = new FS::Conf;
1143 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1144 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1146 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1148 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1150 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1151 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1154 #and generate an invoice for it now too
1155 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1156 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1161 $cust_main->apply_payments;
1163 if ( $validate->{'save'} ) {
1164 my $new = new FS::cust_main { $cust_main->hash };
1165 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1166 $new->set( $_ => $validate->{$_} )
1167 foreach qw( payname paystart_month paystart_year payissue payip );
1168 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1170 my $bill_location = FS::cust_location->new({
1171 map { $_ => $validate->{$_} }
1172 qw(address1 address2 city state country zip)
1174 $new->set('bill_location' => $bill_location);
1175 # but don't allow the service address to change this way.
1177 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1178 $new->set( $_ => $validate->{$_} )
1179 foreach qw( payname payip paytype paystate
1180 stateid stateid_state );
1181 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1183 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1184 $new->set( 'paydate' => $validate->{'paydate'} );
1185 my $error = $new->replace($cust_main);
1187 #no, this causes customers to process their payments again
1188 #return { 'error' => $error };
1189 #XXX just warn verosely for now so i can figure out how these happen in
1190 # the first place, eventually should redirect them to the "change
1191 #address" page but indicate the payment did process??
1192 delete($validate->{'payinfo'}); #don't want to log this!
1193 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1194 "NEW: ". Dumper($new)."\n".
1195 "OLD: ". Dumper($cust_main)."\n".
1196 "PACKET: ". Dumper($validate)."\n";
1204 my $receipt_html = '';
1206 # currently supported for realtime CC only; send receipt data to SS
1207 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1210 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1213 <TD ALIGN="right">Payment#</TD>
1214 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1218 <TD ALIGN="right">Date</TD>
1220 <TD BGCOLOR="#FFFFFF"><B>! .
1221 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1227 <TD ALIGN="right">Amount</TD>
1228 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1233 <TD ALIGN="right">Payment method</TD>
1234 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1247 'amount' => sprintf('%.2f', $cust_pay->paid),
1248 'date' => $cust_pay->_date,
1249 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1250 'time_pretty' => time2str('%T', $cust_pay->_date),
1251 'auth_num' => $cust_pay->auth,
1252 'order_num' => $cust_pay->order_number,
1253 'receipt_html' => $receipt_html,
1260 'receipt_html' => '',
1267 sub realtime_collect {
1270 my $session = _cache->get($p->{'session_id'})
1271 or return { 'error' => "Can't resume session" }; #better error message
1273 my $custnum = $session->{'custnum'};
1275 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1276 or return { 'error' => "unknown custnum $custnum" };
1279 if ( $p->{'amount'} ) {
1280 $amount = $p->{'amount'};
1282 elsif ( $session->{'pkgnum'} ) {
1283 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1286 $amount = $cust_main->balance;
1289 my $error = $cust_main->realtime_collect(
1290 'method' => $p->{'method'},
1291 'amount' => $amount,
1292 'pkgnum' => $session->{'pkgnum'},
1293 'session_id' => $p->{'session_id'},
1297 return { 'error' => $error } unless ref( $error );
1299 return { 'error' => '', amount => $amount, %$error };
1302 sub start_thirdparty {
1304 my $session = _cache->get($p->{'session_id'})
1305 or return { 'error' => "Can't resume session" }; #better error message
1306 my $custnum = $session->{'custnum'};
1307 my $cust_main = FS::cust_main->by_key($custnum);
1309 my $amount = $p->{'amount'}
1310 or return { error => 'no amount' };
1312 my $result = $cust_main->create_payment(
1313 'method' => $p->{'method'},
1314 'amount' => $p->{'amount'},
1315 'pkgnum' => $session->{'pkgnum'},
1316 'session_id' => $p->{'session_id'},
1319 if ( ref($result) ) { # hashref or error
1322 return { error => $result };
1326 sub finish_thirdparty {
1328 my $session_id = delete $p->{'session_id'};
1329 my $session = _cache->get($session_id)
1330 or return { 'error' => "Can't resume session" };
1331 my $custnum = $session->{'custnum'};
1332 my $cust_main = FS::cust_main->by_key($custnum);
1334 if ( $p->{_cancel} ) {
1335 # customer backed out of making a payment
1336 return $cust_main->cancel_payment( $session_id );
1338 my $result = $cust_main->execute_payment( $session_id, %$p );
1339 if ( ref($result) ) {
1342 return { error => $result };
1346 sub process_payment_order_pkg {
1349 my $hr = process_payment($p);
1350 return $hr if $hr->{'error'};
1355 sub process_payment_order_renew {
1358 my $hr = process_payment($p);
1359 return $hr if $hr->{'error'};
1364 sub process_prepay {
1368 my $session = _cache->get($p->{'session_id'})
1369 or return { 'error' => "Can't resume session" }; #better error message
1373 my $custnum = $session->{'custnum'};
1375 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1376 or return { 'error' => "unknown custnum $custnum" };
1378 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1379 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1387 return { 'error' => $error } if $error;
1389 return { 'error' => '',
1390 'amount' => $amount,
1391 'seconds' => $seconds,
1392 'duration' => duration_exact($seconds),
1393 'upbytes' => $upbytes,
1394 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1395 'downbytes' => $downbytes,
1396 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1397 'totalbytes'=> $totalbytes,
1398 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1405 my $session = _cache->get($p->{'session_id'})
1406 or return { 'error' => "Can't resume session" }; #better error message
1408 my $custnum = $session->{'custnum'};
1410 my $invnum = $p->{'invnum'};
1412 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1413 'custnum' => $custnum } )
1414 or return { 'error' => "Can't find invnum" };
1418 return { 'error' => '',
1419 'invnum' => $invnum,
1420 'invoice_text' => join('', $cust_bill->print_text ),
1421 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1428 my $session = _cache->get($p->{'session_id'})
1429 or return { 'error' => "Can't resume session" }; #better error message
1431 my $custnum = $session->{'custnum'};
1433 my $invnum = $p->{'invnum'};
1435 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1436 'custnum' => $custnum } )
1437 or return { 'error' => "Can't find invnum" };
1441 return { 'error' => '',
1442 'invnum' => $invnum,
1443 'invoice_pdf' => $cust_bill->print_pdf({
1444 'unsquelch_cdr' => 1,
1445 'locale' => $p->{'locale'},
1451 sub legacy_invoice {
1453 my $session = _cache->get($p->{'session_id'})
1454 or return { 'error' => "Can't resume session" }; #better error message
1456 my $custnum = $session->{'custnum'};
1458 my $legacyinvnum = $p->{'legacyinvnum'};
1461 'legacyinvnum' => $legacyinvnum,
1462 'custnum' => $custnum,
1465 my $legacy_cust_bill =
1466 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1467 || qsearchs('legacy_cust_bill', \%hash )
1468 or return { 'error' => "Can't find legacyinvnum" };
1472 return { 'error' => '',
1473 'legacyinvnum' => $legacyinvnum,
1474 'legacyid' => $legacy_cust_bill->legacyid,
1475 'invoice_html' => $legacy_cust_bill->content_html,
1480 sub legacy_invoice_pdf {
1482 my $session = _cache->get($p->{'session_id'})
1483 or return { 'error' => "Can't resume session" }; #better error message
1485 my $custnum = $session->{'custnum'};
1487 my $legacyinvnum = $p->{'legacyinvnum'};
1489 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1490 'legacyinvnum' => $legacyinvnum,
1491 'custnum' => $custnum,
1492 }) or return { 'error' => "Can't find legacyinvnum" };
1496 return { 'error' => '',
1497 'legacyinvnum' => $legacyinvnum,
1498 'legacyid' => $legacy_cust_bill->legacyid,
1499 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1507 #sessioning for this? how do we get the session id to the backend invoice
1508 # template so it can add it to the link, blah
1511 if ( $p->{'invnum'} ) {
1512 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1513 or return { 'error' => 'unknown invnum' };
1514 $agentnum = $cust_bill->cust_main->agentnum;
1517 my $templatename = $p->{'template'} || $p->{'templatename'};
1519 #false laziness-ish w/view/cust_bill-logo.cgi
1521 my $conf = new FS::Conf;
1522 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1523 $templatename = "_$1";
1528 my $filename = "logo$templatename.png";
1530 return { 'error' => '',
1531 'logo' => $conf->config_binary($filename, $agentnum),
1532 'content_type' => 'image/png', #should allow gif, jpg too
1539 my $session = _cache->get($p->{'session_id'})
1540 or return { 'error' => "Can't resume session" }; #better error message
1542 my $custnum = $session->{'custnum'};
1544 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1545 or return { 'error' => "unknown custnum $custnum" };
1547 my $conf = new FS::Conf;
1549 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1551 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1555 return { 'error' => '',
1556 'balance' => $cust_main->balance,
1559 my $owed = $_->owed;
1561 +{ 'invnum' => $_->invnum,
1562 '_date' => $_->_date,
1563 'date' => time2str("%b %o, %Y", $_->_date),
1564 'date_short' => time2str("%m-%d-%Y", $_->_date),
1565 'previous' => sprintf('%.2f', ($_->previous)[0]),
1566 'charged' => sprintf('%.2f', $_->charged),
1567 'owed' => sprintf('%.2f', $owed),
1568 'balance' => sprintf('%.2f', $balance),
1573 'legacy_invoices' => [
1575 +{ 'legacyinvnum' => $_->legacyinvnum,
1576 'legacyid' => $_->legacyid,
1577 '_date' => $_->_date,
1578 'date' => time2str("%b %o, %Y", $_->_date),
1579 'date_short' => time2str("%m-%d-%Y", $_->_date),
1580 'charged' => sprintf('%.2f', $_->charged),
1581 'has_content' => ( length($_->content_pdf)
1582 || length($_->content_html) ),
1592 my $session = _cache->get($p->{'session_id'})
1593 or return { 'error' => "Can't resume session" }; #better error message
1595 my $custnum = $session->{'custnum'};
1597 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1598 or return { 'error' => "unknown custnum $custnum" };
1600 my @errors = $cust_main->cancel( 'quiet'=>1 );
1602 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1604 return { 'error' => $error };
1611 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1612 return { 'error' => $session } if $context eq 'error';
1614 my $search = { 'custnum' => $custnum };
1615 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1616 my $cust_main = qsearchs('cust_main', $search )
1617 or return { 'error' => "unknown custnum $custnum" };
1619 my $conf = new FS::Conf;
1620 my $immutable = $conf->exists('selfservice_immutable-package');
1622 # the duplication below is necessary:
1623 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1624 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1625 # non-backwards-compatible change breaking the software of anyone using the API
1626 # instead of the stock selfservice
1627 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1628 if( $conf->exists('selfservice_server-view-wholesale') ) {
1629 return { 'svcnum' => $session->{'svcnum'},
1630 'custnum' => $custnum,
1631 'cust_pkg' => [ map {
1633 immutable => $immutable,
1634 part_pkg => [ map $_->hashref, $_->part_pkg ],
1636 [ map $_->hashref, $_->available_part_svc ],
1638 [ map { my $ref = { $_->hash,
1639 label => [ $_->label ],
1641 $ref->{_password} = $_->svc_x->_password
1642 if $context eq 'agent'
1643 && $conf->exists('agent-showpasswords')
1644 && $_->part_svc->svcdb eq 'svc_acct';
1649 } $cust_main->cust_pkg
1652 small_custview( $cust_main, $conf->config('countrydefault') ),
1653 'wholesale_view' => 1,
1654 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1655 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1656 'lnp' => $conf->exists('svc_phone-lnp'),
1660 { 'svcnum' => $session->{'svcnum'},
1661 'custnum' => $custnum,
1662 'cust_pkg' => [ map {
1663 my $primary_cust_svc = $_->primary_cust_svc;
1666 immutable => $immutable,
1667 pkg_label => $_->pkg_locale,
1668 status => $_->status,
1669 statuscolor => $_->statuscolor,
1671 [ map { $_->hashref }
1672 grep { $_->selfservice_access ne 'hidden' }
1673 $_->available_part_svc
1676 [ map { my $ref = { $_->hash,
1677 label => [ $_->label ],
1679 $ref->{_password} = $_->svc_x->_password
1680 if $context eq 'agent'
1681 && $conf->exists('agent-showpasswords')
1682 && $_->part_svc->svcdb eq 'svc_acct';
1683 $ref->{svchash} = { $_->svc_x->hash } if
1684 $_->part_svc->svcdb eq 'svc_phone';
1685 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1686 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1689 grep { $_->part_svc->selfservice_access ne 'hidden' }
1694 ? { $primary_cust_svc->hash,
1695 label => [ $primary_cust_svc->label ],
1696 finger => $primary_cust_svc->svc_x->finger, #uuh
1697 $primary_cust_svc->part_svc->hash,
1701 } $cust_main->ncancelled_pkgs
1704 small_custview( $cust_main, $conf->config('countrydefault') ),
1705 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1713 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1714 return { 'error' => $session } if $context eq 'error';
1716 my $search = { 'custnum' => $custnum };
1717 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1718 my $cust_main = qsearchs('cust_main', $search )
1719 or return { 'error' => "unknown custnum $custnum" };
1721 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1722 if ( ! $pkgnum && $p->{'svcnum'} ) {
1723 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1724 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1728 my @cust_pkg_usage = ();
1729 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1730 foreach my $cust_pkg ( $p->{'ncancelled'}
1731 ? $cust_main->ncancelled_pkgs
1732 : $cust_main->unsuspended_pkgs ) {
1733 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1734 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1735 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1738 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1740 foreach (@cust_pkg_usage) {
1741 my $part = $_->part_pkg_usage;
1742 my $tag = $part->description . ($part->shared ? 1 : 0);
1743 my $row = $usage_pools{$tag}
1744 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1745 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1746 $row->[2] += $part->minutes; # minutes total
1749 if ( $p->{'svcdb'} ) {
1750 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1752 : ref($p->{'svcdb'}) eq 'ARRAY'
1753 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1754 : { $p->{'svcdb'} => 1 };
1755 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1758 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1761 my $conf = new FS::Conf;
1764 'svcnum' => $session->{'svcnum'},
1765 'custnum' => $custnum,
1766 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1767 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1770 my $svc_x = $_->svc_x;
1771 my($label, $value) = $_->label;
1772 my $part_svc = $_->part_svc;
1773 my $svcdb = $part_svc->svcdb;
1774 my $cust_pkg = $_->cust_pkg;
1775 my $part_pkg = $cust_pkg->part_pkg;
1778 'svcnum' => $_->svcnum,
1779 'display_svcnum' => $_->display_svcnum,
1783 'pkg_label' => $cust_pkg->pkg_locale,
1784 'pkg_status' => $cust_pkg->status,
1785 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1788 if ( $svcdb eq 'svc_acct' ) {
1791 'username' => $svc_x->username,
1792 'email' => $svc_x->email,
1793 'finger' => $svc_x->finger,
1794 'seconds' => $svc_x->seconds,
1795 'upbytes' => display_bytecount($svc_x->upbytes),
1796 'downbytes' => display_bytecount($svc_x->downbytes),
1797 'totalbytes' => display_bytecount($svc_x->totalbytes),
1799 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1800 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1801 'recharge_upbytes' =>
1802 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1803 'recharge_downbytes' =>
1804 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1805 'recharge_totalbytes' =>
1806 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1810 } elsif ( $svcdb eq 'svc_dsl' ) {
1811 $hash{'phonenum'} = $svc_x->phonenum;
1812 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1813 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1814 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1817 $hash{'name'} = $cust_main->name;
1819 } elsif ( $svcdb eq 'svc_phone' ) {
1820 # could potentially show lots of things...
1821 $hash{'outbound'} = 1;
1822 $hash{'inbound'} = 0;
1823 if ( $part_pkg->plan eq 'voip_inbound' ) {
1824 $hash{'outbound'} = 0;
1825 $hash{'inbound'} = 1;
1826 } elsif ( $part_pkg->option('selfservice_inbound_format')
1827 or $conf->config('selfservice-default_inbound_cdr_format')
1829 $hash{'inbound'} = 1;
1831 foreach (qw(inbound outbound)) {
1832 # hmm...we can't filter by status here, because there might
1833 # not be cdr_terminations at all. have to go by date.
1834 # find all since the last bill date.
1835 # XXX cdr types? we are going to need them.
1837 my $sum_cdr = $svc_x->sum_cdrs(
1838 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1839 'begin' => ($cust_pkg->last_bill || 0),
1841 'disable_charged_party' => 1,
1843 $hash{$_} = $sum_cdr->hashref;
1848 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1859 map { $usage_pools{$_} }
1867 sub _customer_svc_x {
1868 my($custnum, $svcnum, $table) = (shift, shift, shift);
1869 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1871 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1872 my $search = " AND custnum = $1";
1873 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1876 'table' => ($table || 'svc_acct'),
1877 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1878 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1879 #'LEFT JOIN cust_main USING ( custnum ) ',
1880 'hashref' => $hashref,
1881 'extra_sql' => $search, #important
1886 sub svc_status_html {
1889 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1890 return { 'error' => $session } if $context eq 'error';
1892 #XXX only svc_dsl for now
1893 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1894 or return { 'error' => "Service not found" };
1896 my $html = $svc_x->getstatus_html;
1898 return { 'html' => $html };
1902 sub svc_status_hash {
1905 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1906 return { 'error' => $session } if $context eq 'error';
1908 #XXX only svc_acct for now
1909 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1910 or return { 'error' => "Service not found" };
1912 my ( $html, $hashref ) = $svc_x->export_getstatus;
1917 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1918 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1919 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1920 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1921 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1924 my( $p, $method ) = @_;
1926 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1927 return { 'error' => $session } if $context eq 'error';
1929 #XXX only svc_acct for now
1930 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1931 or return { 'error' => "Service not found" };
1933 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1935 my $error = $svc_x->$method($p); #$p? returns error?
1936 return { 'error' => $error } if $error;
1938 return {}; #? { 'error' => '' }
1942 sub acct_forward_info {
1945 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1946 return { 'error' => $session } if $context eq 'error';
1948 my $svc_forward = _customer_svc_x( $custnum,
1949 { 'srcsvc' => $p->{'svcnum'} },
1952 or return { 'error' => '',
1956 return { 'error' => '',
1957 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1962 sub process_acct_forward {
1964 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1965 return { 'error' => $session } if $context eq 'error';
1967 my $old = _customer_svc_x( $custnum,
1968 { 'srcsvc' => $p->{'svcnum'} },
1972 if ( $p->{'dst'} eq '' ) {
1974 my $error = $old->delete;
1975 return { 'error' => $error };
1977 return { 'error' => '' };
1980 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1981 'dst' => $p->{'dst'},
1986 $new->svcnum($old->svcnum);
1987 my $cust_svc = $old->cust_svc;
1988 $new->svcpart($old->svcpart);
1989 $new->pkgnuym($old->pkgnum);
1990 $error = $new->replace($old);
1992 my $conf = new FS::Conf;
1993 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1995 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1996 or return { 'error' => 'No service' }; #how would we even get here?
1998 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2000 $error = $new->insert;
2003 return { 'error' => $error };
2007 sub list_dsl_devices {
2010 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2011 return { 'error' => $session } if $context eq 'error';
2013 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2014 or return { 'error' => "Service not found" };
2017 'devices' => [ map {
2018 +{ 'mac_addr' => $_->mac_addr };
2019 } $svc_dsl->dsl_device
2025 sub add_dsl_device {
2028 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2029 return { 'error' => $session } if $context eq 'error';
2031 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2032 or return { 'error' => "Service not found" };
2034 return { 'error' => 'No MAC address supplied' }
2035 unless length($p->{'mac_addr'});
2037 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2038 'mac_addr' => scalar($p->{'mac_addr'}),
2040 my $error = $dsl_device->insert;
2041 return { 'error' => $error };
2045 sub delete_dsl_device {
2048 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2049 return { 'error' => $session } if $context eq 'error';
2051 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2052 or return { 'error' => "Service not found" };
2054 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2055 'mac_addr' => scalar($p->{'mac_addr'}),
2058 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2060 my $error = $dsl_device->delete;
2061 return { 'error' => $error };
2067 _usage_details( \&_port_graph, $p,
2068 'svcdb' => 'svc_port',
2073 my($svc_port, $begin, $end) = @_;
2075 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2076 push @usage, { 'png' => $pngOrError };
2080 sub _list_svc_usage {
2081 my($svc_acct, $begin, $end) = @_;
2083 foreach my $part_export (
2084 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2085 qw( sqlradius sqlradius_withdomain )
2087 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2092 sub list_svc_usage {
2093 _usage_details(\&_list_svc_usage, @_);
2096 sub _list_support_usage {
2097 my($svc_acct, $begin, $end) = @_;
2099 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2100 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2102 push @usage, { 'seconds' => $_->seconds,
2103 'support' => $_->support,
2104 '_date' => $_->_date,
2105 'id' => $_->transaction_id,
2106 'creator' => $_->creator,
2107 'subject' => $_->subject,
2108 'status' => $_->status,
2109 'ticketid' => $_->ticketid,
2115 sub list_support_usage {
2116 _usage_details(\&_list_support_usage, @_);
2119 sub _list_cdr_usage {
2120 # XXX CDR type support...
2121 # XXX any way to do a paged search on this?
2122 # we have to return the results all at once...
2123 my($svc_phone, $begin, $end, %opt) = @_;
2124 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2125 $svc_phone->get_cdrs(
2128 'disable_charged_party' => 1,
2133 sub list_cdr_usage {
2135 _usage_details( \&_list_cdr_usage, $p,
2136 'svcdb' => 'svc_phone',
2140 sub _usage_details {
2141 my($callback, $p, %opt) = @_;
2142 my $conf = FS::Conf->new;
2144 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2145 return { 'error' => $session } if $context eq 'error';
2147 my $search = { 'svcnum' => $p->{'svcnum'} };
2148 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2150 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2152 my $svc_x = qsearchs( $svcdb, $search );
2153 return { 'error' => 'No service selected in list_svc_usage' }
2156 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2157 my $freq = $cust_pkg->part_pkg->freq;
2160 if ( $svcdb eq 'svc_phone' ) {
2162 if ( $p->{inbound} ) {
2163 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2164 || $conf->config('selfservice-default_inbound_cdr_format')
2165 || 'source_default';
2166 $callback_opt{inbound} = 1;
2168 $format = $cust_pkg->part_pkg->option('selfservice_format')
2169 || $conf->config('selfservice-default_cdr_format')
2173 $callback_opt{format} = $format;
2174 $callback_opt{use_clid} = 1;
2175 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2178 my $start = $cust_pkg->setup;
2179 #my $end = $cust_pkg->bill; # or time?
2182 unless ( $p->{beginning} ) {
2183 $p->{beginning} = $cust_pkg->last_bill;
2184 $p->{ending} = $end;
2187 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2188 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2190 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2194 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2195 # ugly kludge, I know
2196 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2197 if (defined $delete_col) {
2198 delete($_->[$delete_col]) foreach ($header, @usage);
2202 #kinda false laziness with FS::cust_main::bill, but perhaps
2203 #we should really change this bit to DateTime and DateTime::Duration
2205 #change this bit to use Date::Manip? CAREFUL with timezones (see
2206 # mailing list archive)
2207 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2208 (localtime($p->{ending}) )[0,1,2,3,4,5];
2209 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2210 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2212 if ( $freq =~ /^\d+$/ ) {
2214 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2216 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2217 } elsif ( $freq =~ /^(\d+)w$/ ) {
2219 $nmday += $weeks * 7;
2220 $pmday -= $weeks * 7;
2221 } elsif ( $freq =~ /^(\d+)d$/ ) {
2225 } elsif ( $freq =~ /^(\d+)h$/ ) {
2230 return { 'error' => "unparsable frequency: ". $freq };
2233 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2234 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2238 'svcnum' => $p->{svcnum},
2239 'beginning' => $p->{beginning},
2240 'ending' => $p->{ending},
2241 'inbound' => $p->{inbound},
2242 'previous' => ($previous > $start) ? $previous : $start,
2243 'next' => ($next < $end) ? $next : $end,
2244 'header' => $header,
2252 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2253 return { 'error' => $session } if $context eq 'error';
2255 my $search = { 'custnum' => $custnum };
2256 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2257 my $cust_main = qsearchs('cust_main', $search )
2258 or return { 'error' => "unknown custnum $custnum" };
2260 my $status = $cust_main->status;
2261 #false laziness w/ClientAPI/Signup.pm
2263 my $cust_pkg = new FS::cust_pkg ( {
2264 'custnum' => $custnum,
2265 'pkgpart' => $p->{'pkgpart'},
2267 my $error = $cust_pkg->check;
2268 return { 'error' => $error } if $error;
2271 unless ( $p->{'svcpart'} eq 'none' ) {
2275 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2277 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2278 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2279 $svcdb = $part_svc->svcdb;
2281 $svcdb = 'svc_acct';
2283 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2286 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2287 'svc_domain' => [ qw( domain ) ],
2288 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2289 'svc_external' => [ qw( id title ) ],
2290 'svc_pbx' => [ qw( id title ) ],
2293 my $svc_x = "FS::$svcdb"->new( {
2294 'svcpart' => $svcpart,
2295 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2298 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2301 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2302 my $acct_snarf = new FS::acct_snarf ( {
2303 'machine' => $p->{"snarf_machine$snarfnum"},
2304 'protocol' => $p->{"snarf_protocol$snarfnum"},
2305 'username' => $p->{"snarf_username$snarfnum"},
2306 '_password' => $p->{"snarf_password$snarfnum"},
2309 push @acct_snarf, $acct_snarf;
2311 $svc_x->child_objects( \@acct_snarf );
2314 my $y = $svc_x->setdefault; # arguably should be in new method
2315 return { 'error' => $y } if $y && !ref($y);
2317 $error = $svc_x->check;
2318 return { 'error' => $error } if $error;
2325 tie my %hash, 'Tie::RefHash';
2326 %hash = ( $cust_pkg => \@svc );
2328 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2329 return { 'error' => $error } if $error;
2331 my $conf = new FS::Conf;
2332 if ( $conf->exists('signup_server-realtime') ) {
2334 my $bill_error = _do_bop_realtime( $cust_main, $status );
2337 $cust_pkg->cancel('quiet'=>1);
2340 $cust_pkg->reexport;
2344 $cust_pkg->reexport;
2347 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2349 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2356 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2357 return { 'error' => $session } if $context eq 'error';
2359 my $conf = new FS::Conf;
2360 my $immutable = $conf->exists('selfservice_immutable-package');
2361 return { 'error' => "Package modification disabled" } if $immutable;
2363 my $search = { 'custnum' => $custnum };
2364 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2365 my $cust_main = qsearchs('cust_main', $search )
2366 or return { 'error' => "unknown custnum $custnum" };
2368 my $status = $cust_main->status;
2369 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2370 or return { 'error' => "unknown package $p->{pkgnum}" };
2372 #if someone does need self-service package change of suspended packages,
2373 # figure out how to be more discriminating
2374 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2375 if $cust_pkg->status eq 'suspended';
2378 my $error = FS::cust_pkg::order( $custnum,
2384 if ( $conf->exists('signup_server-realtime') ) {
2386 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2389 $newpkg[0]->suspend;
2392 $newpkg[0]->reexport;
2396 $newpkg[0]->reexport;
2399 return { error => '', pkgnum => $cust_pkg->pkgnum };
2403 sub order_recharge {
2406 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2407 return { 'error' => $session } if $context eq 'error';
2409 my $search = { 'custnum' => $custnum };
2410 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2411 my $cust_main = qsearchs('cust_main', $search )
2412 or return { 'error' => "unknown custnum $custnum" };
2414 my $status = $cust_main->status;
2415 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2416 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2418 my $svc_x = $cust_svc->svc_x;
2419 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2422 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2423 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2424 recharge_totalbytes );
2425 my $amount = $part_pkg->option('recharge_amount', 1);
2427 my ($l, $v, $d) = $cust_svc->label; # blah
2428 my $pkg = "Recharge $v";
2430 my $bill_error = $cust_main->charge($amount, $pkg,
2431 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2432 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2433 $part_pkg->taxclass); #meh
2435 my $conf = new FS::Conf;
2436 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2438 $bill_error = _do_bop_realtime( $cust_main, $status );
2443 my $error = $svc_x->recharge (\%vhash);
2444 return { 'error' => $error } if $error;
2448 my $error = $bill_error;
2449 $error ||= $svc_x->recharge (\%vhash);
2450 return { 'error' => $error } if $error;
2453 return { error => '', svc => $cust_svc->part_svc->svc };
2457 sub _do_bop_realtime {
2458 my ($cust_main, $status, %opt) = @_;
2460 my $old_balance = $cust_main->balance;
2462 my $bill_error = $cust_main->bill
2463 || $cust_main->apply_payments_and_credits;
2465 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2466 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2468 if ( $cust_main->balance > $old_balance
2469 && $cust_main->balance > 0
2470 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2471 || $status eq 'suspended'
2475 unless ( $opt{'no_credit'} ) {
2476 #this makes sense. credit is "un-doing" the invoice
2477 my $conf = new FS::Conf;
2478 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2479 'self-service decline',
2480 reason_type=>$conf->config('signup_credit_type'),
2482 $cust_main->apply_credits( 'order' => 'newest' );
2485 return { 'error' => '_decline', 'bill_error' => $bill_error };
2494 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2495 return { 'error' => $session } if $context eq 'error';
2497 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2498 or return { 'error' => "unknown custnum $custnum" };
2500 my @cust_pkg = sort { $a->bill <=> $b->bill }
2501 grep { $_->part_pkg->freq ne '0' }
2502 $cust_main->ncancelled_pkgs;
2504 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2506 my $total = $cust_main->balance;
2509 my $bill = $_->bill;
2510 $total += $_->part_pkg->base_recur($_, \$bill);
2511 my $renew_date = $_->part_pkg->add_freq($_->bill);
2513 'pkgnum' => $_->pkgnum,
2514 'amount' => sprintf('%.2f', $total),
2515 'bill_date' => $_->bill,
2516 'bill_date_pretty' => time2str('%x', $_->bill),
2517 'renew_date' => $renew_date,
2518 'renew_date_pretty' => time2str('%x', $renew_date),
2519 'expire_date' => $_->expire,
2520 'expire_date_pretty' => time2str('%x', $_->expire),
2525 return { 'dates' => \@array };
2529 sub payment_info_renew_info {
2531 my $renew_info = renew_info($p);
2532 my $payment_info = payment_info($p);
2533 return { %$renew_info,
2541 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2542 return { 'error' => $session } if $context eq 'error';
2544 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2545 or return { 'error' => "unknown custnum $custnum" };
2547 my $date = $p->{'date'};
2551 #freeside-daily -n -d $date fs_daily $custnum
2552 $cust_main->bill_and_collect( 'time' => $date,
2553 'invoice_time' => $now,
2554 'actual_time' => $now,
2555 'check_freq' => '1d',
2558 return { 'error' => '' };
2564 my $session = _cache->get($p->{'session_id'})
2565 or return { 'error' => "Can't resume session" }; #better error message
2567 my $custnum = $session->{'custnum'};
2569 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2570 or return { 'error' => "unknown custnum $custnum" };
2572 my $conf = new FS::Conf;
2574 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2575 or return { 'error' => 'Permission denied' };
2577 my $pkgnum = $p->{'pkgnum'};
2579 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2580 'pkgnum' => $pkgnum, } )
2581 or return { 'error' => "unknown pkgnum $pkgnum" };
2583 my $error = $cust_pkg->suspend(reason => $reasonnum);
2584 return { 'error' => $error };
2590 my $session = _cache->get($p->{'session_id'})
2591 or return { 'error' => "Can't resume session" }; #better error message
2593 my $custnum = $session->{'custnum'};
2595 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2596 or return { 'error' => "unknown custnum $custnum" };
2598 my $pkgnum = $p->{'pkgnum'};
2600 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2601 'pkgnum' => $pkgnum, } )
2602 or return { 'error' => "unknown pkgnum $pkgnum" };
2604 my $error = $cust_pkg->cancel('quiet' => 1);
2605 return { 'error' => $error };
2609 sub provision_phone {
2612 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2614 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2615 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2616 return { 'error' => $session } if $context eq 'error';
2618 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2619 return { 'error' => 'service not found' } unless $svc_phone;
2620 return { 'error' => 'invalid svcnum' }
2621 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2623 $svc_phone->email($p->{'email'})
2624 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2625 $svc_phone->forwarddst($p->{'forwarddst'})
2626 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2627 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2628 return { 'error' => $svc_phone->replace };
2632 unless($p->{'lnp'}) {
2633 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2634 $p->{'lnp_status'} = "portingin";
2635 return _provision( 'FS::svc_phone',
2636 [qw(lnp_desired_due_date lnp_other_provider
2637 lnp_other_provider_account phonenum countrycode lnp_status)],
2638 [qw(phonenum countrycode)],
2645 unless (scalar(@bulkdid)) {
2646 return _provision( 'FS::svc_phone',
2647 [qw(phonenum countrycode)],
2648 [qw(phonenum countrycode)],
2654 # bulk DID order case
2656 foreach my $did ( @bulkdid ) {
2657 $did =~ s/[^0-9]//g;
2658 $error = _provision( 'FS::svc_phone',
2659 [qw(phonenum countrycode)],
2660 [qw(phonenum countrycode)],
2662 'pkgnum' => $p->{'pkgnum'},
2663 'svcpart' => $p->{'svcpart'},
2665 'countrycode' => $p->{'countrycode'},
2666 'session_id' => $p->{'session_id'},
2669 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2671 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2674 sub provision_acct {
2676 warn "provision_acct called\n"
2679 return { 'error' => gettext('passwords_dont_match') }
2680 if $p->{'_password'} ne $p->{'_password2'};
2681 return { 'error' => gettext('empty_password') }
2682 unless length($p->{'_password'});
2684 if ($p->{'domsvc'}) {
2685 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2686 qw ( svcpart pkgnum ) );
2687 return { 'error' => gettext('invalid_domain') }
2688 unless ($domains{$p->{'domsvc'}});
2691 warn "provision_acct calling _provision\n"
2693 _provision( 'FS::svc_acct',
2694 [qw(username _password domsvc)],
2695 [qw(username _password domsvc)],
2701 sub provision_external {
2703 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2704 _provision( 'FS::svc_external',
2713 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2714 warn "_provision called for $class\n"
2717 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2718 return { 'error' => $session } if $context eq 'error';
2720 my $search = { 'custnum' => $custnum };
2721 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2722 my $cust_main = qsearchs('cust_main', $search )
2723 or return { 'error' => "unknown custnum $custnum" };
2725 my $pkgnum = $p->{'pkgnum'};
2727 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2729 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2730 'pkgnum' => $pkgnum,
2732 or return { 'error' => "unknown pkgnum $pkgnum" };
2734 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2736 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2737 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2739 warn "creating $class record\n"
2741 my $svc_x = $class->new( {
2742 'pkgnum' => $p->{'pkgnum'},
2743 'svcpart' => $p->{'svcpart'},
2744 map { $_ => $p->{$_} } @$fields
2746 warn "inserting $class record\n"
2748 my $error = $svc_x->insert;
2751 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2753 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2756 my $return = { 'svc' => $part_svc->svc,
2758 map { $_ => $svc_x->get($_) } @$return_fields
2760 warn "_provision returning ". Dumper($return). "\n"
2769 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2770 return { 'error' => $session } if $context eq 'error';
2772 my $search = { 'custnum' => $custnum };
2773 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2774 my $cust_main = qsearchs('cust_main', $search )
2775 or return { 'error' => "unknown custnum $custnum" };
2777 my $pkgnum = $p->{'pkgnum'};
2779 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2780 'pkgnum' => $pkgnum,
2782 or return { 'error' => "unknown pkgnum $pkgnum" };
2784 my $svcpart = $p->{'svcpart'};
2786 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2787 'svcpart' => $svcpart, } )
2788 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2789 my $part_svc = $pkg_svc->part_svc;
2791 my $conf = new FS::Conf;
2794 'svc' => $part_svc->svc,
2795 'svcdb' => $part_svc->svcdb,
2796 'pkgnum' => $pkgnum,
2797 'svcpart' => $svcpart,
2798 'custnum' => $custnum,
2800 'security_phrase' => 0, #XXX !
2801 'svc_acct_pop' => [], #XXX !
2803 'init_popstate' => '',
2808 small_custview( $cust_main, $conf->config('countrydefault') ),
2812 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2813 && $ret->{'svcdb'} eq 'svc_phone') {
2814 $ret->{'svcnum'} = $p->{'svcnum'};
2815 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2816 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2817 $ret->{'email'} = $svc_phone->email;
2818 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2825 sub unprovision_svc {
2828 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2829 return { 'error' => $session } if $context eq 'error';
2831 my $search = { 'custnum' => $custnum };
2832 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2833 my $cust_main = qsearchs('cust_main', $search )
2834 or return { 'error' => "unknown custnum $custnum" };
2836 my $svcnum = $p->{'svcnum'};
2838 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2839 or return { 'error' => "unknown svcnum $svcnum" };
2841 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2842 unless $cust_svc->cust_pkg->custnum == $custnum;
2844 my $conf = new FS::Conf;
2846 return { 'svc' => $cust_svc->part_svc->svc,
2847 'error' => $cust_svc->cancel,
2849 small_custview( $cust_main, $conf->config('countrydefault') ),
2854 sub myaccount_passwd {
2856 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2857 return { 'error' => $session } if $context eq 'error';
2859 return { 'error' => "New passwords don't match." }
2860 if $p->{'new_password'} ne $p->{'new_password2'};
2862 return { 'error' => 'Enter new password' }
2863 unless length($p->{'new_password'});
2865 #my $search = { 'custnum' => $custnum };
2866 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2867 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2868 my $search = " AND custnum = $1";
2869 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2871 my $svc_acct = qsearchs( {
2872 'table' => 'svc_acct',
2873 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2874 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2875 'LEFT JOIN cust_main USING ( custnum ) ',
2876 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2877 'extra_sql' => $search, #important
2879 or return { 'error' => "Service not found" };
2883 my $conf = new FS::Conf;
2885 return { 'error' => 'Incorrect current password.' }
2886 if ( exists($p->{'old_password'})
2887 || $conf->exists('selfservice-password_change_oldpass')
2889 && ! $svc_acct->check_password($p->{'old_password'});
2891 $error = 'Password too short.'
2892 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2893 $error = 'Password too long.'
2894 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2896 $svc_acct->set_password($p->{'new_password'});
2897 $error ||= $svc_acct->replace();
2899 #regular pw change in self-service should change contact pw too, otherwise its
2900 #way too confusing. hell its confusing they're separate at all, but alas.
2901 #need to support the "ISP provides email that's used as a contact email" case
2903 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2904 if ( $contact && $contact->custnum == $custnum ) {
2905 #svc_acct was successful but this one returns an error? "shouldn't happen"
2906 $error ||= $contact->change_password($p->{'new_password'});
2909 my($label, $value) = $svc_acct->cust_svc->label;
2911 return { 'error' => $error,
2918 # sub contact_passwd {
2920 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2921 # return { 'error' => $session } if $context eq 'error';
2923 # return { 'error' => 'Not logged in as a contact.' }
2924 # unless $session->{'contactnum'};
2926 # return { 'error' => "New passwords don't match." }
2927 # if $p->{'new_password'} ne $p->{'new_password2'};
2929 # return { 'error' => 'Enter new password' }
2930 # unless length($p->{'new_password'});
2932 # #my $search = { 'custnum' => $custnum };
2933 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2934 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2935 # my $search = " AND selfservice_access IS NOT NULL ".
2936 # " AND selfservice_access = 'Y' ".
2937 # " AND ( disabled IS NULL OR disabled = '' )".
2938 # " AND custnum IS NOT NULL AND custnum = $1";
2939 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2941 # my $contact = qsearchs( {
2942 # 'table' => 'contact',
2943 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2944 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2945 # 'extra_sql' => $search, #important
2947 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2948 # # deleted since then?
2952 # # use these svc_acct length restrictions??
2953 # my $conf = new FS::Conf;
2954 # $error = 'Password too short.'
2955 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2956 # $error = 'Password too long.'
2957 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2959 # $error ||= $contact->change_password($p->{'new_password'});
2961 # return { 'error' => $error, };
2968 my $info = skin_info($p);
2970 my $conf = new FS::Conf;
2971 my $verification = $conf->config('selfservice-password_reset_verification')
2972 or return { %$info, 'error' => 'Password resets disabled' };
2977 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2979 $contact = FS::contact->by_selfservice_email($p->{'email'});
2981 $cust_main = $contact->cust_main if $contact;
2983 #also look for an svc_acct, otherwise it would be super confusing
2985 my($username, $domain) = split('@', $p->{'email'});
2986 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2987 if ( $svc_domain ) {
2988 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2989 'domsvc' => $svc_domain->svcnum }
2992 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2993 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
2995 #precaution: don't change svc_acct password not part of the same
2996 # customer as contact
2997 $svc_acct = '' if ! $cust_pkg
2998 || $cust_pkg->custnum != $cust_main->custnum;
3003 return { %$info, 'error' => 'Email address not found' }
3004 unless $contact || $svc_acct;
3006 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3008 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3009 or return { %$info, 'error' => 'Account not found' };
3011 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3012 'domsvc' => $svc_domain->svcnum }
3014 or return { %$info, 'error' => 'Account not found' };
3016 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3017 or return { %$info, 'error' => 'Account not found' };
3019 $cust_main = $cust_pkg->cust_main;
3024 'email' => sub { 1; },
3026 my( $p, $cust_main ) = @_;
3027 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3028 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3031 my( $p, $cust_main ) = @_;
3032 my $cust_pay = qsearchs({
3033 'table' => 'cust_pay',
3034 'hashref' => { 'custnum' => $cust_main->custnum },
3035 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3039 $p->{'amount'} == $cust_pay->paid;
3042 my( $p, $cust_main ) = @_;
3043 $p->{'zip'} eq $cust_main->zip
3044 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3048 foreach my $verify ( split(',', $verification) ) {
3050 &{ $verify{$verify} }( $p, $cust_main )
3051 or return { %$info, 'error' => 'Account not found' };
3055 #okay, we're verified
3059 my $error = $contact->send_reset_email(
3060 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3064 return { %$info, 'error' => $error }; #????
3067 } elsif ( $svc_acct ) {
3069 #create a unique session
3071 my $reset_session = {
3072 'svcnum' => $svc_acct->svcnum,
3076 my $timeout = '1 hour'; #?
3078 my $reset_session_id;
3080 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3081 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3084 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3088 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3089 $cust_main->agentnum);
3090 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3091 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3093 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3094 my $error = $msg_template->send( 'cust_main' => $cust_main,
3095 'object' => $svc_acct,
3096 'substitutions' => {
3097 'session_id' => $reset_session_id,
3101 return { %$info, 'error' => $error }; #????
3106 return { %$info, 'error' => '' };
3109 sub check_reset_passwd {
3112 my $conf = new FS::Conf;
3113 my $verification = $conf->config('selfservice-password_reset_verification')
3114 or return { 'error' => 'Password resets disabled' };
3116 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3117 or return { 'error' => "Can't resume session" }; #better error message
3119 if ( $reset_session->{'svcnum'} ) {
3121 my $svcnum = $reset_session->{'svcnum'};
3123 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3124 or return { 'error' => "Service not found" };
3126 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3127 my $info = skin_info($p);
3131 'session_id' => $p->{'session_id'},
3132 'username' => $svc_acct->username,
3135 } elsif ( $reset_session->{'contactnum'} ) {
3137 my $contactnum = $reset_session->{'contactnum'};
3139 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3140 or return { 'error' => "Contact not found" };
3142 my @contact_email = $contact->contact_email;
3143 return { 'error' => 'No contact email' } unless @contact_email;
3145 $p->{'agentnum'} = $contact->cust_main->agentnum;
3146 my $info = skin_info($p);
3150 'session_id' => $p->{'session_id'},
3151 'email' => $contact_email[0]->email, #the first?
3156 return { 'error' => 'No svcnum or contactnum in session' }; #??
3162 sub process_reset_passwd {
3165 my $conf = new FS::Conf;
3166 my $verification = $conf->config('selfservice-password_reset_verification')
3167 or return { 'error' => 'Password resets disabled' };
3169 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3170 or return { 'error' => "Can't resume session" }; #better error message
3175 if ( $reset_session->{'svcnum'} ) {
3177 my $svcnum = $reset_session->{'svcnum'};
3179 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3180 or return { 'error' => "Service not found" };
3182 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3183 $info ||= skin_info($p);
3188 if ( $reset_session->{'contactnum'} ) {
3190 my $contactnum = $reset_session->{'contactnum'};
3192 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3193 or return { 'error' => "Contact not found" };
3195 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3196 $info ||= skin_info($p);
3200 return { %$info, 'error' => "New passwords don't match." }
3201 if $p->{'new_password'} ne $p->{'new_password2'};
3203 return { %$info, 'error' => 'Enter new password' }
3204 unless length($p->{'new_password'});
3208 $svc_acct->set_password($p->{'new_password'});
3209 my $error = $svc_acct->replace();
3211 return { %$info, 'error' => $error } if $error;
3213 #my($label, $value) = $svc_acct->cust_svc->label;
3214 #return { 'error' => $error,
3215 # #'label' => $label,
3216 # #'value' => $value,
3223 my $error = $contact->change_password($p->{'new_password'});
3225 return { %$info, 'error' => $error }; # if $error;
3229 #password changed ,so remove session, don't want it reused
3230 _cache->remove($p->{'session_id'});
3232 return { %$info, 'error' => '' };
3238 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3239 return { 'error' => $session } if $context eq 'error';
3242 if ( $session->{'pkgnum'} ) {
3244 #tickets for specific service with pkg-balances on
3245 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3246 'pkgnum' => $session->{'pkgnum'} })
3247 or return { 'error' => 'unknown package' };
3248 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3249 push @tickets, $cust_svc->tickets( $p->{status} );
3254 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3255 or return { 'error' => "unknown custnum $custnum" };
3257 @tickets = $cust_main->tickets( $p->{status} );
3260 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3261 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3262 my $conf = new FS::Conf;
3263 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3267 ($a->{'_selfservice_priority'} eq '') <=>
3268 ($b->{'_selfservice_priority'} eq '')
3271 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3277 +{ tickets => \@tickets };
3284 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3285 return { 'error' => $session } if $context eq 'error';
3287 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3288 FS::TicketSystem->init();
3290 my $conf = new FS::Conf;
3291 my $queue = $p->{'queue'}
3292 || $conf->config('ticket_system-selfservice_queueid')
3293 || $conf->config('ticket_system-default_queueid');
3295 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3296 my $err_or_ticket = FS::TicketSystem->create_ticket(
3297 '', #create RT session based on FS CurrentUser (fs_selfservice)
3299 'custnum' => $custnum,
3300 'svcnum' => $session->{'svcnum'},
3301 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3304 if ( ref($err_or_ticket) ) {
3305 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3307 return { 'error' => '',
3308 'ticket_id' => $err_or_ticket->id,
3311 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3313 return { 'error' => $err_or_ticket };
3321 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3322 return { 'error' => $session } if $context eq 'error';
3324 return { error => 'requested format not implemented' }
3325 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3327 my $conf = new FS::Conf;
3328 my $age_threshold = 0;
3329 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3330 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3332 my $search = { 'custnum' => $custnum };
3333 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3334 my $cust_main = qsearchs('cust_main', $search )
3335 or return { 'error' => "unknown custnum $custnum" };
3337 # does it make more sense to just run one sql query for this instead of all the
3338 # insanity below? would increase performance greately for large data sets?
3340 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3341 my @part_svc = $cust_pkg->part_svc;
3342 foreach my $part_svc ( @part_svc ) {
3343 if($part_svc->svcdb eq 'svc_phone'){
3344 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3345 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3346 push @svc_phone, $cust_pkg_svc->svc_x
3347 if $cust_pkg_svc->date_inserted >= $age_threshold;
3355 my($xls_r,$xls_c) = (0,0);
3358 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3359 if($p->{'format'} eq 'csv') {
3360 $csv = new Text::CSV_XS { 'always_quote' => 1,
3363 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3364 $content .= $csv->string;
3366 elsif($p->{'format'} eq 'xls') {
3367 my $XLS1 = new IO::Scalar \$content;
3368 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3369 or return { 'error' => "Error opening .xls file: $!" };
3370 $xls = $xls_workbook->add_worksheet('DIDs');
3371 foreach ( @fields ) {
3372 $xls->write(0,$xls_c++,$_);
3377 foreach my $svc_phone ( @svc_phone ) {
3378 my @cols = map { $svc_phone->$_ } @fields;
3379 if($p->{'format'} eq 'csv') {
3380 return { 'error' => 'Unable to create CSV' }
3381 unless $csv->combine(@cols);
3382 $content .= $csv->string;
3384 elsif($p->{'format'} eq 'xls') {
3387 $xls->write($xls_r,$xls_c++,$_);
3393 $xls_workbook->close() if $p->{'format'} eq 'xls';
3395 { content => $content, format => $p->{'format'}, };
3400 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3401 return { 'error' => $session } if $context eq 'error';
3403 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3404 # FS::TicketSystem->init();
3405 # return { 'error' => 'get_ticket configuration error' }
3406 # if $FS::TicketSystem::system ne 'RT_Internal';
3408 # check existence and ownership as part of this
3409 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3410 my $rt_session = FS::TicketSystem->session('');
3411 my $Ticket = FS::TicketSystem->get_ticket_object(
3413 ticket_id => $p->{'ticket_id'},
3416 return { 'error' => 'ticket not found' } if !$Ticket;
3418 if ( length( $p->{'subject'} || '' ) ) {
3420 if ( $p->{'subject'} ne $Ticket->Subject ) {
3421 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3422 return { 'error' => "unable to set subject: $msg" } if !$val;
3426 if(length($p->{'reply'})) {
3427 my @err_or_res = FS::TicketSystem->correspond_ticket(
3429 'ticket_id' => $p->{'ticket_id'},
3430 'content' => $p->{'reply'},
3433 return { 'error' => 'unable to reply to ticket' }
3434 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3437 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3438 my $err_or_ticket = FS::TicketSystem->get_ticket(
3440 'ticket_id' => $p->{'ticket_id'},
3443 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3444 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3446 return { 'error' => $err_or_ticket };
3449 my @custs = @{$err_or_ticket->{'custs'}};
3450 my @txns = @{$err_or_ticket->{'txns'}};
3453 # superseded by check in get_ticket_object
3454 #return { 'error' => 'invalid ticket requested' }
3455 #unless grep($_ eq $custnum, @custs);
3457 foreach my $txn ( @txns ) {
3458 push @filtered_txns, $txn
3459 if ($txn->{'type'} eq 'EmailRecord'
3460 || $txn->{'type'} eq 'Correspond'
3461 || $txn->{'type'} eq 'Create');
3464 warn "$me get_ticket: successful: \n"
3466 return { 'error' => '',
3467 'transactions' => \@filtered_txns,
3468 'ticket_fields' => $err_or_ticket->{'fields'},
3469 'ticket_id' => $p->{'ticket_id'},
3473 sub adjust_ticket_priority {
3475 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3476 return { 'error' => $session } if $context eq 'error';
3478 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3479 # FS::TicketSystem->init;
3480 my $ss_priority = FS::TicketSystem->selfservice_priority;
3482 return { 'error' => 'adjust_ticket_priority configuration error' }
3483 if $FS::TicketSystem::system ne 'RT_Internal'
3486 my $values = $p->{'values'}; #hashref, id => priority value
3489 foreach my $id (keys %$values) {
3490 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3491 my $Ticket = FS::TicketSystem->get_ticket_object('',
3493 'custnum' => $custnum,
3496 $ticket_error{$id} = 'ticket not found';
3500 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3501 # We're not going to implement it for RT_External.
3502 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3503 my $new_value = $values->{$id};
3504 next if $old_value eq $new_value;
3506 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3508 # AddCustomFieldValue works fine (replacing any existing value) if it's
3509 # a single-valued custom field, which it should be. If it's not, you're
3510 # doing something wrong.
3512 if ( length($new_value) ) {
3513 ($val, $msg) = $Ticket->AddCustomFieldValue(
3514 Field => $ss_priority,
3515 Value => $new_value,
3519 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3520 Field => $ss_priority,
3521 Value => $old_value,
3525 $ticket_error{$id} = $msg if !$val;
3526 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3528 return { 'error' => '',
3529 'ticket_error' => \%ticket_error,
3530 %{ customer_info($p) } # send updated customer info back
3536 sub _custoragent_session_custnum {
3539 my($context, $session, $custnum);
3540 if ( $p->{'session_id'} ) {
3542 $context = 'customer';
3543 $session = _cache->get($p->{'session_id'})
3544 or return ( 'error' => "Can't resume session" ); #better error message
3545 $custnum = $session->{'custnum'};
3547 } elsif ( $p->{'agent_session_id'} ) {
3550 my $agent_cache = new FS::ClientAPI_SessionCache( {
3551 'namespace' => 'FS::ClientAPI::Agent',
3553 $session = $agent_cache->get($p->{'agent_session_id'})
3554 or return ( 'error' => "Can't resume session" ); #better error message
3555 $custnum = $p->{'custnum'};
3559 return ( 'error' => "Can't resume session" ); #better error message
3562 ($context, $session, $custnum);