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;
49 use FS::cust_location;
52 $me = '[FS::ClientAPI::MyAccount]';
54 use vars qw( @cust_main_editable_fields @location_editable_fields );
55 @cust_main_editable_fields = qw(
56 first last company daytime night fax mobile
58 payby payinfo payname paystart_month paystart_year payissue payip
59 ss paytype paystate stateid stateid_state
61 @location_editable_fields = qw(
62 address1 address2 city county state zip country
66 BEGIN { #preload to reduce time customer_info takes
67 if ( $FS::TicketSystem::system ) {
68 warn "$me: initializing ticket system\n" if $DEBUG;
69 FS::TicketSystem->init();
74 $cache ||= new FS::ClientAPI_SessionCache( {
75 'namespace' => 'FS::ClientAPI::MyAccount',
82 my($context, $session, $custnum) = _custoragent_session_custnum($p);
83 #return { 'error' => $session } if $context eq 'error';
86 if ( $context eq 'customer' ) {
88 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
91 $sth->execute($custnum) or die $sth->errstr;
93 $agentnum = $sth->fetchrow_arrayref->[0]
94 or die "no agentnum for custnum $custnum";
96 #} elsif ( $context eq 'agent' ) {
97 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
100 $p->{'agentnum'} = $agentnum;
102 my $conf = new FS::Conf;
104 #false laziness w/Signup.pm
106 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
108 if ( $skin_info_cache_agent ) {
110 warn "$me loading cached skin info for agentnum $agentnum\n"
115 warn "$me populating skin info cache for agentnum $agentnum\n"
118 $skin_info_cache_agent = {
119 'agentnum' => $agentnum,
120 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
121 qw( company_name date_format ) ),
122 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
123 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
124 text_color link_color vlink_color hlink_color alink_color
125 font title_color title_align title_size menu_bgcolor menu_fontsize
128 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
129 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
130 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
132 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
133 qw( title_left_image title_right_image
134 menu_top_image menu_body_image menu_bottom_image
137 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
138 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
139 qw( head body_header body_footer company_address ) ),
140 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
143 services.php Services
144 services.php My Services
145 services_new.php Order a new service
148 personal.php Personal Information
149 password.php Change Password
152 payment_cc.php Credit Card Payment
153 payment_ach.php Electronic Check Payment
154 payment_paypal.php PayPal Payment
155 payment_webpay.php Webpay Payments
158 usage_data.php Data usage
159 usage_cdr.php Call usage
161 tickets.php Help Desk
162 tickets.php Open Tickets
163 tickets_resolved.php Resolved Tickets
164 ticket_create.php Create a new ticket
172 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
176 #{ %$skin_info_cache_agent };
177 $skin_info_cache_agent;
184 my $conf = new FS::Conf;
188 'phone_login' => $conf->exists('selfservice_server-phone_login'),
189 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
190 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
191 'banner_image_md5' =>
192 md5_hex($conf->config_binary('selfservice-login_banner_image')),
199 sub login_banner_image {
201 my $conf = new FS::Conf;
202 my $image = $conf->config_binary('selfservice-login_banner_image');
204 'md5' => md5_hex($image),
209 #false laziness w/FS::ClientAPI::passwd::passwd
213 my $conf = new FS::Conf;
217 if ( $p->{'domain'} eq 'svc_phone'
218 && $conf->exists('selfservice_server-phone_login') ) {
220 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
221 return { error => 'Number not found.' } unless $svc_phone;
224 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
225 #return { error => 'Only primary user may log in.' }
226 # if $conf->exists('selfservice_server-primary_only')
227 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
229 return { error => 'Incorrect PIN.' }
230 unless $svc_phone->check_pin($p->{'password'});
234 } elsif ( $p->{email}
235 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
238 return { error => 'Incorrect contact password.' }
239 unless $contact->authenticate_password($p->{'password'});
241 $session->{'custnum'} = $contact->custnum;
245 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
247 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
248 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
250 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
251 'domsvc' => $svc_domain->svcnum, }
253 return { error => 'User not found.' } unless $svc_acct;
255 if($conf->exists('selfservice_server-login_svcpart')) {
256 my @svcpart = $conf->config('selfservice_server-login_svcpart');
257 my $svcpart = $svc_acct->cust_svc->svcpart;
258 return { error => 'Invalid user.' }
259 unless grep($_ eq $svcpart, @svcpart);
262 return { error => 'Incorrect password.' }
263 unless $svc_acct->check_password($p->{'password'});
271 $session->{'svcnum'} = $svc_x->svcnum;
273 my $cust_svc = $svc_x->cust_svc;
274 my $cust_pkg = $cust_svc->cust_pkg;
276 my $cust_main = $cust_pkg->cust_main;
277 $session->{'custnum'} = $cust_main->custnum;
278 if ( $conf->exists('pkg-balances') ) {
279 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
280 $cust_main->ncancelled_pkgs;
281 $session->{'pkgnum'} = $cust_pkg->pkgnum
282 if scalar(@cust_pkg) > 1;
286 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
287 #return { error => 'Only primary user may log in.' }
288 # if $conf->exists('selfservice_server-primary_only')
289 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
290 my $part_pkg = $cust_pkg->part_pkg;
291 return { error => 'Only primary user may log in.' }
292 if $conf->exists('selfservice_server-primary_only')
293 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
299 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
300 } until ( ! defined _cache->get($session_id) ); #just in case
302 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
303 _cache->set( $session_id, $session, $timeout );
305 return { 'error' => '',
306 'session_id' => $session_id,
312 my $skin_info = skin_info($p);
313 if ( $p->{'session_id'} ) {
314 _cache->remove($p->{'session_id'});
315 return { %$skin_info, 'error' => '' };
317 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
324 my($context, $session, $custnum) = _custoragent_session_custnum($p);
325 return { 'error' => $session } if $context eq 'error';
327 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
328 or return { 'error' => "Service not found" };
330 $session->{'svcnum'} = $svc_acct->svcnum;
332 my $conf = new FS::Conf;
333 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
334 _cache->set( $p->{'session_id'}, $session, $timeout );
336 return { 'error' => '' };
340 sub payment_gateway {
342 # takes a cust_main and a cust_payby entry, returns the payment_gateway
343 my $conf = new FS::Conf;
344 my $cust_main = shift;
345 my $cust_payby = shift;
346 my $gatewaynum = $conf->config('selfservice-payment_gateway');
348 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
349 die "configured gatewaynum $gatewaynum not found!" if !$pg;
353 return '' if ! FS::payby->realtime($cust_payby);
354 my $pg = $cust_main->agent->payment_gateway(
355 'method' => FS::payby->payby2bop($cust_payby),
365 my $conf = new FS::Conf;
367 my $info = skin_info($p);
369 use vars qw( $cust_paybys ); #cache for performance
370 unless ( $cust_paybys ) {
372 my %cust_paybys = map { $_ => 1 }
373 map { FS::payby->payby2payment($_) }
374 $conf->config('signup_server-payby');
376 $cust_paybys = [ keys %cust_paybys ];
379 $info->{'cust_paybys'} = $cust_paybys;
381 my($context, $session, $custnum) = _custoragent_session_custnum($p);
382 return { 'error' => $session } if $context eq 'error';
384 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
385 or return { 'error' => "unknown custnum $custnum" };
387 $info->{'hide_payment_fields'} = [
389 my $pg = payment_gateway($cust_main, $_);
390 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
391 } @{ $info->{cust_paybys} }
394 $info->{'self_suspend_reason'} =
395 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
397 $info->{'edit_ticket_subject'} =
398 $conf->exists('ticket_system-selfservice_edit_subject') &&
399 $cust_main->edit_subject;
401 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
403 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
406 'custnum' => $custnum,
407 'access_pkgnum' => $session->{'pkgnum'},
408 'access_svcnum' => $session->{'svcnum'},
415 my($context, $session, $custnum) = _custoragent_session_custnum($p);
416 return { 'error' => $session } if $context eq 'error';
420 my $conf = new FS::Conf;
421 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
423 # if ( $FS::TicketSystem::system ) {
424 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
425 # FS::TicketSystem->init();
428 if ( $custnum ) { #customer record
430 %return = ( %return, %{ customer_info_short($p) } );
432 #redundant with customer_info_short, but we need it for several things below
433 my $search = { 'custnum' => $custnum };
434 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
435 my $cust_main = qsearchs('cust_main', $search )
436 or return { 'error' => "unknown custnum $custnum" };
438 my $list_tickets = list_tickets($p);
439 $return{'tickets'} = $list_tickets->{'tickets'};
441 if ( $session->{'pkgnum'} ) {
442 #XXX open invoices in the pkg-balances case
446 invnum => $_->invnum,
447 date => time2str("%b %o, %Y", $_->_date),
450 } $cust_main->open_cust_bill;
451 $return{open_invoices} = \@open;
453 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
454 my $sth = dbh->prepare($sql) or die dbh->errstr;
455 $sth->execute($custnum) or die $sth->errstr;
456 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
457 $return{'last_invoice_date_pretty'} =
458 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
461 #customer_info_short always has nobalance on..
462 $return{small_custview} =
463 small_custview( $cust_main,
464 $return{countrydefault},
465 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
468 $return{has_ship_address} = $cust_main->has_ship_address;
469 $return{status} = $cust_main->status;
470 $return{statuscolor} = $cust_main->statuscolor;
472 # compatibility: some places in selfservice use this to determine
473 # if there's a ship address
474 if ( $return{has_ship_address} ) {
475 $return{ship_last} = $cust_main->last;
476 $return{ship_first} = $cust_main->first;
479 if (scalar($conf->config('support_packages'))) {
480 my @support_services = ();
481 foreach ($cust_main->support_services) {
482 my $seconds = $_->svc_x->seconds || 0;
483 my $time_remaining = (($seconds < 0) ? '-' : '' ).
484 int(abs($seconds)/3600)."h".
485 sprintf("%02d",(abs($seconds)%3600)/60)."m";
486 my $cust_pkg = $_->cust_pkg;
489 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
490 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
491 push @support_services, { svcnum => $_->svcnum,
492 time => $time_remaining,
497 $return{support_services} = \@support_services;
500 if ( $conf->config('prepayment_discounts-credit_type') ) {
502 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
505 } elsif ( $session->{'svcnum'} ) { #no customer record
507 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
508 or die "unknown svcnum";
509 $return{name} = $svc_acct->email;
513 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
517 return { 'error' => '',
518 'custnum' => $custnum,
524 sub customer_info_short {
527 my($context, $session, $custnum) = _custoragent_session_custnum($p);
528 return { 'error' => $session } if $context eq 'error';
532 my $conf = new FS::Conf;
534 if ( $custnum ) { #customer record
536 my $search = { 'custnum' => $custnum };
537 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
538 my $cust_main = qsearchs('cust_main', $search )
539 or return { 'error' => "unknown custnum $custnum" };
541 $return{display_custnum} = $cust_main->display_custnum;
543 if ( $session->{'pkgnum'} ) {
544 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
545 #next_bill_date from cust_pkg?
547 $return{balance} = $cust_main->balance;
548 $return{next_bill_date} = $cust_main->next_bill_date;
549 $return{next_bill_date_pretty} =
550 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
554 $return{countrydefault} = scalar($conf->config('countrydefault'));
556 $return{small_custview} =
557 small_custview( $cust_main,
558 $return{countrydefault},
562 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
564 $return{payby} = $cust_main->payby;
566 #none of these are terribly expensive if we want 'em...
567 for (@cust_main_editable_fields) {
568 $return{$_} = $cust_main->get($_);
570 #maybe a little more expensive, but it should be cached by now
571 for (@location_editable_fields) {
572 $return{$_} = $cust_main->bill_location->get($_);
573 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
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,
1137 'paynum_ref' => \$paynum,
1140 return { 'error' => $error } if $error;
1142 #no error, so order the fee package if applicable...
1143 my $conf = new FS::Conf;
1144 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1145 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1147 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1149 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1151 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1152 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1155 #and generate an invoice for it now too
1156 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1157 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1162 $cust_main->apply_payments;
1164 if ( $validate->{'save'} ) {
1165 my $new = new FS::cust_main { $cust_main->hash };
1166 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1167 $new->set( $_ => $validate->{$_} )
1168 foreach qw( payname paystart_month paystart_year payissue payip );
1169 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1171 my $bill_location = FS::cust_location->new({
1172 map { $_ => $validate->{$_} }
1173 qw(address1 address2 city state country zip)
1175 $new->set('bill_location' => $bill_location);
1176 # but don't allow the service address to change this way.
1178 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1179 $new->set( $_ => $validate->{$_} )
1180 foreach qw( payname payip paytype paystate
1181 stateid stateid_state );
1182 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1184 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1185 $new->set( 'paydate' => $validate->{'paydate'} );
1186 my $error = $new->replace($cust_main);
1188 #no, this causes customers to process their payments again
1189 #return { 'error' => $error };
1190 #XXX just warn verosely for now so i can figure out how these happen in
1191 # the first place, eventually should redirect them to the "change
1192 #address" page but indicate the payment did process??
1193 delete($validate->{'payinfo'}); #don't want to log this!
1194 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1195 "NEW: ". Dumper($new)."\n".
1196 "OLD: ". Dumper($cust_main)."\n".
1197 "PACKET: ". Dumper($validate)."\n";
1205 my $receipt_html = '';
1207 # currently supported for realtime CC only; send receipt data to SS
1208 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1211 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1214 <TD ALIGN="right">Payment#</TD>
1215 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1219 <TD ALIGN="right">Date</TD>
1221 <TD BGCOLOR="#FFFFFF"><B>! .
1222 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1228 <TD ALIGN="right">Amount</TD>
1229 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1234 <TD ALIGN="right">Payment method</TD>
1235 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1248 'amount' => sprintf('%.2f', $cust_pay->paid),
1249 'date' => $cust_pay->_date,
1250 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1251 'time_pretty' => time2str('%T', $cust_pay->_date),
1252 'auth_num' => $cust_pay->auth,
1253 'order_num' => $cust_pay->order_number,
1254 'receipt_html' => $receipt_html,
1261 'receipt_html' => '',
1268 sub realtime_collect {
1271 my $session = _cache->get($p->{'session_id'})
1272 or return { 'error' => "Can't resume session" }; #better error message
1274 my $custnum = $session->{'custnum'};
1276 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1277 or return { 'error' => "unknown custnum $custnum" };
1280 if ( $p->{'amount'} ) {
1281 $amount = $p->{'amount'};
1283 elsif ( $session->{'pkgnum'} ) {
1284 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1287 $amount = $cust_main->balance;
1290 my $error = $cust_main->realtime_collect(
1291 'method' => $p->{'method'},
1292 'amount' => $amount,
1293 'pkgnum' => $session->{'pkgnum'},
1294 'session_id' => $p->{'session_id'},
1298 return { 'error' => $error } unless ref( $error );
1300 return { 'error' => '', amount => $amount, %$error };
1303 sub start_thirdparty {
1305 my $session = _cache->get($p->{'session_id'})
1306 or return { 'error' => "Can't resume session" }; #better error message
1307 my $custnum = $session->{'custnum'};
1308 my $cust_main = FS::cust_main->by_key($custnum);
1310 my $amount = $p->{'amount'}
1311 or return { error => 'no amount' };
1313 my $result = $cust_main->create_payment(
1314 'method' => $p->{'method'},
1315 'amount' => $p->{'amount'},
1316 'pkgnum' => $session->{'pkgnum'},
1317 'session_id' => $p->{'session_id'},
1320 if ( ref($result) ) { # hashref or error
1323 return { error => $result };
1327 sub finish_thirdparty {
1329 my $session_id = delete $p->{'session_id'};
1330 my $session = _cache->get($session_id)
1331 or return { 'error' => "Can't resume session" };
1332 my $custnum = $session->{'custnum'};
1333 my $cust_main = FS::cust_main->by_key($custnum);
1335 if ( $p->{_cancel} ) {
1336 # customer backed out of making a payment
1337 return $cust_main->cancel_payment( $session_id );
1339 my $result = $cust_main->execute_payment( $session_id, %$p );
1340 if ( ref($result) ) {
1343 return { error => $result };
1347 sub process_payment_order_pkg {
1350 my $hr = process_payment($p);
1351 return $hr if $hr->{'error'};
1356 sub process_payment_order_renew {
1359 my $hr = process_payment($p);
1360 return $hr if $hr->{'error'};
1365 sub process_prepay {
1369 my $session = _cache->get($p->{'session_id'})
1370 or return { 'error' => "Can't resume session" }; #better error message
1374 my $custnum = $session->{'custnum'};
1376 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1377 or return { 'error' => "unknown custnum $custnum" };
1379 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1380 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1388 return { 'error' => $error } if $error;
1390 return { 'error' => '',
1391 'amount' => $amount,
1392 'seconds' => $seconds,
1393 'duration' => duration_exact($seconds),
1394 'upbytes' => $upbytes,
1395 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1396 'downbytes' => $downbytes,
1397 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1398 'totalbytes'=> $totalbytes,
1399 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1406 my $session = _cache->get($p->{'session_id'})
1407 or return { 'error' => "Can't resume session" }; #better error message
1409 my $custnum = $session->{'custnum'};
1411 my $invnum = $p->{'invnum'};
1413 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1414 'custnum' => $custnum } )
1415 or return { 'error' => "Can't find invnum" };
1419 return { 'error' => '',
1420 'invnum' => $invnum,
1421 'invoice_text' => join('', $cust_bill->print_text ),
1422 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1429 my $session = _cache->get($p->{'session_id'})
1430 or return { 'error' => "Can't resume session" }; #better error message
1432 my $custnum = $session->{'custnum'};
1434 my $invnum = $p->{'invnum'};
1436 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1437 'custnum' => $custnum } )
1438 or return { 'error' => "Can't find invnum" };
1442 return { 'error' => '',
1443 'invnum' => $invnum,
1444 'invoice_pdf' => $cust_bill->print_pdf({
1445 'unsquelch_cdr' => 1,
1446 'locale' => $p->{'locale'},
1452 sub legacy_invoice {
1454 my $session = _cache->get($p->{'session_id'})
1455 or return { 'error' => "Can't resume session" }; #better error message
1457 my $custnum = $session->{'custnum'};
1459 my $legacyinvnum = $p->{'legacyinvnum'};
1462 'legacyinvnum' => $legacyinvnum,
1463 'custnum' => $custnum,
1466 my $legacy_cust_bill =
1467 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1468 || qsearchs('legacy_cust_bill', \%hash )
1469 or return { 'error' => "Can't find legacyinvnum" };
1473 return { 'error' => '',
1474 'legacyinvnum' => $legacyinvnum,
1475 'legacyid' => $legacy_cust_bill->legacyid,
1476 'invoice_html' => $legacy_cust_bill->content_html,
1481 sub legacy_invoice_pdf {
1483 my $session = _cache->get($p->{'session_id'})
1484 or return { 'error' => "Can't resume session" }; #better error message
1486 my $custnum = $session->{'custnum'};
1488 my $legacyinvnum = $p->{'legacyinvnum'};
1490 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1491 'legacyinvnum' => $legacyinvnum,
1492 'custnum' => $custnum,
1493 }) or return { 'error' => "Can't find legacyinvnum" };
1497 return { 'error' => '',
1498 'legacyinvnum' => $legacyinvnum,
1499 'legacyid' => $legacy_cust_bill->legacyid,
1500 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1508 #sessioning for this? how do we get the session id to the backend invoice
1509 # template so it can add it to the link, blah
1512 if ( $p->{'invnum'} ) {
1513 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1514 or return { 'error' => 'unknown invnum' };
1515 $agentnum = $cust_bill->cust_main->agentnum;
1518 my $templatename = $p->{'template'} || $p->{'templatename'};
1520 #false laziness-ish w/view/cust_bill-logo.cgi
1522 my $conf = new FS::Conf;
1523 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1524 $templatename = "_$1";
1529 my $filename = "logo$templatename.png";
1531 return { 'error' => '',
1532 'logo' => $conf->config_binary($filename, $agentnum),
1533 'content_type' => 'image/png', #should allow gif, jpg too
1540 my $session = _cache->get($p->{'session_id'})
1541 or return { 'error' => "Can't resume session" }; #better error message
1543 my $custnum = $session->{'custnum'};
1545 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1546 or return { 'error' => "unknown custnum $custnum" };
1548 my $conf = new FS::Conf;
1550 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1552 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1556 return { 'error' => '',
1557 'balance' => $cust_main->balance,
1560 my $owed = $_->owed;
1562 +{ 'invnum' => $_->invnum,
1563 '_date' => $_->_date,
1564 'date' => time2str("%b %o, %Y", $_->_date),
1565 'date_short' => time2str("%m-%d-%Y", $_->_date),
1566 'previous' => sprintf('%.2f', ($_->previous)[0]),
1567 'charged' => sprintf('%.2f', $_->charged),
1568 'owed' => sprintf('%.2f', $owed),
1569 'balance' => sprintf('%.2f', $balance),
1574 'legacy_invoices' => [
1576 +{ 'legacyinvnum' => $_->legacyinvnum,
1577 'legacyid' => $_->legacyid,
1578 '_date' => $_->_date,
1579 'date' => time2str("%b %o, %Y", $_->_date),
1580 'date_short' => time2str("%m-%d-%Y", $_->_date),
1581 'charged' => sprintf('%.2f', $_->charged),
1582 'has_content' => ( length($_->content_pdf)
1583 || length($_->content_html) ),
1593 my $session = _cache->get($p->{'session_id'})
1594 or return { 'error' => "Can't resume session" }; #better error message
1596 my $custnum = $session->{'custnum'};
1598 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1599 or return { 'error' => "unknown custnum $custnum" };
1601 my @errors = $cust_main->cancel( 'quiet'=>1 );
1603 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1605 return { 'error' => $error };
1612 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1613 return { 'error' => $session } if $context eq 'error';
1615 my $search = { 'custnum' => $custnum };
1616 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1617 my $cust_main = qsearchs('cust_main', $search )
1618 or return { 'error' => "unknown custnum $custnum" };
1620 my $conf = new FS::Conf;
1621 my $immutable = $conf->exists('selfservice_immutable-package');
1623 # the duplication below is necessary:
1624 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1625 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1626 # non-backwards-compatible change breaking the software of anyone using the API
1627 # instead of the stock selfservice
1628 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1629 if( $conf->exists('selfservice_server-view-wholesale') ) {
1630 return { 'svcnum' => $session->{'svcnum'},
1631 'custnum' => $custnum,
1632 'cust_pkg' => [ map {
1634 immutable => $immutable,
1635 part_pkg => [ map $_->hashref, $_->part_pkg ],
1637 [ map $_->hashref, $_->available_part_svc ],
1639 [ map { my $ref = { $_->hash,
1640 label => [ $_->label ],
1642 $ref->{_password} = $_->svc_x->_password
1643 if $context eq 'agent'
1644 && $conf->exists('agent-showpasswords')
1645 && $_->part_svc->svcdb eq 'svc_acct';
1650 } $cust_main->cust_pkg
1653 small_custview( $cust_main, $conf->config('countrydefault') ),
1654 'wholesale_view' => 1,
1655 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1656 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1657 'lnp' => $conf->exists('svc_phone-lnp'),
1661 { 'svcnum' => $session->{'svcnum'},
1662 'custnum' => $custnum,
1663 'cust_pkg' => [ map {
1664 my $primary_cust_svc = $_->primary_cust_svc;
1667 immutable => $immutable,
1668 pkg_label => $_->pkg_locale,
1669 status => $_->status,
1670 statuscolor => $_->statuscolor,
1672 [ map { $_->hashref }
1673 grep { $_->selfservice_access ne 'hidden' }
1674 $_->available_part_svc
1677 [ map { my $ref = { $_->hash,
1678 label => [ $_->label ],
1680 $ref->{_password} = $_->svc_x->_password
1681 if $context eq 'agent'
1682 && $conf->exists('agent-showpasswords')
1683 && $_->part_svc->svcdb eq 'svc_acct';
1684 $ref->{svchash} = { $_->svc_x->hash } if
1685 $_->part_svc->svcdb eq 'svc_phone';
1686 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1687 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1690 grep { $_->part_svc->selfservice_access ne 'hidden' }
1695 ? { $primary_cust_svc->hash,
1696 label => [ $primary_cust_svc->label ],
1697 finger => $primary_cust_svc->svc_x->finger, #uuh
1698 $primary_cust_svc->part_svc->hash,
1702 } $cust_main->ncancelled_pkgs
1705 small_custview( $cust_main, $conf->config('countrydefault') ),
1706 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1714 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1715 return { 'error' => $session } if $context eq 'error';
1717 my $conf = new FS::Conf;
1719 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1720 my $search = { 'custnum' => $custnum };
1721 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1722 my $cust_main = qsearchs('cust_main', $search )
1723 or return { 'error' => "unknown custnum $custnum" };
1725 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1726 if ( ! $pkgnum && $p->{'svcnum'} ) {
1727 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1728 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1732 my @cust_pkg_usage = ();
1733 foreach my $cust_pkg ( $p->{'ncancelled'}
1734 ? $cust_main->ncancelled_pkgs
1735 : $cust_main->unsuspended_pkgs ) {
1736 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1737 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1738 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1741 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1744 foreach (@cust_pkg_usage) {
1745 my $part = $_->part_pkg_usage;
1746 my $tag = $part->description . ($part->shared ? 1 : 0);
1747 my $row = $usage_pools{$tag}
1748 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1749 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1750 $row->[2] += $part->minutes; # minutes total
1752 } # otherwise just leave them empty
1754 if ( $p->{'svcdb'} ) {
1755 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1757 : ref($p->{'svcdb'}) eq 'ARRAY'
1758 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1759 : { $p->{'svcdb'} => 1 };
1760 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1763 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1766 my @svcs; # stuff to return to the client
1767 foreach my $cust_svc (@cust_svc) {
1768 my $svc_x = $cust_svc->svc_x;
1769 my($label, $value) = $cust_svc->label;
1770 my $part_svc = $cust_svc->part_svc;
1771 my $svcdb = $part_svc->svcdb;
1772 my $cust_pkg = $cust_svc->cust_pkg;
1773 my $part_pkg = $cust_pkg->part_pkg;
1776 'svcnum' => $cust_svc->svcnum,
1777 'display_svcnum' => $cust_svc->display_svcnum,
1781 'pkg_label' => $cust_pkg->pkg_locale,
1782 'pkg_status' => $cust_pkg->status,
1783 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1786 # would it make sense to put this in a svc_* method?
1788 if ( $svcdb eq 'svc_acct' ) {
1789 foreach (qw(username email finger seconds)) {
1790 $hash{$_} = $svc_x->$_;
1796 'upbytes' => display_bytecount($svc_x->upbytes),
1797 'downbytes' => display_bytecount($svc_x->downbytes),
1798 'totalbytes' => display_bytecount($svc_x->totalbytes),
1800 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1801 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1802 'recharge_upbytes' =>
1803 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1804 'recharge_downbytes' =>
1805 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1806 'recharge_totalbytes' =>
1807 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1812 } elsif ( $svcdb eq 'svc_dsl' ) {
1814 $hash{'phonenum'} = $svc_x->phonenum;
1815 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1816 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1817 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1820 $hash{'name'} = $cust_main->name;
1822 # no usage to hide here
1824 } elsif ( $svcdb eq 'svc_phone' ) {
1826 # could potentially show lots of things...
1827 $hash{'outbound'} = 1;
1828 $hash{'inbound'} = 0;
1829 if ( $part_pkg->plan eq 'voip_inbound' ) {
1830 $hash{'outbound'} = 0;
1831 $hash{'inbound'} = 1;
1832 } elsif ( $part_pkg->option('selfservice_inbound_format')
1833 or $conf->config('selfservice-default_inbound_cdr_format')
1835 $hash{'inbound'} = 1;
1837 foreach (qw(inbound outbound)) {
1838 # hmm...we can't filter by status here, because there might
1839 # not be cdr_terminations at all. have to go by date.
1840 # find all since the last bill date.
1841 # XXX cdr types? we are going to need them.
1843 my $sum_cdr = $svc_x->sum_cdrs(
1844 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1845 'begin' => ($cust_pkg->last_bill || 0),
1847 'disable_charged_party' => 1,
1849 $hash{$_} = $sum_cdr->hashref;
1852 } # not hiding usage
1856 } # foreach $cust_svc
1859 'svcnum' => $session->{'svcnum'},
1860 'custnum' => $custnum,
1861 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1862 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1865 map { $usage_pools{$_} }
1869 'hide_usage' => $hide_usage,
1874 sub _customer_svc_x {
1875 my($custnum, $svcnum, $table) = (shift, shift, shift);
1876 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1878 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1879 my $search = " AND custnum = $1";
1880 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1883 'table' => ($table || 'svc_acct'),
1884 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1885 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1886 #'LEFT JOIN cust_main USING ( custnum ) ',
1887 'hashref' => $hashref,
1888 'extra_sql' => $search, #important
1893 sub svc_status_html {
1896 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1897 return { 'error' => $session } if $context eq 'error';
1899 #XXX only svc_dsl for now
1900 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1901 or return { 'error' => "Service not found" };
1903 my $html = $svc_x->getstatus_html;
1905 return { 'html' => $html };
1909 sub svc_status_hash {
1912 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1913 return { 'error' => $session } if $context eq 'error';
1915 #XXX only svc_acct for now
1916 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1917 or return { 'error' => "Service not found" };
1919 my ( $html, $hashref ) = $svc_x->export_getstatus;
1924 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1925 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1926 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1927 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1928 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1931 my( $p, $method ) = @_;
1933 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1934 return { 'error' => $session } if $context eq 'error';
1936 #XXX only svc_acct for now
1937 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1938 or return { 'error' => "Service not found" };
1940 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1942 my $error = $svc_x->$method($p); #$p? returns error?
1943 return { 'error' => $error } if $error;
1945 return {}; #? { 'error' => '' }
1949 sub acct_forward_info {
1952 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1953 return { 'error' => $session } if $context eq 'error';
1955 my $svc_forward = _customer_svc_x( $custnum,
1956 { 'srcsvc' => $p->{'svcnum'} },
1959 or return { 'error' => '',
1963 return { 'error' => '',
1964 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1969 sub process_acct_forward {
1971 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1972 return { 'error' => $session } if $context eq 'error';
1974 my $old = _customer_svc_x( $custnum,
1975 { 'srcsvc' => $p->{'svcnum'} },
1979 if ( $p->{'dst'} eq '' ) {
1981 my $error = $old->delete;
1982 return { 'error' => $error };
1984 return { 'error' => '' };
1987 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1988 'dst' => $p->{'dst'},
1993 $new->svcnum($old->svcnum);
1994 my $cust_svc = $old->cust_svc;
1995 $new->svcpart($old->svcpart);
1996 $new->pkgnuym($old->pkgnum);
1997 $error = $new->replace($old);
1999 my $conf = new FS::Conf;
2000 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2002 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2003 or return { 'error' => 'No service' }; #how would we even get here?
2005 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2007 $error = $new->insert;
2010 return { 'error' => $error };
2014 sub list_dsl_devices {
2017 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2018 return { 'error' => $session } if $context eq 'error';
2020 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2021 or return { 'error' => "Service not found" };
2024 'devices' => [ map {
2025 +{ 'mac_addr' => $_->mac_addr };
2026 } $svc_dsl->dsl_device
2032 sub add_dsl_device {
2035 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2036 return { 'error' => $session } if $context eq 'error';
2038 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2039 or return { 'error' => "Service not found" };
2041 return { 'error' => 'No MAC address supplied' }
2042 unless length($p->{'mac_addr'});
2044 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2045 'mac_addr' => scalar($p->{'mac_addr'}),
2047 my $error = $dsl_device->insert;
2048 return { 'error' => $error };
2052 sub delete_dsl_device {
2055 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2056 return { 'error' => $session } if $context eq 'error';
2058 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2059 or return { 'error' => "Service not found" };
2061 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2062 'mac_addr' => scalar($p->{'mac_addr'}),
2065 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2067 my $error = $dsl_device->delete;
2068 return { 'error' => $error };
2074 _usage_details( \&_port_graph, $p,
2075 'svcdb' => 'svc_port',
2080 my($svc_port, $begin, $end) = @_;
2082 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2083 push @usage, { 'png' => $pngOrError };
2087 sub _list_svc_usage {
2088 my($svc_acct, $begin, $end) = @_;
2090 foreach my $part_export (
2091 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2092 qw( sqlradius sqlradius_withdomain )
2094 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2099 sub list_svc_usage {
2100 _usage_details(\&_list_svc_usage, @_);
2103 sub _list_support_usage {
2104 my($svc_acct, $begin, $end) = @_;
2106 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2107 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2109 push @usage, { 'seconds' => $_->seconds,
2110 'support' => $_->support,
2111 '_date' => $_->_date,
2112 'id' => $_->transaction_id,
2113 'creator' => $_->creator,
2114 'subject' => $_->subject,
2115 'status' => $_->status,
2116 'ticketid' => $_->ticketid,
2122 sub list_support_usage {
2123 _usage_details(\&_list_support_usage, @_);
2126 sub _list_cdr_usage {
2127 # XXX CDR type support...
2128 # XXX any way to do a paged search on this?
2129 # we have to return the results all at once...
2130 my($svc_phone, $begin, $end, %opt) = @_;
2131 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2132 $svc_phone->get_cdrs(
2135 'disable_charged_party' => 1,
2140 sub list_cdr_usage {
2142 _usage_details( \&_list_cdr_usage, $p,
2143 'svcdb' => 'svc_phone',
2147 sub _usage_details {
2148 my($callback, $p, %opt) = @_;
2149 my $conf = FS::Conf->new;
2151 if ( $conf->exists('selfservice_hide-usage') ) {
2152 return { 'error' => 'Viewing usage is not allowed.' };
2155 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2156 return { 'error' => $session } if $context eq 'error';
2158 my $search = { 'svcnum' => $p->{'svcnum'} };
2159 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2161 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2163 my $svc_x = qsearchs( $svcdb, $search );
2164 return { 'error' => 'No service selected in list_svc_usage' }
2167 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2168 my $freq = $cust_pkg->part_pkg->freq;
2171 if ( $svcdb eq 'svc_phone' ) {
2173 if ( $p->{inbound} ) {
2174 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2175 || $conf->config('selfservice-default_inbound_cdr_format')
2176 || 'source_default';
2177 $callback_opt{inbound} = 1;
2179 $format = $cust_pkg->part_pkg->option('selfservice_format')
2180 || $conf->config('selfservice-default_cdr_format')
2184 $callback_opt{format} = $format;
2185 $callback_opt{use_clid} = 1;
2186 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2189 my $start = $cust_pkg->setup;
2190 #my $end = $cust_pkg->bill; # or time?
2193 unless ( $p->{beginning} ) {
2194 $p->{beginning} = $cust_pkg->last_bill;
2195 $p->{ending} = $end;
2198 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2199 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2201 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2205 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2206 # ugly kludge, I know
2207 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2208 if (defined $delete_col) {
2209 delete($_->[$delete_col]) foreach ($header, @usage);
2213 #kinda false laziness with FS::cust_main::bill, but perhaps
2214 #we should really change this bit to DateTime and DateTime::Duration
2216 #change this bit to use Date::Manip? CAREFUL with timezones (see
2217 # mailing list archive)
2218 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2219 (localtime($p->{ending}) )[0,1,2,3,4,5];
2220 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2221 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2223 if ( $freq =~ /^\d+$/ ) {
2225 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2227 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2228 } elsif ( $freq =~ /^(\d+)w$/ ) {
2230 $nmday += $weeks * 7;
2231 $pmday -= $weeks * 7;
2232 } elsif ( $freq =~ /^(\d+)d$/ ) {
2236 } elsif ( $freq =~ /^(\d+)h$/ ) {
2241 return { 'error' => "unparsable frequency: ". $freq };
2244 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2245 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2249 'svcnum' => $p->{svcnum},
2250 'beginning' => $p->{beginning},
2251 'ending' => $p->{ending},
2252 'inbound' => $p->{inbound},
2253 'previous' => ($previous > $start) ? $previous : $start,
2254 'next' => ($next < $end) ? $next : $end,
2255 'header' => $header,
2263 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2264 return { 'error' => $session } if $context eq 'error';
2266 my $search = { 'custnum' => $custnum };
2267 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2268 my $cust_main = qsearchs('cust_main', $search )
2269 or return { 'error' => "unknown custnum $custnum" };
2271 my $status = $cust_main->status;
2273 my %order_pkg_options = ();
2274 if ( $p->{locationnum} > 0 ) {
2275 $order_pkg_options{locationnum} = delete($p->{locationnum});
2276 } elsif ( $p->{address1} ) {
2277 $order_pkg_options{'cust_location'} = new FS::cust_location {
2278 map { $_ => $p->{$_} }
2279 qw( address1 address2 city county state zip country )
2283 #false laziness w/ClientAPI/Signup.pm
2285 my $cust_pkg = new FS::cust_pkg ( {
2286 'custnum' => $custnum,
2287 'pkgpart' => $p->{'pkgpart'},
2288 'quantity' => $p->{'quantity'} || 1,
2290 my $error = $cust_pkg->check;
2291 return { 'error' => $error } if $error;
2294 unless ( $p->{'svcpart'} eq 'none' ) {
2298 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2300 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2301 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2302 $svcdb = $part_svc->svcdb;
2304 $svcdb = 'svc_acct';
2306 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2309 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2310 'svc_domain' => [ qw( domain ) ],
2311 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2312 'svc_external' => [ qw( id title ) ],
2313 'svc_pbx' => [ qw( id title ) ],
2316 my $svc_x = "FS::$svcdb"->new( {
2317 'svcpart' => $svcpart,
2318 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2321 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2324 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2325 my $acct_snarf = new FS::acct_snarf ( {
2326 'machine' => $p->{"snarf_machine$snarfnum"},
2327 'protocol' => $p->{"snarf_protocol$snarfnum"},
2328 'username' => $p->{"snarf_username$snarfnum"},
2329 '_password' => $p->{"snarf_password$snarfnum"},
2332 push @acct_snarf, $acct_snarf;
2334 $svc_x->child_objects( \@acct_snarf );
2337 my $y = $svc_x->setdefault; # arguably should be in new method
2338 return { 'error' => $y } if $y && !ref($y);
2340 $error = $svc_x->check;
2341 return { 'error' => $error } if $error;
2347 $error = $cust_main->order_pkg(
2348 'cust_pkg' => $cust_pkg,
2353 return { 'error' => $error } if $error;
2355 my $conf = new FS::Conf;
2356 if ( $conf->exists('signup_server-realtime') ) {
2358 my $bill_error = _do_bop_realtime( $cust_main, $status );
2361 $cust_pkg->cancel('quiet'=>1);
2364 $cust_pkg->reexport;
2368 $cust_pkg->reexport;
2371 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2373 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2380 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2381 return { 'error' => $session } if $context eq 'error';
2383 my $conf = new FS::Conf;
2384 my $immutable = $conf->exists('selfservice_immutable-package');
2385 return { 'error' => "Package modification disabled" } if $immutable;
2387 my $search = { 'custnum' => $custnum };
2388 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2389 my $cust_main = qsearchs('cust_main', $search )
2390 or return { 'error' => "unknown custnum $custnum" };
2392 my $status = $cust_main->status;
2393 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2394 or return { 'error' => "unknown package $p->{pkgnum}" };
2396 #if someone does need self-service package change of suspended packages,
2397 # figure out how to be more discriminating
2398 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2399 if $cust_pkg->status eq 'suspended';
2401 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2402 'quantity' => $p->{'quantity'} || 1,
2405 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2406 unless ref($err_or_cust_pkg);
2408 if ( $conf->exists('signup_server-realtime') ) {
2410 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2413 $err_or_cust_pkg->suspend;
2416 $err_or_cust_pkg->reexport;
2420 $err_or_cust_pkg->reexport;
2423 return { error => '', pkgnum => $cust_pkg->pkgnum };
2427 sub order_recharge {
2430 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2431 return { 'error' => $session } if $context eq 'error';
2433 my $search = { 'custnum' => $custnum };
2434 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2435 my $cust_main = qsearchs('cust_main', $search )
2436 or return { 'error' => "unknown custnum $custnum" };
2438 my $status = $cust_main->status;
2439 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2440 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2442 my $svc_x = $cust_svc->svc_x;
2443 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2446 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2447 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2448 recharge_totalbytes );
2449 my $amount = $part_pkg->option('recharge_amount', 1);
2451 my ($l, $v, $d) = $cust_svc->label; # blah
2452 my $pkg = "Recharge $v";
2454 my $bill_error = $cust_main->charge($amount, $pkg,
2455 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2456 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2457 $part_pkg->taxclass); #meh
2459 my $conf = new FS::Conf;
2460 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2462 $bill_error = _do_bop_realtime( $cust_main, $status );
2467 my $error = $svc_x->recharge (\%vhash);
2468 return { 'error' => $error } if $error;
2472 my $error = $bill_error;
2473 $error ||= $svc_x->recharge (\%vhash);
2474 return { 'error' => $error } if $error;
2477 return { error => '', svc => $cust_svc->part_svc->svc };
2481 sub _do_bop_realtime {
2482 my ($cust_main, $status, %opt) = @_;
2484 my $old_balance = $cust_main->balance;
2486 my $bill_error = $cust_main->bill
2487 || $cust_main->apply_payments_and_credits;
2489 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2490 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2492 if ( $cust_main->balance > $old_balance
2493 && $cust_main->balance > 0
2494 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2495 || $status eq 'suspended'
2499 unless ( $opt{'no_credit'} ) {
2500 #this makes sense. credit is "un-doing" the invoice
2501 my $conf = new FS::Conf;
2502 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2503 'self-service decline',
2504 reason_type=>$conf->config('signup_credit_type'),
2506 $cust_main->apply_credits( 'order' => 'newest' );
2509 return { 'error' => '_decline', 'bill_error' => $bill_error };
2518 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2519 return { 'error' => $session } if $context eq 'error';
2521 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2522 or return { 'error' => "unknown custnum $custnum" };
2524 my @cust_pkg = sort { $a->bill <=> $b->bill }
2525 grep { $_->part_pkg->freq ne '0' }
2526 $cust_main->ncancelled_pkgs;
2528 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2530 my $total = $cust_main->balance;
2533 my $bill = $_->bill;
2534 $total += $_->part_pkg->base_recur($_, \$bill);
2535 my $renew_date = $_->part_pkg->add_freq($_->bill);
2537 'pkgnum' => $_->pkgnum,
2538 'amount' => sprintf('%.2f', $total),
2539 'bill_date' => $_->bill,
2540 'bill_date_pretty' => time2str('%x', $_->bill),
2541 'renew_date' => $renew_date,
2542 'renew_date_pretty' => time2str('%x', $renew_date),
2543 'expire_date' => $_->expire,
2544 'expire_date_pretty' => time2str('%x', $_->expire),
2549 return { 'dates' => \@array };
2553 sub payment_info_renew_info {
2555 my $renew_info = renew_info($p);
2556 my $payment_info = payment_info($p);
2557 return { %$renew_info,
2565 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2566 return { 'error' => $session } if $context eq 'error';
2568 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2569 or return { 'error' => "unknown custnum $custnum" };
2571 my $date = $p->{'date'};
2575 #freeside-daily -n -d $date fs_daily $custnum
2576 $cust_main->bill_and_collect( 'time' => $date,
2577 'invoice_time' => $now,
2578 'actual_time' => $now,
2579 'check_freq' => '1d',
2582 return { 'error' => '' };
2588 my $session = _cache->get($p->{'session_id'})
2589 or return { 'error' => "Can't resume session" }; #better error message
2591 my $custnum = $session->{'custnum'};
2593 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2594 or return { 'error' => "unknown custnum $custnum" };
2596 my $conf = new FS::Conf;
2598 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2599 or return { 'error' => 'Permission denied' };
2601 my $pkgnum = $p->{'pkgnum'};
2603 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2604 'pkgnum' => $pkgnum, } )
2605 or return { 'error' => "unknown pkgnum $pkgnum" };
2607 my $error = $cust_pkg->suspend(reason => $reasonnum);
2608 return { 'error' => $error };
2614 my $session = _cache->get($p->{'session_id'})
2615 or return { 'error' => "Can't resume session" }; #better error message
2617 my $custnum = $session->{'custnum'};
2619 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2620 or return { 'error' => "unknown custnum $custnum" };
2622 my $pkgnum = $p->{'pkgnum'};
2624 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2625 'pkgnum' => $pkgnum, } )
2626 or return { 'error' => "unknown pkgnum $pkgnum" };
2628 my $error = $cust_pkg->cancel('quiet' => 1);
2629 return { 'error' => $error };
2633 sub provision_phone {
2636 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2638 #editing an existing phone number
2639 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2640 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2641 return { 'error' => $session } if $context eq 'error';
2643 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2644 return { 'error' => 'service not found' } unless $svc_phone;
2645 return { 'error' => 'invalid svcnum' }
2646 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2648 $svc_phone->email($p->{'email'})
2649 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2650 $svc_phone->forwarddst($p->{'forwarddst'})
2651 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2652 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2653 return { 'error' => $svc_phone->replace };
2657 unless ( $p->{'lnp'} ) {
2658 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2659 $p->{'lnp_status'} = "portingin";
2660 return _provision( 'FS::svc_phone',
2661 [qw(lnp_desired_due_date lnp_other_provider
2662 lnp_other_provider_account phonenum countrycode lnp_status)],
2663 [qw(phonenum countrycode)],
2669 # single DID order (the usual case)
2670 unless (scalar(@bulkdid)) {
2671 return _provision( 'FS::svc_phone',
2672 [qw(phonenum countrycode)],
2673 [qw(phonenum countrycode)],
2679 # bulk DID order case
2681 foreach my $did ( @bulkdid ) {
2682 $did =~ s/[^0-9]//g;
2683 $error = _provision( 'FS::svc_phone',
2684 [qw(phonenum countrycode)],
2685 [qw(phonenum countrycode)],
2687 'pkgnum' => $p->{'pkgnum'},
2688 'svcpart' => $p->{'svcpart'},
2690 'countrycode' => $p->{'countrycode'},
2691 'session_id' => $p->{'session_id'},
2694 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2696 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2699 sub provision_acct {
2701 warn "provision_acct called\n"
2704 return { 'error' => gettext('passwords_dont_match') }
2705 if $p->{'_password'} ne $p->{'_password2'};
2706 return { 'error' => gettext('empty_password') }
2707 unless length($p->{'_password'});
2709 if ($p->{'domsvc'}) {
2710 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2711 qw ( svcpart pkgnum ) );
2712 return { 'error' => gettext('invalid_domain') }
2713 unless ($domains{$p->{'domsvc'}});
2716 warn "provision_acct calling _provision\n"
2718 _provision( 'FS::svc_acct',
2719 [qw(username _password domsvc)],
2720 [qw(username _password domsvc)],
2726 sub provision_external {
2728 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2729 _provision( 'FS::svc_external',
2738 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2739 warn "_provision called for $class\n"
2742 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2743 return { 'error' => $session } if $context eq 'error';
2745 my $search = { 'custnum' => $custnum };
2746 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2747 my $cust_main = qsearchs('cust_main', $search )
2748 or return { 'error' => "unknown custnum $custnum" };
2750 my $pkgnum = $p->{'pkgnum'};
2752 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2754 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2755 'pkgnum' => $pkgnum,
2757 or return { 'error' => "unknown pkgnum $pkgnum" };
2759 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2761 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2762 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2764 warn "creating $class record\n"
2766 my $svc_x = $class->new( {
2767 'pkgnum' => $p->{'pkgnum'},
2768 'svcpart' => $p->{'svcpart'},
2769 map { $_ => $p->{$_} } @$fields
2772 my %insert_args = ();
2773 #i shouldn't be a special case here (pass an option or something)
2774 if ( $class eq 'FS::svc_phone'
2775 && grep length($p->{$_}), @location_editable_fields
2778 $insert_args{'cust_location'} = new FS::cust_location {
2779 map { $_ => $p->{$_} } @location_editable_fields
2783 warn "inserting $class record\n"
2785 my $error = $svc_x->insert(%insert_args);
2788 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2790 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2793 my $return = { 'svc' => $part_svc->svc,
2795 map { $_ => $svc_x->get($_) } @$return_fields
2797 warn "_provision returning ". Dumper($return). "\n"
2806 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2807 return { 'error' => $session } if $context eq 'error';
2809 my $search = { 'custnum' => $custnum };
2810 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2811 my $cust_main = qsearchs('cust_main', $search )
2812 or return { 'error' => "unknown custnum $custnum" };
2814 my $pkgnum = $p->{'pkgnum'};
2816 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2817 'pkgnum' => $pkgnum,
2819 or return { 'error' => "unknown pkgnum $pkgnum" };
2821 my $svcpart = $p->{'svcpart'};
2823 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2824 'svcpart' => $svcpart, } )
2825 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2826 my $part_svc = $pkg_svc->part_svc;
2828 my $conf = new FS::Conf;
2831 'svc' => $part_svc->svc,
2832 'svcdb' => $part_svc->svcdb,
2833 'pkgnum' => $pkgnum,
2834 'svcpart' => $svcpart,
2835 'custnum' => $custnum,
2837 'security_phrase' => 0, #XXX !
2838 'svc_acct_pop' => [], #XXX !
2840 'init_popstate' => '',
2845 small_custview( $cust_main, $conf->config('countrydefault') ),
2849 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2850 && $ret->{'svcdb'} eq 'svc_phone') {
2851 $ret->{'svcnum'} = $p->{'svcnum'};
2852 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2853 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2854 $ret->{'email'} = $svc_phone->email;
2855 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2862 sub unprovision_svc {
2865 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2866 return { 'error' => $session } if $context eq 'error';
2868 my $search = { 'custnum' => $custnum };
2869 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2870 my $cust_main = qsearchs('cust_main', $search )
2871 or return { 'error' => "unknown custnum $custnum" };
2873 my $svcnum = $p->{'svcnum'};
2875 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2876 or return { 'error' => "unknown svcnum $svcnum" };
2878 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2879 unless $cust_svc->cust_pkg->custnum == $custnum;
2881 my $conf = new FS::Conf;
2883 return { 'svc' => $cust_svc->part_svc->svc,
2884 'error' => $cust_svc->cancel,
2886 small_custview( $cust_main, $conf->config('countrydefault') ),
2891 sub myaccount_passwd {
2893 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2894 return { 'error' => $session } if $context eq 'error';
2896 return { 'error' => "New passwords don't match." }
2897 if $p->{'new_password'} ne $p->{'new_password2'};
2899 return { 'error' => 'Enter new password' }
2900 unless length($p->{'new_password'});
2902 #my $search = { 'custnum' => $custnum };
2903 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2904 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2905 my $search = " AND custnum = $1";
2906 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2908 my $svc_acct = qsearchs( {
2909 'table' => 'svc_acct',
2910 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2911 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2912 'LEFT JOIN cust_main USING ( custnum ) ',
2913 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2914 'extra_sql' => $search, #important
2916 or return { 'error' => "Service not found" };
2920 my $conf = new FS::Conf;
2922 return { 'error' => 'Incorrect current password.' }
2923 if ( exists($p->{'old_password'})
2924 || $conf->exists('selfservice-password_change_oldpass')
2926 && ! $svc_acct->check_password($p->{'old_password'});
2928 $error = 'Password too short.'
2929 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2930 $error = 'Password too long.'
2931 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2933 $svc_acct->set_password($p->{'new_password'});
2934 $error ||= $svc_acct->replace();
2936 #regular pw change in self-service should change contact pw too, otherwise its
2937 #way too confusing. hell its confusing they're separate at all, but alas.
2938 #need to support the "ISP provides email that's used as a contact email" case
2940 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2941 if ( $contact && $contact->custnum == $custnum ) {
2942 #svc_acct was successful but this one returns an error? "shouldn't happen"
2943 $error ||= $contact->change_password($p->{'new_password'});
2946 my($label, $value) = $svc_acct->cust_svc->label;
2948 return { 'error' => $error,
2955 # sub contact_passwd {
2957 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2958 # return { 'error' => $session } if $context eq 'error';
2960 # return { 'error' => 'Not logged in as a contact.' }
2961 # unless $session->{'contactnum'};
2963 # return { 'error' => "New passwords don't match." }
2964 # if $p->{'new_password'} ne $p->{'new_password2'};
2966 # return { 'error' => 'Enter new password' }
2967 # unless length($p->{'new_password'});
2969 # #my $search = { 'custnum' => $custnum };
2970 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2971 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2972 # my $search = " AND selfservice_access IS NOT NULL ".
2973 # " AND selfservice_access = 'Y' ".
2974 # " AND ( disabled IS NULL OR disabled = '' )".
2975 # " AND custnum IS NOT NULL AND custnum = $1";
2976 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2978 # my $contact = qsearchs( {
2979 # 'table' => 'contact',
2980 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2981 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2982 # 'extra_sql' => $search, #important
2984 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2985 # # deleted since then?
2989 # # use these svc_acct length restrictions??
2990 # my $conf = new FS::Conf;
2991 # $error = 'Password too short.'
2992 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2993 # $error = 'Password too long.'
2994 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2996 # $error ||= $contact->change_password($p->{'new_password'});
2998 # return { 'error' => $error, };
3005 my $info = skin_info($p);
3007 my $conf = new FS::Conf;
3008 my $verification = $conf->config('selfservice-password_reset_verification')
3009 or return { %$info, 'error' => 'Password resets disabled' };
3014 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3016 $contact = FS::contact->by_selfservice_email($p->{'email'});
3018 $cust_main = $contact->cust_main if $contact;
3020 #also look for an svc_acct, otherwise it would be super confusing
3022 my($username, $domain) = split('@', $p->{'email'});
3023 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3024 if ( $svc_domain ) {
3025 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3026 'domsvc' => $svc_domain->svcnum }
3029 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3030 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3032 #precaution: don't change svc_acct password not part of the same
3033 # customer as contact
3034 $svc_acct = '' if ! $cust_pkg
3035 || $cust_pkg->custnum != $cust_main->custnum;
3040 return { %$info, 'error' => 'Email address not found' }
3041 unless $contact || $svc_acct;
3043 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3045 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3046 or return { %$info, 'error' => 'Account not found' };
3048 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3049 'domsvc' => $svc_domain->svcnum }
3051 or return { %$info, 'error' => 'Account not found' };
3053 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3054 or return { %$info, 'error' => 'Account not found' };
3056 $cust_main = $cust_pkg->cust_main;
3061 'email' => sub { 1; },
3063 my( $p, $cust_main ) = @_;
3064 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3065 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3068 my( $p, $cust_main ) = @_;
3069 my $cust_pay = qsearchs({
3070 'table' => 'cust_pay',
3071 'hashref' => { 'custnum' => $cust_main->custnum },
3072 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3076 $p->{'amount'} == $cust_pay->paid;
3079 my( $p, $cust_main ) = @_;
3080 $p->{'zip'} eq $cust_main->zip
3081 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3085 foreach my $verify ( split(',', $verification) ) {
3087 &{ $verify{$verify} }( $p, $cust_main )
3088 or return { %$info, 'error' => 'Account not found' };
3092 #okay, we're verified
3096 my $error = $contact->send_reset_email(
3097 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3101 return { %$info, 'error' => $error }; #????
3104 } elsif ( $svc_acct ) {
3106 #create a unique session
3108 my $reset_session = {
3109 'svcnum' => $svc_acct->svcnum,
3113 my $timeout = '1 hour'; #?
3115 my $reset_session_id;
3117 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3118 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3121 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3125 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3126 $cust_main->agentnum);
3127 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3128 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3130 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3131 my $error = $msg_template->send( 'cust_main' => $cust_main,
3132 'object' => $svc_acct,
3133 'substitutions' => {
3134 'session_id' => $reset_session_id,
3138 return { %$info, 'error' => $error }; #????
3143 return { %$info, 'error' => '' };
3146 sub check_reset_passwd {
3149 my $conf = new FS::Conf;
3150 my $verification = $conf->config('selfservice-password_reset_verification')
3151 or return { 'error' => 'Password resets disabled' };
3153 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3154 or return { 'error' => "Can't resume session" }; #better error message
3156 if ( $reset_session->{'svcnum'} ) {
3158 my $svcnum = $reset_session->{'svcnum'};
3160 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3161 or return { 'error' => "Service not found" };
3163 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3164 my $info = skin_info($p);
3168 'session_id' => $p->{'session_id'},
3169 'username' => $svc_acct->username,
3172 } elsif ( $reset_session->{'contactnum'} ) {
3174 my $contactnum = $reset_session->{'contactnum'};
3176 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3177 or return { 'error' => "Contact not found" };
3179 my @contact_email = $contact->contact_email;
3180 return { 'error' => 'No contact email' } unless @contact_email;
3182 $p->{'agentnum'} = $contact->cust_main->agentnum;
3183 my $info = skin_info($p);
3187 'session_id' => $p->{'session_id'},
3188 'email' => $contact_email[0]->email, #the first?
3193 return { 'error' => 'No svcnum or contactnum in session' }; #??
3199 sub process_reset_passwd {
3202 my $conf = new FS::Conf;
3203 my $verification = $conf->config('selfservice-password_reset_verification')
3204 or return { 'error' => 'Password resets disabled' };
3206 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3207 or return { 'error' => "Can't resume session" }; #better error message
3212 if ( $reset_session->{'svcnum'} ) {
3214 my $svcnum = $reset_session->{'svcnum'};
3216 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3217 or return { 'error' => "Service not found" };
3219 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3220 $info ||= skin_info($p);
3225 if ( $reset_session->{'contactnum'} ) {
3227 my $contactnum = $reset_session->{'contactnum'};
3229 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3230 or return { 'error' => "Contact not found" };
3232 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3233 $info ||= skin_info($p);
3237 return { %$info, 'error' => "New passwords don't match." }
3238 if $p->{'new_password'} ne $p->{'new_password2'};
3240 return { %$info, 'error' => 'Enter new password' }
3241 unless length($p->{'new_password'});
3245 $svc_acct->set_password($p->{'new_password'});
3246 my $error = $svc_acct->replace();
3248 return { %$info, 'error' => $error } if $error;
3250 #my($label, $value) = $svc_acct->cust_svc->label;
3251 #return { 'error' => $error,
3252 # #'label' => $label,
3253 # #'value' => $value,
3260 my $error = $contact->change_password($p->{'new_password'});
3262 return { %$info, 'error' => $error }; # if $error;
3266 #password changed ,so remove session, don't want it reused
3267 _cache->remove($p->{'session_id'});
3269 return { %$info, 'error' => '' };
3275 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3276 return { 'error' => $session } if $context eq 'error';
3279 if ( $session->{'pkgnum'} ) {
3281 #tickets for specific service with pkg-balances on
3282 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3283 'pkgnum' => $session->{'pkgnum'} })
3284 or return { 'error' => 'unknown package' };
3285 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3286 push @tickets, $cust_svc->tickets( $p->{status} );
3291 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3292 or return { 'error' => "unknown custnum $custnum" };
3294 @tickets = $cust_main->tickets( $p->{status} );
3297 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3298 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3299 my $conf = new FS::Conf;
3300 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3304 ($a->{'_selfservice_priority'} eq '') <=>
3305 ($b->{'_selfservice_priority'} eq '')
3308 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3314 +{ tickets => \@tickets };
3321 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3322 return { 'error' => $session } if $context eq 'error';
3324 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3325 FS::TicketSystem->init();
3327 my $conf = new FS::Conf;
3328 my $queue = $p->{'queue'}
3329 || $conf->config('ticket_system-selfservice_queueid')
3330 || $conf->config('ticket_system-default_queueid');
3332 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3333 my $err_or_ticket = FS::TicketSystem->create_ticket(
3334 '', #create RT session based on FS CurrentUser (fs_selfservice)
3336 'custnum' => $custnum,
3337 'svcnum' => $session->{'svcnum'},
3338 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3341 if ( ref($err_or_ticket) ) {
3342 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3344 return { 'error' => '',
3345 'ticket_id' => $err_or_ticket->id,
3348 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3350 return { 'error' => $err_or_ticket };
3358 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3359 return { 'error' => $session } if $context eq 'error';
3361 return { error => 'requested format not implemented' }
3362 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3364 my $conf = new FS::Conf;
3365 my $age_threshold = 0;
3366 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3367 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3369 my $search = { 'custnum' => $custnum };
3370 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3371 my $cust_main = qsearchs('cust_main', $search )
3372 or return { 'error' => "unknown custnum $custnum" };
3374 # does it make more sense to just run one sql query for this instead of all the
3375 # insanity below? would increase performance greately for large data sets?
3377 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3378 my @part_svc = $cust_pkg->part_svc;
3379 foreach my $part_svc ( @part_svc ) {
3380 if($part_svc->svcdb eq 'svc_phone'){
3381 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3382 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3383 push @svc_phone, $cust_pkg_svc->svc_x
3384 if $cust_pkg_svc->date_inserted >= $age_threshold;
3392 my($xls_r,$xls_c) = (0,0);
3395 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3396 if($p->{'format'} eq 'csv') {
3397 $csv = new Text::CSV_XS { 'always_quote' => 1,
3400 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3401 $content .= $csv->string;
3403 elsif($p->{'format'} eq 'xls') {
3404 my $XLS1 = new IO::Scalar \$content;
3405 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3406 or return { 'error' => "Error opening .xls file: $!" };
3407 $xls = $xls_workbook->add_worksheet('DIDs');
3408 foreach ( @fields ) {
3409 $xls->write(0,$xls_c++,$_);
3414 foreach my $svc_phone ( @svc_phone ) {
3415 my @cols = map { $svc_phone->$_ } @fields;
3416 if($p->{'format'} eq 'csv') {
3417 return { 'error' => 'Unable to create CSV' }
3418 unless $csv->combine(@cols);
3419 $content .= $csv->string;
3421 elsif($p->{'format'} eq 'xls') {
3424 $xls->write($xls_r,$xls_c++,$_);
3430 $xls_workbook->close() if $p->{'format'} eq 'xls';
3432 { content => $content, format => $p->{'format'}, };
3437 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3438 return { 'error' => $session } if $context eq 'error';
3440 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3441 # FS::TicketSystem->init();
3442 # return { 'error' => 'get_ticket configuration error' }
3443 # if $FS::TicketSystem::system ne 'RT_Internal';
3445 # check existence and ownership as part of this
3446 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3447 my $rt_session = FS::TicketSystem->session('');
3448 my $Ticket = FS::TicketSystem->get_ticket_object(
3450 ticket_id => $p->{'ticket_id'},
3453 return { 'error' => 'ticket not found' } if !$Ticket;
3455 if ( length( $p->{'subject'} || '' ) ) {
3457 if ( $p->{'subject'} ne $Ticket->Subject ) {
3458 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3459 return { 'error' => "unable to set subject: $msg" } if !$val;
3463 if(length($p->{'reply'})) {
3464 my @err_or_res = FS::TicketSystem->correspond_ticket(
3466 'ticket_id' => $p->{'ticket_id'},
3467 'content' => $p->{'reply'},
3470 return { 'error' => 'unable to reply to ticket' }
3471 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3474 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3475 my $err_or_ticket = FS::TicketSystem->get_ticket(
3477 'ticket_id' => $p->{'ticket_id'},
3480 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3481 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3483 return { 'error' => $err_or_ticket };
3486 my @custs = @{$err_or_ticket->{'custs'}};
3487 my @txns = @{$err_or_ticket->{'txns'}};
3490 # superseded by check in get_ticket_object
3491 #return { 'error' => 'invalid ticket requested' }
3492 #unless grep($_ eq $custnum, @custs);
3494 foreach my $txn ( @txns ) {
3495 push @filtered_txns, $txn
3496 if ($txn->{'type'} eq 'EmailRecord'
3497 || $txn->{'type'} eq 'Correspond'
3498 || $txn->{'type'} eq 'Create');
3501 warn "$me get_ticket: successful: \n"
3503 return { 'error' => '',
3504 'transactions' => \@filtered_txns,
3505 'ticket_fields' => $err_or_ticket->{'fields'},
3506 'ticket_id' => $p->{'ticket_id'},
3510 sub adjust_ticket_priority {
3512 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3513 return { 'error' => $session } if $context eq 'error';
3515 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3516 # FS::TicketSystem->init;
3517 my $ss_priority = FS::TicketSystem->selfservice_priority;
3519 return { 'error' => 'adjust_ticket_priority configuration error' }
3520 if $FS::TicketSystem::system ne 'RT_Internal'
3523 my $values = $p->{'values'}; #hashref, id => priority value
3526 foreach my $id (keys %$values) {
3527 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3528 my $Ticket = FS::TicketSystem->get_ticket_object('',
3530 'custnum' => $custnum,
3533 $ticket_error{$id} = 'ticket not found';
3537 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3538 # We're not going to implement it for RT_External.
3539 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3540 my $new_value = $values->{$id};
3541 next if $old_value eq $new_value;
3543 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3545 # AddCustomFieldValue works fine (replacing any existing value) if it's
3546 # a single-valued custom field, which it should be. If it's not, you're
3547 # doing something wrong.
3549 if ( length($new_value) ) {
3550 ($val, $msg) = $Ticket->AddCustomFieldValue(
3551 Field => $ss_priority,
3552 Value => $new_value,
3556 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3557 Field => $ss_priority,
3558 Value => $old_value,
3562 $ticket_error{$id} = $msg if !$val;
3563 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3565 return { 'error' => '',
3566 'ticket_error' => \%ticket_error,
3567 %{ customer_info($p) } # send updated customer info back
3573 sub _custoragent_session_custnum {
3576 my($context, $session, $custnum);
3577 if ( $p->{'session_id'} ) {
3579 $context = 'customer';
3580 $session = _cache->get($p->{'session_id'})
3581 or return ( 'error' => "Can't resume session" ); #better error message
3582 $custnum = $session->{'custnum'};
3584 } elsif ( $p->{'agent_session_id'} ) {
3587 my $agent_cache = new FS::ClientAPI_SessionCache( {
3588 'namespace' => 'FS::ClientAPI::Agent',
3590 $session = $agent_cache->get($p->{'agent_session_id'})
3591 or return ( 'error' => "Can't resume session" ); #better error message
3592 $custnum = $p->{'custnum'};
3596 return ( 'error' => "Can't resume session" ); #better error message
3599 ($context, $session, $custnum);