1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
51 $me = '[FS::ClientAPI::MyAccount]';
53 use vars qw( @cust_main_editable_fields @location_editable_fields );
54 @cust_main_editable_fields = qw(
55 first last company daytime night fax mobile
57 payby payinfo payname paystart_month paystart_year payissue payip
58 ss paytype paystate stateid stateid_state
60 @location_editable_fields = qw(
61 address1 address2 city county state zip country
65 BEGIN { #preload to reduce time customer_info takes
66 if ( $FS::TicketSystem::system ) {
67 warn "$me: initializing ticket system\n" if $DEBUG;
68 FS::TicketSystem->init();
73 $cache ||= new FS::ClientAPI_SessionCache( {
74 'namespace' => 'FS::ClientAPI::MyAccount',
81 my($context, $session, $custnum) = _custoragent_session_custnum($p);
82 #return { 'error' => $session } if $context eq 'error';
85 if ( $context eq 'customer' ) {
87 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
90 $sth->execute($custnum) or die $sth->errstr;
92 $agentnum = $sth->fetchrow_arrayref->[0]
93 or die "no agentnum for custnum $custnum";
95 #} elsif ( $context eq 'agent' ) {
96 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
99 $p->{'agentnum'} = $agentnum;
101 my $conf = new FS::Conf;
103 #false laziness w/Signup.pm
105 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
107 if ( $skin_info_cache_agent ) {
109 warn "$me loading cached skin info for agentnum $agentnum\n"
114 warn "$me populating skin info cache for agentnum $agentnum\n"
117 $skin_info_cache_agent = {
118 'agentnum' => $agentnum,
119 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
120 qw( company_name date_format ) ),
121 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
122 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
123 text_color link_color vlink_color hlink_color alink_color
124 font title_color title_align title_size menu_bgcolor menu_fontsize
127 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
128 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
129 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
131 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
132 qw( title_left_image title_right_image
133 menu_top_image menu_body_image menu_bottom_image
136 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
137 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
138 qw( head body_header body_footer company_address ) ),
139 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
142 services.php Services
143 services.php My Services
144 services_new.php Order a new service
147 personal.php Personal Information
148 password.php Change Password
151 payment_cc.php Credit Card Payment
152 payment_ach.php Electronic Check Payment
153 payment_paypal.php PayPal Payment
154 payment_webpay.php Webpay Payments
157 usage_data.php Data usage
158 usage_cdr.php Call usage
160 tickets.php Help Desk
161 tickets.php Open Tickets
162 tickets_resolved.php Resolved Tickets
163 ticket_create.php Create a new ticket
171 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
175 #{ %$skin_info_cache_agent };
176 $skin_info_cache_agent;
183 my $conf = new FS::Conf;
187 'phone_login' => $conf->exists('selfservice_server-phone_login'),
188 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
189 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
190 'banner_image_md5' =>
191 md5_hex($conf->config_binary('selfservice-login_banner_image')),
198 sub login_banner_image {
200 my $conf = new FS::Conf;
201 my $image = $conf->config_binary('selfservice-login_banner_image');
203 'md5' => md5_hex($image),
208 #false laziness w/FS::ClientAPI::passwd::passwd
212 my $conf = new FS::Conf;
216 if ( $p->{'domain'} eq 'svc_phone'
217 && $conf->exists('selfservice_server-phone_login') ) {
219 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
220 return { error => 'Number not found.' } unless $svc_phone;
223 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
224 #return { error => 'Only primary user may log in.' }
225 # if $conf->exists('selfservice_server-primary_only')
226 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
228 return { error => 'Incorrect PIN.' }
229 unless $svc_phone->check_pin($p->{'password'});
233 } elsif ( $p->{email}
234 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
237 return { error => 'Incorrect contact password.' }
238 unless $contact->authenticate_password($p->{'password'});
240 $session->{'custnum'} = $contact->custnum;
244 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
246 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
247 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
249 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
250 'domsvc' => $svc_domain->svcnum, }
252 return { error => 'User not found.' } unless $svc_acct;
254 if($conf->exists('selfservice_server-login_svcpart')) {
255 my @svcpart = $conf->config('selfservice_server-login_svcpart');
256 my $svcpart = $svc_acct->cust_svc->svcpart;
257 return { error => 'Invalid user.' }
258 unless grep($_ eq $svcpart, @svcpart);
261 return { error => 'Incorrect password.' }
262 unless $svc_acct->check_password($p->{'password'});
270 $session->{'svcnum'} = $svc_x->svcnum;
272 my $cust_svc = $svc_x->cust_svc;
273 my $cust_pkg = $cust_svc->cust_pkg;
275 my $cust_main = $cust_pkg->cust_main;
276 $session->{'custnum'} = $cust_main->custnum;
277 if ( $conf->exists('pkg-balances') ) {
278 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
279 $cust_main->ncancelled_pkgs;
280 $session->{'pkgnum'} = $cust_pkg->pkgnum
281 if scalar(@cust_pkg) > 1;
285 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
286 #return { error => 'Only primary user may log in.' }
287 # if $conf->exists('selfservice_server-primary_only')
288 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
289 my $part_pkg = $cust_pkg->part_pkg;
290 return { error => 'Only primary user may log in.' }
291 if $conf->exists('selfservice_server-primary_only')
292 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
298 $session_id = sha512_hex(time(). {}. rand(). $$)
299 } until ( ! defined _cache->get($session_id) ); #just in case
301 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
302 _cache->set( $session_id, $session, $timeout );
304 return { 'error' => '',
305 'session_id' => $session_id,
311 my $skin_info = skin_info($p);
312 if ( $p->{'session_id'} ) {
313 _cache->remove($p->{'session_id'});
314 return { %$skin_info, 'error' => '' };
316 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
323 my($context, $session, $custnum) = _custoragent_session_custnum($p);
324 return { 'error' => $session } if $context eq 'error';
326 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
327 or return { 'error' => "Service not found" };
329 $session->{'svcnum'} = $svc_acct->svcnum;
331 my $conf = new FS::Conf;
332 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
333 _cache->set( $p->{'session_id'}, $session, $timeout );
335 return { 'error' => '' };
339 sub payment_gateway {
341 # takes a cust_main and a cust_payby entry, returns the payment_gateway
342 my $conf = new FS::Conf;
343 my $cust_main = shift;
344 my $cust_payby = shift;
345 my $gatewaynum = $conf->config('selfservice-payment_gateway');
347 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
348 die "configured gatewaynum $gatewaynum not found!" if !$pg;
352 return '' if ! FS::payby->realtime($cust_payby);
353 my $pg = $cust_main->agent->payment_gateway(
354 'method' => FS::payby->payby2bop($cust_payby),
364 my $conf = new FS::Conf;
366 my $info = skin_info($p);
368 use vars qw( $cust_paybys ); #cache for performance
369 unless ( $cust_paybys ) {
371 my %cust_paybys = map { $_ => 1 }
372 map { FS::payby->payby2payment($_) }
373 $conf->config('signup_server-payby');
375 $cust_paybys = [ keys %cust_paybys ];
378 $info->{'cust_paybys'} = $cust_paybys;
380 my($context, $session, $custnum) = _custoragent_session_custnum($p);
381 return { 'error' => $session } if $context eq 'error';
383 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
384 or return { 'error' => "unknown custnum $custnum" };
386 $info->{'hide_payment_fields'} = [
388 my $pg = payment_gateway($cust_main, $_);
389 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
390 } @{ $info->{cust_paybys} }
393 $info->{'self_suspend_reason'} =
394 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
396 $info->{'edit_ticket_subject'} =
397 $conf->exists('ticket_system-selfservice_edit_subject') &&
398 $cust_main->edit_subject;
400 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
402 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
405 'custnum' => $custnum,
406 'access_pkgnum' => $session->{'pkgnum'},
407 'access_svcnum' => $session->{'svcnum'},
414 my($context, $session, $custnum) = _custoragent_session_custnum($p);
415 return { 'error' => $session } if $context eq 'error';
419 my $conf = new FS::Conf;
420 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
422 # if ( $FS::TicketSystem::system ) {
423 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
424 # FS::TicketSystem->init();
427 if ( $custnum ) { #customer record
429 %return = ( %return, %{ customer_info_short($p) } );
431 #redundant with customer_info_short, but we need it for several things below
432 my $search = { 'custnum' => $custnum };
433 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
434 my $cust_main = qsearchs('cust_main', $search )
435 or return { 'error' => "unknown custnum $custnum" };
437 my $list_tickets = list_tickets($p);
438 $return{'tickets'} = $list_tickets->{'tickets'};
440 if ( $session->{'pkgnum'} ) {
441 #XXX open invoices in the pkg-balances case
445 invnum => $_->invnum,
446 date => time2str("%b %o, %Y", $_->_date),
449 } $cust_main->open_cust_bill;
450 $return{open_invoices} = \@open;
452 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
453 my $sth = dbh->prepare($sql) or die dbh->errstr;
454 $sth->execute($custnum) or die $sth->errstr;
455 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
456 $return{'last_invoice_date_pretty'} =
457 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
460 #customer_info_short always has nobalance on..
461 $return{small_custview} =
462 small_custview( $cust_main,
463 $return{countrydefault},
464 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
467 $return{has_ship_address} = $cust_main->has_ship_address;
468 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
469 $return{statuscolor} = $cust_main->statuscolor;
470 $return{status_label} = $cust_main->status_label;
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{first} = $cust_main->first;
563 $return{'last'} = $cust_main->get('last');
564 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
566 $return{payby} = $cust_main->payby;
568 #none of these are terribly expensive if we want 'em...
569 for (@cust_main_editable_fields) {
570 $return{$_} = $cust_main->get($_);
572 #maybe a little more expensive, but it should be cached by now
573 for (@location_editable_fields) {
574 $return{$_} = $cust_main->bill_location->get($_)
575 if $cust_main->bill_locationnum;
576 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
577 if $cust_main->ship_locationnum;
580 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
581 $return{payinfo} = $cust_main->paymask;
582 @return{'month', 'year'} = $cust_main->paydate_monthyear;
585 my @invoicing_list = $cust_main->invoicing_list;
586 $return{'invoicing_list'} =
587 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
588 $return{'postal_invoicing'} =
589 0 < ( grep { $_ eq 'POST' } @invoicing_list );
591 if ( $session->{'svcnum'} ) {
592 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
593 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
594 $return{'svcnum'} = $session->{'svcnum'};
597 } elsif ( $session->{'svcnum'} ) { #no customer record
599 #uuh, not supproted yet... die?
600 return { 'error' => 'customer_info_short not yet supported as agent' };
604 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
608 return { 'error' => '',
609 'custnum' => $custnum,
614 sub billing_history {
617 my($context, $session, $custnum) = _custoragent_session_custnum($p);
618 return { 'error' => $session } if $context eq 'error';
620 return { 'error' => 'No customer' } unless $custnum;
622 my $search = { 'custnum' => $custnum };
623 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
624 my $cust_main = qsearchs('cust_main', $search )
625 or return { 'error' => "unknown custnum $custnum" };
629 if ( $session->{'pkgnum'} ) {
630 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
631 #next_bill_date from cust_pkg?
632 return { 'error' => 'No history for package' };
635 $return{balance} = $cust_main->balance;
636 $return{next_bill_date} = $cust_main->next_bill_date;
637 $return{next_bill_date_pretty} =
638 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
643 my $conf = new FS::Conf;
645 if ( $conf->exists('selfservice-billing_history-line_items') ) {
647 foreach my $cust_bill ( $cust_main->cust_bill ) {
650 'type' => 'Line item',
651 'description' => $_->desc( $cust_main->locale ).
652 ( $_->sdate && $_->edate
653 ? ' '. time2str('%d-%b-%Y', $_->sdate).
654 ' To '. time2str('%d-%b-%Y', $_->edate)
657 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
658 'date' => $cust_bill->_date,
659 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
661 foreach $cust_bill->cust_bill_pkg;
669 'description' => 'Invoice #'. $_->display_invnum,
670 'amount' => sprintf('%.2f', $_->charged ),
672 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
674 foreach $cust_main->cust_bill;
680 'description' => 'Payment', #XXX type
681 'amount' => sprintf('%.2f', 0 - $_->paid ),
683 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
685 foreach $cust_main->cust_pay;
689 'description' => 'Credit', #more info?
690 'amount' => sprintf('%.2f', 0 -$_->amount ),
692 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
694 foreach $cust_main->cust_credit;
698 'description' => 'Refund', #more info? type, like payment?
699 'amount' => $_->refund,
701 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
703 foreach $cust_main->cust_refund;
705 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
707 $return{'history'} = \@history;
715 my $session = _cache->get($p->{'session_id'})
716 or return { 'error' => "Can't resume session" }; #better error message
718 my $custnum = $session->{'custnum'}
719 or return { 'error' => "no customer record" };
721 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
722 or return { 'error' => "unknown custnum $custnum" };
724 my $new = new FS::cust_main { $cust_main->hash };
726 $new->set( $_ => $p->{$_} )
727 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
729 if ( exists($p->{address1}) ) {
730 my $bill_location = FS::cust_location->new({
731 map { $_ => $p->{$_} } @location_editable_fields
733 # if this is unchanged from before, cust_main::replace will ignore it
734 $new->set('bill_location' => $bill_location);
737 if ( exists($p->{ship_address1}) ) {
738 my $ship_location = FS::cust_location->new({
739 map { $_ => $p->{"ship_$_"} } @location_editable_fields
741 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
742 # Selfservice unfortunately tries to indicate "same as billing
743 # address" by sending all fields empty. Did this ever work?
744 $ship_location = $cust_main->bill_location;
746 $new->set('ship_location' => $ship_location);
748 # but if it hasn't been passed in at all, leave ship_location alone--
749 # DON'T change it to match bill_location.
752 if (exists($p->{'payby'})) {
753 $p->{'payby'} =~ /^([A-Z]{4})$/
754 or return { 'error' => "illegal_payby " . $p->{'payby'} };
758 my $conf = new FS::Conf;
760 if ( $payby =~ /^(CARD|DCRD)$/ ) {
762 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
764 if ( $new->payinfo eq $cust_main->paymask ) {
765 $new->payinfo($cust_main->payinfo);
767 $new->payinfo($p->{'payinfo'});
770 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
772 if ( $conf->exists('selfservice-onfile_require_cvv') ){
773 return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
776 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
779 $p->{'payinfo1'} =~ /^([\dx]+)$/
780 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
782 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
783 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
785 $payinfo = $payinfo1. '@'. $payinfo2;
787 $new->payinfo( ($payinfo eq $cust_main->paymask)
788 ? $cust_main->payinfo
792 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
794 } elsif ( $payby =~ /^(BILL)$/ ) {
796 } elsif ( $payby ) { #notyet ready
797 return { 'error' => "unknown payby $payby" };
801 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
802 #false laziness with httemplate/edit/process/cust_main.cgi
803 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
804 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
806 @invoicing_list = $cust_main->invoicing_list;
809 my $error = $new->replace($cust_main, \@invoicing_list);
810 return { 'error' => $error } if $error;
813 return { 'error' => '' };
818 my $session = _cache->get($p->{'session_id'})
819 or return { 'error' => "Can't resume session" }; #better error message
825 my $conf = new FS::Conf;
826 use vars qw($payment_info); #cache for performance
827 unless ( $payment_info ) {
829 my %states = map { $_->state => 1 }
830 qsearch('cust_main_county', {
831 'country' => $conf->config('countrydefault') || 'US'
834 my %cust_paybys = map { $_ => 1 }
835 map { FS::payby->payby2payment($_) }
836 $conf->config('signup_server-payby');
838 my @cust_paybys = keys %cust_paybys;
842 #list all counties/states/countries
843 'cust_main_county' =>
844 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
846 #shortcut for one-country folks
848 [ sort { $a cmp $b } keys %states ],
850 'card_types' => card_types(),
852 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
853 'require_cvv' => $conf->exists('selfservice-require_cvv'),
854 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
856 'paytypes' => [ @FS::cust_main::paytypes ],
858 'paybys' => [ $conf->config('signup_server-payby') ],
859 'cust_paybys' => \@cust_paybys,
861 'stateid_label' => FS::Msgcat::_gettext('stateid'),
862 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
864 'show_ss' => $conf->exists('show_ss'),
865 'show_stateid' => $conf->exists('show_stateid'),
866 'show_paystate' => $conf->exists('show_bankstate'),
868 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
870 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
879 my %return = %$payment_info;
881 my $custnum = $session->{'custnum'};
883 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
884 or return { 'error' => "unknown custnum $custnum" };
886 $return{'hide_payment_fields'} = [
888 my $pg = payment_gateway($cust_main, $_);
889 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
890 } @{ $return{cust_paybys} }
893 $return{balance} = $cust_main->balance; #XXX pkg-balances?
895 $return{payname} = $cust_main->payname
896 || ( $cust_main->first. ' '. $cust_main->get('last') );
898 $return{$_} = $cust_main->bill_location->get($_)
899 for qw(address1 address2 city state zip);
901 $return{payby} = $cust_main->payby;
902 $return{stateid_state} = $cust_main->stateid_state;
904 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
905 $return{card_type} = cardtype($cust_main->payinfo);
906 $return{payinfo} = $cust_main->paymask;
908 @return{'month', 'year'} = $cust_main->paydate_monthyear;
912 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
913 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
914 $return{payinfo1} = $payinfo1;
915 $return{payinfo2} = $payinfo2;
916 $return{paytype} = $cust_main->paytype;
917 $return{paystate} = $cust_main->paystate;
918 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
921 if ( $conf->config('prepayment_discounts-credit_type') ) {
923 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
926 #doubleclick protection
928 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
929 $return{paybatch} = $return{payunique}; #back compat
931 return { 'error' => '',
937 #some false laziness with httemplate/process/payment.cgi - look there for
938 #ACH and CVV support stuff
940 sub validate_payment {
943 my $session = _cache->get($p->{'session_id'})
944 or return { 'error' => "Can't resume session" }; #better error message
946 my $custnum = $session->{'custnum'};
948 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
949 or return { 'error' => "unknown custnum $custnum" };
951 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
952 or return { 'error' => gettext('illegal_amount') };
954 return { error => 'Amount must be greater than 0' } unless $amount > 0;
956 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
957 #changing the hidden form values
958 my $conf = new FS::Conf;
959 my $fee_display = $conf->config('selfservice_process-display') || 'add';
960 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
961 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
962 if ( $fee_display eq 'add'
964 and ! $fee_skip_first || scalar($cust_main->cust_pay)
967 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
968 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
971 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
972 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
973 my $discount_term = $1;
975 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
976 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
979 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
980 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
983 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
984 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
987 $payunique = $paybatch if ! length($payunique) && length($paybatch);
989 $p->{'payby'} ||= 'CARD';
990 $p->{'payby'} =~ /^([A-Z]{4})$/
991 or return { 'error' => "illegal_payby " . $p->{'payby'} };
994 #false laziness w/process/payment.cgi
997 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
999 $p->{'payinfo1'} =~ /^([\dx]+)$/
1000 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1002 $p->{'payinfo2'} =~ /^([\dx]+)$/
1003 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1005 $payinfo = $payinfo1. '@'. $payinfo2;
1007 $payinfo = $cust_main->payinfo
1008 if $cust_main->paymask eq $payinfo;
1010 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1012 $payinfo = $p->{'payinfo'};
1016 #more intelligent matching will be needed here if you change
1017 #card_masking_method and don't remove existing paymasks
1018 if ( $cust_main->paymask eq $payinfo ) {
1019 $payinfo = $cust_main->payinfo;
1023 $payinfo =~ s/\D//g;
1024 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1025 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1029 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1030 return { 'error' => gettext('unknown_card_type') }
1031 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1033 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1034 if ( cardtype($payinfo) eq 'American Express card' ) {
1035 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1036 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1039 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1040 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1043 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1044 return { 'error' => 'CVV2 is required' };
1045 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1046 return { 'error' => 'CVV2 is required' };
1050 die "unknown payby $payby";
1053 my %payby2fields = (
1054 'CARD' => [ qw( paystart_month paystart_year payissue payip
1055 address1 address2 city state zip country ) ],
1056 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1060 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1063 'cust_main' => $cust_main, #XXX or just custnum??
1064 'amount' => sprintf('%.2f', $amount),
1066 'payinfo' => $payinfo,
1067 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1068 'card_type' => $card_type,
1069 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1070 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1071 'month' => $p->{'month'},
1072 'year' => $p->{'year'},
1073 'payname' => $payname,
1074 'payunique' => $payunique,
1075 'paybatch' => $paybatch,
1076 'paycvv' => $paycvv,
1077 'payname' => $payname,
1078 'discount_term' => $discount_term,
1079 'pkgnum' => $session->{'pkgnum'},
1080 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1090 my $validate = validate_payment($p);
1091 return $validate if $validate->{'error'};
1093 my $conf = new FS::Conf;
1094 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1095 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1097 +{ map { $_=>$validate->{$_} }
1098 qw( card_type paymask payname paydate_pretty month year amount
1099 address1 address2 city state zip country
1105 sub process_stored_payment {
1108 my $session_id = $p->{'session_id'};
1110 my $payment_info = _cache->get( "payment_$session_id" )
1111 or return { 'error' => "Can't resume session" }; #better error message
1113 do_process_payment($payment_info);
1117 sub process_payment {
1120 my $payment_info = validate_payment($p);
1121 return $payment_info if $payment_info->{'error'};
1123 do_process_payment($payment_info);
1127 sub do_process_payment {
1128 my $validate = shift;
1130 my $cust_main = $validate->{'cust_main'};
1132 my $amount = delete $validate->{'amount'};
1135 my $payby = delete $validate->{'payby'};
1137 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1140 'paynum_ref' => \$paynum,
1143 return { 'error' => $error } if $error;
1145 #no error, so order the fee package if applicable...
1146 my $conf = new FS::Conf;
1147 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1148 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1150 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1152 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1154 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1155 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1158 #and generate an invoice for it now too
1159 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1160 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1165 $cust_main->apply_payments;
1167 if ( $validate->{'save'} ) {
1168 my $new = new FS::cust_main { $cust_main->hash };
1169 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1170 $new->set( $_ => $validate->{$_} )
1171 foreach qw( payname paystart_month paystart_year payissue payip );
1172 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1174 my $bill_location = FS::cust_location->new({
1175 map { $_ => $validate->{$_} }
1176 qw(address1 address2 city state country zip)
1178 $new->set('bill_location' => $bill_location);
1179 # but don't allow the service address to change this way.
1181 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1182 $new->set( $_ => $validate->{$_} )
1183 foreach qw( payname payip paytype paystate
1184 stateid stateid_state );
1185 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1187 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1188 $new->set( 'paydate' => $validate->{'paydate'} );
1189 my $error = $new->replace($cust_main);
1191 #no, this causes customers to process their payments again
1192 #return { 'error' => $error };
1193 #XXX just warn verosely for now so i can figure out how these happen in
1194 # the first place, eventually should redirect them to the "change
1195 #address" page but indicate the payment did process??
1196 delete($validate->{'payinfo'}); #don't want to log this!
1197 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1198 "NEW: ". Dumper($new)."\n".
1199 "OLD: ". Dumper($cust_main)."\n".
1200 "PACKET: ". Dumper($validate)."\n";
1208 my $receipt_html = '';
1210 # currently supported for realtime CC only; send receipt data to SS
1211 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1214 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1217 <TD ALIGN="right">Payment#</TD>
1218 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1222 <TD ALIGN="right">Date</TD>
1224 <TD BGCOLOR="#FFFFFF"><B>! .
1225 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1231 <TD ALIGN="right">Amount</TD>
1232 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1237 <TD ALIGN="right">Payment method</TD>
1238 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1251 'amount' => sprintf('%.2f', $cust_pay->paid),
1252 'date' => $cust_pay->_date,
1253 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1254 'time_pretty' => time2str('%T', $cust_pay->_date),
1255 'auth_num' => $cust_pay->auth,
1256 'order_num' => $cust_pay->order_number,
1257 'receipt_html' => $receipt_html,
1264 'receipt_html' => '',
1271 sub realtime_collect {
1274 my $session = _cache->get($p->{'session_id'})
1275 or return { 'error' => "Can't resume session" }; #better error message
1277 my $custnum = $session->{'custnum'};
1279 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1280 or return { 'error' => "unknown custnum $custnum" };
1283 if ( $p->{'amount'} ) {
1284 $amount = $p->{'amount'};
1286 elsif ( $session->{'pkgnum'} ) {
1287 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1290 $amount = $cust_main->balance;
1293 my $error = $cust_main->realtime_collect(
1294 'method' => $p->{'method'},
1295 'amount' => $amount,
1296 'pkgnum' => $session->{'pkgnum'},
1297 'session_id' => $p->{'session_id'},
1301 return { 'error' => $error } unless ref( $error );
1303 return { 'error' => '', amount => $amount, %$error };
1306 sub start_thirdparty {
1308 my $session = _cache->get($p->{'session_id'})
1309 or return { 'error' => "Can't resume session" }; #better error message
1310 my $custnum = $session->{'custnum'};
1311 my $cust_main = FS::cust_main->by_key($custnum);
1313 my $amount = $p->{'amount'}
1314 or return { error => 'no amount' };
1316 my $result = $cust_main->create_payment(
1317 'method' => $p->{'method'},
1318 'amount' => $p->{'amount'},
1319 'pkgnum' => $session->{'pkgnum'},
1320 'session_id' => $p->{'session_id'},
1323 if ( ref($result) ) { # hashref or error
1326 return { error => $result };
1330 sub finish_thirdparty {
1332 my $session_id = delete $p->{'session_id'};
1333 my $session = _cache->get($session_id)
1334 or return { 'error' => "Can't resume session" };
1335 my $custnum = $session->{'custnum'};
1336 my $cust_main = FS::cust_main->by_key($custnum);
1338 if ( $p->{_cancel} ) {
1339 # customer backed out of making a payment
1340 return $cust_main->cancel_payment( $session_id );
1342 my $result = $cust_main->execute_payment( $session_id, %$p );
1343 if ( ref($result) ) {
1346 return { error => $result };
1350 sub process_payment_order_pkg {
1353 my $hr = process_payment($p);
1354 return $hr if $hr->{'error'};
1359 sub process_payment_order_renew {
1362 my $hr = process_payment($p);
1363 return $hr if $hr->{'error'};
1368 sub process_prepay {
1372 my $session = _cache->get($p->{'session_id'})
1373 or return { 'error' => "Can't resume session" }; #better error message
1377 my $custnum = $session->{'custnum'};
1379 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1380 or return { 'error' => "unknown custnum $custnum" };
1382 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1383 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1391 return { 'error' => $error } if $error;
1393 return { 'error' => '',
1394 'amount' => $amount,
1395 'seconds' => $seconds,
1396 'duration' => duration_exact($seconds),
1397 'upbytes' => $upbytes,
1398 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1399 'downbytes' => $downbytes,
1400 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1401 'totalbytes'=> $totalbytes,
1402 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1409 my $session = _cache->get($p->{'session_id'})
1410 or return { 'error' => "Can't resume session" }; #better error message
1412 my $custnum = $session->{'custnum'};
1414 my $invnum = $p->{'invnum'};
1416 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1417 'custnum' => $custnum } )
1418 or return { 'error' => "Can't find invnum" };
1422 return { 'error' => '',
1423 'invnum' => $invnum,
1424 'invoice_text' => join('', $cust_bill->print_text ),
1425 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1432 my $session = _cache->get($p->{'session_id'})
1433 or return { 'error' => "Can't resume session" }; #better error message
1435 my $custnum = $session->{'custnum'};
1437 my $invnum = $p->{'invnum'};
1439 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1440 'custnum' => $custnum } )
1441 or return { 'error' => "Can't find invnum" };
1445 return { 'error' => '',
1446 'invnum' => $invnum,
1447 'invoice_pdf' => $cust_bill->print_pdf({
1448 'unsquelch_cdr' => 1,
1449 'locale' => $p->{'locale'},
1455 sub legacy_invoice {
1457 my $session = _cache->get($p->{'session_id'})
1458 or return { 'error' => "Can't resume session" }; #better error message
1460 my $custnum = $session->{'custnum'};
1462 my $legacyinvnum = $p->{'legacyinvnum'};
1465 'legacyinvnum' => $legacyinvnum,
1466 'custnum' => $custnum,
1469 my $legacy_cust_bill =
1470 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1471 || qsearchs('legacy_cust_bill', \%hash )
1472 or return { 'error' => "Can't find legacyinvnum" };
1476 return { 'error' => '',
1477 'legacyinvnum' => $legacyinvnum,
1478 'legacyid' => $legacy_cust_bill->legacyid,
1479 'invoice_html' => $legacy_cust_bill->content_html,
1484 sub legacy_invoice_pdf {
1486 my $session = _cache->get($p->{'session_id'})
1487 or return { 'error' => "Can't resume session" }; #better error message
1489 my $custnum = $session->{'custnum'};
1491 my $legacyinvnum = $p->{'legacyinvnum'};
1493 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1494 'legacyinvnum' => $legacyinvnum,
1495 'custnum' => $custnum,
1496 }) or return { 'error' => "Can't find legacyinvnum" };
1500 return { 'error' => '',
1501 'legacyinvnum' => $legacyinvnum,
1502 'legacyid' => $legacy_cust_bill->legacyid,
1503 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1511 #sessioning for this? how do we get the session id to the backend invoice
1512 # template so it can add it to the link, blah
1515 if ( $p->{'invnum'} ) {
1516 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1517 or return { 'error' => 'unknown invnum' };
1518 $agentnum = $cust_bill->cust_main->agentnum;
1521 my $templatename = $p->{'template'} || $p->{'templatename'};
1523 #false laziness-ish w/view/cust_bill-logo.cgi
1525 my $conf = new FS::Conf;
1526 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1527 $templatename = "_$1";
1532 my $filename = "logo$templatename.png";
1534 return { 'error' => '',
1535 'logo' => $conf->config_binary($filename, $agentnum),
1536 'content_type' => 'image/png', #should allow gif, jpg too
1543 my $session = _cache->get($p->{'session_id'})
1544 or return { 'error' => "Can't resume session" }; #better error message
1546 my $custnum = $session->{'custnum'};
1548 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1549 or return { 'error' => "unknown custnum $custnum" };
1551 my $conf = new FS::Conf;
1553 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1555 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1559 return { 'error' => '',
1560 'balance' => $cust_main->balance,
1563 my $owed = $_->owed;
1565 +{ 'invnum' => $_->invnum,
1566 '_date' => $_->_date,
1567 'date' => time2str("%b %o, %Y", $_->_date),
1568 'date_short' => time2str("%m-%d-%Y", $_->_date),
1569 'previous' => sprintf('%.2f', ($_->previous)[0]),
1570 'charged' => sprintf('%.2f', $_->charged),
1571 'owed' => sprintf('%.2f', $owed),
1572 'balance' => sprintf('%.2f', $balance),
1577 'legacy_invoices' => [
1579 +{ 'legacyinvnum' => $_->legacyinvnum,
1580 'legacyid' => $_->legacyid,
1581 '_date' => $_->_date,
1582 'date' => time2str("%b %o, %Y", $_->_date),
1583 'date_short' => time2str("%m-%d-%Y", $_->_date),
1584 'charged' => sprintf('%.2f', $_->charged),
1585 'has_content' => ( length($_->content_pdf)
1586 || length($_->content_html) ),
1596 my $session = _cache->get($p->{'session_id'})
1597 or return { 'error' => "Can't resume session" }; #better error message
1599 my $custnum = $session->{'custnum'};
1601 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1602 or return { 'error' => "unknown custnum $custnum" };
1604 my @errors = $cust_main->cancel( 'quiet'=>1 );
1606 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1608 return { 'error' => $error };
1615 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1616 return { 'error' => $session } if $context eq 'error';
1618 my $search = { 'custnum' => $custnum };
1619 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1620 my $cust_main = qsearchs('cust_main', $search )
1621 or return { 'error' => "unknown custnum $custnum" };
1623 my $conf = new FS::Conf;
1624 my $immutable = $conf->exists('selfservice_immutable-package');
1626 # the duplication below is necessary:
1627 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1628 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1629 # non-backwards-compatible change breaking the software of anyone using the API
1630 # instead of the stock selfservice
1631 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1632 if( $conf->exists('selfservice_server-view-wholesale') ) {
1633 return { 'svcnum' => $session->{'svcnum'},
1634 'custnum' => $custnum,
1635 'cust_pkg' => [ map {
1637 immutable => $immutable,
1638 part_pkg => [ map $_->hashref, $_->part_pkg ],
1640 [ map $_->hashref, $_->available_part_svc ],
1642 [ map { my $ref = { $_->hash,
1643 label => [ $_->label ],
1645 $ref->{_password} = $_->svc_x->_password
1646 if $context eq 'agent'
1647 && $conf->exists('agent-showpasswords')
1648 && $_->part_svc->svcdb eq 'svc_acct';
1653 } $cust_main->cust_pkg
1656 small_custview( $cust_main, $conf->config('countrydefault') ),
1657 'wholesale_view' => 1,
1658 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1659 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1660 'lnp' => $conf->exists('svc_phone-lnp'),
1664 { 'svcnum' => $session->{'svcnum'},
1665 'custnum' => $custnum,
1666 'cust_pkg' => [ map {
1667 my $primary_cust_svc = $_->primary_cust_svc;
1670 immutable => $immutable,
1671 pkg_label => $_->pkg_locale,
1672 status => $_->status,
1673 statuscolor => $_->statuscolor,
1675 [ map { $_->hashref }
1676 grep { $_->selfservice_access ne 'hidden' }
1677 $_->available_part_svc
1680 [ map { my $ref = { $_->hash,
1681 label => [ $_->label ],
1683 $ref->{_password} = $_->svc_x->_password
1684 if $context eq 'agent'
1685 && $conf->exists('agent-showpasswords')
1686 && $_->part_svc->svcdb eq 'svc_acct';
1687 $ref->{svchash} = { $_->svc_x->hash } if
1688 $_->part_svc->svcdb eq 'svc_phone';
1689 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1690 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1693 grep { $_->part_svc->selfservice_access ne 'hidden' }
1698 ? { $primary_cust_svc->hash,
1699 label => [ $primary_cust_svc->label ],
1700 finger => $primary_cust_svc->svc_x->finger, #uuh
1701 $primary_cust_svc->part_svc->hash,
1705 } $cust_main->ncancelled_pkgs
1708 small_custview( $cust_main, $conf->config('countrydefault') ),
1709 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1717 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1718 return { 'error' => $session } if $context eq 'error';
1720 my $conf = new FS::Conf;
1722 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1723 my $search = { 'custnum' => $custnum };
1724 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1725 my $cust_main = qsearchs('cust_main', $search )
1726 or return { 'error' => "unknown custnum $custnum" };
1728 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1729 if ( ! $pkgnum && $p->{'svcnum'} ) {
1730 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1731 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1735 my @cust_pkg_usage = ();
1736 foreach my $cust_pkg ( $p->{'ncancelled'}
1737 ? $cust_main->ncancelled_pkgs
1738 : $cust_main->unsuspended_pkgs ) {
1739 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1740 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1741 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1744 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1747 foreach (@cust_pkg_usage) {
1748 my $part = $_->part_pkg_usage;
1749 my $tag = $part->description . ($part->shared ? 1 : 0);
1750 my $row = $usage_pools{$tag}
1751 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1752 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1753 $row->[2] += $part->minutes; # minutes total
1755 } # otherwise just leave them empty
1757 if ( $p->{'svcdb'} ) {
1758 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1760 : ref($p->{'svcdb'}) eq 'ARRAY'
1761 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1762 : { $p->{'svcdb'} => 1 };
1763 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1766 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1769 my @svcs; # stuff to return to the client
1770 foreach my $cust_svc (@cust_svc) {
1771 my $svc_x = $cust_svc->svc_x;
1772 my($label, $value) = $cust_svc->label;
1773 my $part_svc = $cust_svc->part_svc;
1774 my $svcdb = $part_svc->svcdb;
1775 my $cust_pkg = $cust_svc->cust_pkg;
1776 my $part_pkg = $cust_pkg->part_pkg;
1779 'svcnum' => $cust_svc->svcnum,
1780 'display_svcnum' => $cust_svc->display_svcnum,
1784 'pkg_label' => $cust_pkg->pkg_locale,
1785 'pkg_status' => $cust_pkg->status,
1786 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1789 # would it make sense to put this in a svc_* method?
1791 if ( $svcdb eq 'svc_acct' ) {
1792 foreach (qw(username email finger seconds)) {
1793 $hash{$_} = $svc_x->$_;
1799 'upbytes' => display_bytecount($svc_x->upbytes),
1800 'downbytes' => display_bytecount($svc_x->downbytes),
1801 'totalbytes' => display_bytecount($svc_x->totalbytes),
1803 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1804 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1805 'recharge_upbytes' =>
1806 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1807 'recharge_downbytes' =>
1808 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1809 'recharge_totalbytes' =>
1810 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1815 } elsif ( $svcdb eq 'svc_dsl' ) {
1817 $hash{'phonenum'} = $svc_x->phonenum;
1818 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1819 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1820 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1823 $hash{'name'} = $cust_main->name;
1825 # no usage to hide here
1827 } elsif ( $svcdb eq 'svc_phone' ) {
1829 # could potentially show lots of things...
1830 $hash{'outbound'} = 1;
1831 $hash{'inbound'} = 0;
1832 if ( $part_pkg->plan eq 'voip_inbound' ) {
1833 $hash{'outbound'} = 0;
1834 $hash{'inbound'} = 1;
1835 } elsif ( $part_pkg->option('selfservice_inbound_format')
1836 or $conf->config('selfservice-default_inbound_cdr_format')
1838 $hash{'inbound'} = 1;
1840 foreach (qw(inbound outbound)) {
1841 # hmm...we can't filter by status here, because there might
1842 # not be cdr_terminations at all. have to go by date.
1843 # find all since the last bill date.
1844 # XXX cdr types? we are going to need them.
1846 my $sum_cdr = $svc_x->sum_cdrs(
1847 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1848 'begin' => ($cust_pkg->last_bill || 0),
1850 'disable_charged_party' => 1,
1852 $hash{$_} = $sum_cdr->hashref;
1855 } # not hiding usage
1859 } # foreach $cust_svc
1862 'svcnum' => $session->{'svcnum'},
1863 'custnum' => $custnum,
1864 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1865 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1868 map { $usage_pools{$_} }
1872 'hide_usage' => $hide_usage,
1877 sub _customer_svc_x {
1878 my($custnum, $svcnum, $table) = (shift, shift, shift);
1879 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1881 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1882 my $search = " AND custnum = $1";
1883 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1886 'table' => ($table || 'svc_acct'),
1887 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1888 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1889 #'LEFT JOIN cust_main USING ( custnum ) ',
1890 'hashref' => $hashref,
1891 'extra_sql' => $search, #important
1896 sub svc_status_html {
1899 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1900 return { 'error' => $session } if $context eq 'error';
1902 #XXX only svc_dsl for now
1903 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1904 or return { 'error' => "Service not found" };
1906 my $html = $svc_x->getstatus_html;
1908 return { 'html' => $html };
1912 sub svc_status_hash {
1915 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1916 return { 'error' => $session } if $context eq 'error';
1918 #XXX only svc_acct for now
1919 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1920 or return { 'error' => "Service not found" };
1922 my ( $html, $hashref ) = $svc_x->export_getstatus;
1927 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1928 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1929 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1930 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1931 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1934 my( $p, $method ) = @_;
1936 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1937 return { 'error' => $session } if $context eq 'error';
1939 #XXX only svc_acct for now
1940 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1941 or return { 'error' => "Service not found" };
1943 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1945 my $error = $svc_x->$method($p); #$p? returns error?
1946 return { 'error' => $error } if $error;
1948 return {}; #? { 'error' => '' }
1952 sub acct_forward_info {
1955 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1956 return { 'error' => $session } if $context eq 'error';
1958 my $svc_forward = _customer_svc_x( $custnum,
1959 { 'srcsvc' => $p->{'svcnum'} },
1962 or return { 'error' => '',
1966 return { 'error' => '',
1967 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1972 sub process_acct_forward {
1974 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1975 return { 'error' => $session } if $context eq 'error';
1977 my $old = _customer_svc_x( $custnum,
1978 { 'srcsvc' => $p->{'svcnum'} },
1982 if ( $p->{'dst'} eq '' ) {
1984 my $error = $old->delete;
1985 return { 'error' => $error };
1987 return { 'error' => '' };
1990 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1991 'dst' => $p->{'dst'},
1996 $new->svcnum($old->svcnum);
1997 my $cust_svc = $old->cust_svc;
1998 $new->svcpart($old->svcpart);
1999 $new->pkgnuym($old->pkgnum);
2000 $error = $new->replace($old);
2002 my $conf = new FS::Conf;
2003 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2005 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2006 or return { 'error' => 'No service' }; #how would we even get here?
2008 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2010 $error = $new->insert;
2013 return { 'error' => $error };
2017 sub list_dsl_devices {
2020 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2021 return { 'error' => $session } if $context eq 'error';
2023 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2024 or return { 'error' => "Service not found" };
2027 'devices' => [ map {
2028 +{ 'mac_addr' => $_->mac_addr };
2029 } $svc_dsl->dsl_device
2035 sub add_dsl_device {
2038 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2039 return { 'error' => $session } if $context eq 'error';
2041 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2042 or return { 'error' => "Service not found" };
2044 return { 'error' => 'No MAC address supplied' }
2045 unless length($p->{'mac_addr'});
2047 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2048 'mac_addr' => scalar($p->{'mac_addr'}),
2050 my $error = $dsl_device->insert;
2051 return { 'error' => $error };
2055 sub delete_dsl_device {
2058 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2059 return { 'error' => $session } if $context eq 'error';
2061 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2062 or return { 'error' => "Service not found" };
2064 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2065 'mac_addr' => scalar($p->{'mac_addr'}),
2068 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2070 my $error = $dsl_device->delete;
2071 return { 'error' => $error };
2077 _usage_details( \&_port_graph, $p,
2078 'svcdb' => 'svc_port',
2083 my($svc_port, $begin, $end) = @_;
2085 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2086 push @usage, { 'png' => $pngOrError };
2090 sub _list_svc_usage {
2091 my($svc_acct, $begin, $end) = @_;
2093 foreach my $part_export (
2094 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2095 qw( sqlradius sqlradius_withdomain )
2097 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2102 sub list_svc_usage {
2103 _usage_details(\&_list_svc_usage, @_);
2106 sub _list_support_usage {
2107 my($svc_acct, $begin, $end) = @_;
2109 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2110 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2112 push @usage, { 'seconds' => $_->seconds,
2113 'support' => $_->support,
2114 '_date' => $_->_date,
2115 'id' => $_->transaction_id,
2116 'creator' => $_->creator,
2117 'subject' => $_->subject,
2118 'status' => $_->status,
2119 'ticketid' => $_->ticketid,
2125 sub list_support_usage {
2126 _usage_details(\&_list_support_usage, @_);
2129 sub _list_cdr_usage {
2130 # XXX CDR type support...
2131 # XXX any way to do a paged search on this?
2132 # we have to return the results all at once...
2133 my($svc_phone, $begin, $end, %opt) = @_;
2134 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2135 $svc_phone->get_cdrs(
2138 'disable_charged_party' => 1,
2143 sub list_cdr_usage {
2145 _usage_details( \&_list_cdr_usage, $p,
2146 'svcdb' => 'svc_phone',
2150 sub _usage_details {
2151 my($callback, $p, %opt) = @_;
2152 my $conf = FS::Conf->new;
2154 if ( $conf->exists('selfservice_hide-usage') ) {
2155 return { 'error' => 'Viewing usage is not allowed.' };
2158 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2159 return { 'error' => $session } if $context eq 'error';
2161 my $search = { 'svcnum' => $p->{'svcnum'} };
2162 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2164 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2166 my $svc_x = qsearchs( $svcdb, $search );
2167 return { 'error' => 'No service selected in list_svc_usage' }
2170 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2171 my $freq = $cust_pkg->part_pkg->freq;
2174 if ( $svcdb eq 'svc_phone' ) {
2176 if ( $p->{inbound} ) {
2177 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2178 || $conf->config('selfservice-default_inbound_cdr_format')
2179 || 'source_default';
2180 $callback_opt{inbound} = 1;
2182 $format = $cust_pkg->part_pkg->option('selfservice_format')
2183 || $conf->config('selfservice-default_cdr_format')
2187 $callback_opt{format} = $format;
2188 $callback_opt{use_clid} = 1;
2189 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2192 my $start = $cust_pkg->setup;
2193 #my $end = $cust_pkg->bill; # or time?
2196 unless ( $p->{beginning} ) {
2197 $p->{beginning} = $cust_pkg->last_bill;
2198 $p->{ending} = $end;
2201 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2202 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2204 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2208 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2209 # ugly kludge, I know
2210 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2211 if (defined $delete_col) {
2212 delete($_->[$delete_col]) foreach ($header, @usage);
2216 #kinda false laziness with FS::cust_main::bill, but perhaps
2217 #we should really change this bit to DateTime and DateTime::Duration
2219 #change this bit to use Date::Manip? CAREFUL with timezones (see
2220 # mailing list archive)
2221 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2222 (localtime($p->{ending}) )[0,1,2,3,4,5];
2223 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2224 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2226 if ( $freq =~ /^\d+$/ ) {
2228 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2230 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2231 } elsif ( $freq =~ /^(\d+)w$/ ) {
2233 $nmday += $weeks * 7;
2234 $pmday -= $weeks * 7;
2235 } elsif ( $freq =~ /^(\d+)d$/ ) {
2239 } elsif ( $freq =~ /^(\d+)h$/ ) {
2244 return { 'error' => "unparsable frequency: ". $freq };
2247 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2248 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2252 'svcnum' => $p->{svcnum},
2253 'beginning' => $p->{beginning},
2254 'ending' => $p->{ending},
2255 'inbound' => $p->{inbound},
2256 'previous' => ($previous > $start) ? $previous : $start,
2257 'next' => ($next < $end) ? $next : $end,
2258 'header' => $header,
2266 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2267 return { 'error' => $session } if $context eq 'error';
2269 my $search = { 'custnum' => $custnum };
2270 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2271 my $cust_main = qsearchs('cust_main', $search )
2272 or return { 'error' => "unknown custnum $custnum" };
2274 my $status = $cust_main->status;
2275 #false laziness w/ClientAPI/Signup.pm
2277 my $cust_pkg = new FS::cust_pkg ( {
2278 'custnum' => $custnum,
2279 'pkgpart' => $p->{'pkgpart'},
2281 my $error = $cust_pkg->check;
2282 return { 'error' => $error } if $error;
2285 unless ( $p->{'svcpart'} eq 'none' ) {
2289 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2291 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2292 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2293 $svcdb = $part_svc->svcdb;
2295 $svcdb = 'svc_acct';
2297 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2300 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2301 'svc_domain' => [ qw( domain ) ],
2302 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2303 'svc_external' => [ qw( id title ) ],
2304 'svc_pbx' => [ qw( id title ) ],
2307 my $svc_x = "FS::$svcdb"->new( {
2308 'svcpart' => $svcpart,
2309 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2312 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2315 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2316 my $acct_snarf = new FS::acct_snarf ( {
2317 'machine' => $p->{"snarf_machine$snarfnum"},
2318 'protocol' => $p->{"snarf_protocol$snarfnum"},
2319 'username' => $p->{"snarf_username$snarfnum"},
2320 '_password' => $p->{"snarf_password$snarfnum"},
2323 push @acct_snarf, $acct_snarf;
2325 $svc_x->child_objects( \@acct_snarf );
2328 my $y = $svc_x->setdefault; # arguably should be in new method
2329 return { 'error' => $y } if $y && !ref($y);
2331 $error = $svc_x->check;
2332 return { 'error' => $error } if $error;
2339 tie my %hash, 'Tie::RefHash';
2340 %hash = ( $cust_pkg => \@svc );
2342 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2343 return { 'error' => $error } if $error;
2345 my $conf = new FS::Conf;
2346 if ( $conf->exists('signup_server-realtime') ) {
2348 my $bill_error = _do_bop_realtime( $cust_main, $status );
2351 $cust_pkg->cancel('quiet'=>1);
2354 $cust_pkg->reexport;
2358 $cust_pkg->reexport;
2361 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2363 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2370 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2371 return { 'error' => $session } if $context eq 'error';
2373 my $conf = new FS::Conf;
2374 my $immutable = $conf->exists('selfservice_immutable-package');
2375 return { 'error' => "Package modification disabled" } if $immutable;
2377 my $search = { 'custnum' => $custnum };
2378 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2379 my $cust_main = qsearchs('cust_main', $search )
2380 or return { 'error' => "unknown custnum $custnum" };
2382 my $status = $cust_main->status;
2383 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2384 or return { 'error' => "unknown package $p->{pkgnum}" };
2386 #if someone does need self-service package change of suspended packages,
2387 # figure out how to be more discriminating
2388 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2389 if $cust_pkg->status eq 'suspended';
2392 my $error = FS::cust_pkg::order( $custnum,
2398 if ( $conf->exists('signup_server-realtime') ) {
2400 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2403 $newpkg[0]->suspend;
2406 $newpkg[0]->reexport;
2410 $newpkg[0]->reexport;
2413 return { error => '', pkgnum => $cust_pkg->pkgnum };
2417 sub order_recharge {
2420 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2421 return { 'error' => $session } if $context eq 'error';
2423 my $search = { 'custnum' => $custnum };
2424 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2425 my $cust_main = qsearchs('cust_main', $search )
2426 or return { 'error' => "unknown custnum $custnum" };
2428 my $status = $cust_main->status;
2429 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2430 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2432 my $svc_x = $cust_svc->svc_x;
2433 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2436 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2437 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2438 recharge_totalbytes );
2439 my $amount = $part_pkg->option('recharge_amount', 1);
2441 my ($l, $v, $d) = $cust_svc->label; # blah
2442 my $pkg = "Recharge $v";
2444 my $bill_error = $cust_main->charge($amount, $pkg,
2445 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2446 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2447 $part_pkg->taxclass); #meh
2449 my $conf = new FS::Conf;
2450 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2452 $bill_error = _do_bop_realtime( $cust_main, $status );
2457 my $error = $svc_x->recharge (\%vhash);
2458 return { 'error' => $error } if $error;
2462 my $error = $bill_error;
2463 $error ||= $svc_x->recharge (\%vhash);
2464 return { 'error' => $error } if $error;
2467 return { error => '', svc => $cust_svc->part_svc->svc };
2471 sub _do_bop_realtime {
2472 my ($cust_main, $status, %opt) = @_;
2474 my $old_balance = $cust_main->balance;
2476 my $bill_error = $cust_main->bill
2477 || $cust_main->apply_payments_and_credits;
2479 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2480 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2482 if ( $cust_main->balance > $old_balance
2483 && $cust_main->balance > 0
2484 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2485 || $status eq 'suspended'
2489 unless ( $opt{'no_credit'} ) {
2490 #this makes sense. credit is "un-doing" the invoice
2491 my $conf = new FS::Conf;
2492 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2493 'self-service decline',
2494 reason_type=>$conf->config('signup_credit_type'),
2496 $cust_main->apply_credits( 'order' => 'newest' );
2499 return { 'error' => '_decline', 'bill_error' => $bill_error };
2508 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2509 return { 'error' => $session } if $context eq 'error';
2511 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2512 or return { 'error' => "unknown custnum $custnum" };
2514 my @cust_pkg = sort { $a->bill <=> $b->bill }
2515 grep { $_->part_pkg->freq ne '0' }
2516 $cust_main->ncancelled_pkgs;
2518 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2520 my $total = $cust_main->balance;
2523 my $bill = $_->bill;
2524 $total += $_->part_pkg->base_recur($_, \$bill);
2525 my $renew_date = $_->part_pkg->add_freq($_->bill);
2527 'pkgnum' => $_->pkgnum,
2528 'amount' => sprintf('%.2f', $total),
2529 'bill_date' => $_->bill,
2530 'bill_date_pretty' => time2str('%x', $_->bill),
2531 'renew_date' => $renew_date,
2532 'renew_date_pretty' => time2str('%x', $renew_date),
2533 'expire_date' => $_->expire,
2534 'expire_date_pretty' => time2str('%x', $_->expire),
2539 return { 'dates' => \@array };
2543 sub payment_info_renew_info {
2545 my $renew_info = renew_info($p);
2546 my $payment_info = payment_info($p);
2547 return { %$renew_info,
2555 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2556 return { 'error' => $session } if $context eq 'error';
2558 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2559 or return { 'error' => "unknown custnum $custnum" };
2561 my $date = $p->{'date'};
2565 #freeside-daily -n -d $date fs_daily $custnum
2566 $cust_main->bill_and_collect( 'time' => $date,
2567 'invoice_time' => $now,
2568 'actual_time' => $now,
2569 'check_freq' => '1d',
2572 return { 'error' => '' };
2578 my $session = _cache->get($p->{'session_id'})
2579 or return { 'error' => "Can't resume session" }; #better error message
2581 my $custnum = $session->{'custnum'};
2583 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2584 or return { 'error' => "unknown custnum $custnum" };
2586 my $conf = new FS::Conf;
2588 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2589 or return { 'error' => 'Permission denied' };
2591 my $pkgnum = $p->{'pkgnum'};
2593 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2594 'pkgnum' => $pkgnum, } )
2595 or return { 'error' => "unknown pkgnum $pkgnum" };
2597 my $error = $cust_pkg->suspend(reason => $reasonnum);
2598 return { 'error' => $error };
2604 my $session = _cache->get($p->{'session_id'})
2605 or return { 'error' => "Can't resume session" }; #better error message
2607 my $custnum = $session->{'custnum'};
2609 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2610 or return { 'error' => "unknown custnum $custnum" };
2612 my $pkgnum = $p->{'pkgnum'};
2614 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2615 'pkgnum' => $pkgnum, } )
2616 or return { 'error' => "unknown pkgnum $pkgnum" };
2618 my $error = $cust_pkg->cancel('quiet' => 1);
2619 return { 'error' => $error };
2623 sub provision_phone {
2626 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2628 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2629 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2630 return { 'error' => $session } if $context eq 'error';
2632 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2633 return { 'error' => 'service not found' } unless $svc_phone;
2634 return { 'error' => 'invalid svcnum' }
2635 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2637 $svc_phone->email($p->{'email'})
2638 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2639 $svc_phone->forwarddst($p->{'forwarddst'})
2640 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2641 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2642 return { 'error' => $svc_phone->replace };
2646 unless($p->{'lnp'}) {
2647 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2648 $p->{'lnp_status'} = "portingin";
2649 return _provision( 'FS::svc_phone',
2650 [qw(lnp_desired_due_date lnp_other_provider
2651 lnp_other_provider_account phonenum countrycode lnp_status)],
2652 [qw(phonenum countrycode)],
2659 unless (scalar(@bulkdid)) {
2660 return _provision( 'FS::svc_phone',
2661 [qw(phonenum countrycode)],
2662 [qw(phonenum countrycode)],
2668 # bulk DID order case
2670 foreach my $did ( @bulkdid ) {
2671 $did =~ s/[^0-9]//g;
2672 $error = _provision( 'FS::svc_phone',
2673 [qw(phonenum countrycode)],
2674 [qw(phonenum countrycode)],
2676 'pkgnum' => $p->{'pkgnum'},
2677 'svcpart' => $p->{'svcpart'},
2679 'countrycode' => $p->{'countrycode'},
2680 'session_id' => $p->{'session_id'},
2683 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2685 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2688 sub provision_acct {
2690 warn "provision_acct called\n"
2693 return { 'error' => gettext('passwords_dont_match') }
2694 if $p->{'_password'} ne $p->{'_password2'};
2695 return { 'error' => gettext('empty_password') }
2696 unless length($p->{'_password'});
2698 if ($p->{'domsvc'}) {
2699 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2700 qw ( svcpart pkgnum ) );
2701 return { 'error' => gettext('invalid_domain') }
2702 unless ($domains{$p->{'domsvc'}});
2705 warn "provision_acct calling _provision\n"
2707 _provision( 'FS::svc_acct',
2708 [qw(username _password domsvc)],
2709 [qw(username _password domsvc)],
2715 sub provision_external {
2717 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2718 _provision( 'FS::svc_external',
2727 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2728 warn "_provision called for $class\n"
2731 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2732 return { 'error' => $session } if $context eq 'error';
2734 my $search = { 'custnum' => $custnum };
2735 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2736 my $cust_main = qsearchs('cust_main', $search )
2737 or return { 'error' => "unknown custnum $custnum" };
2739 my $pkgnum = $p->{'pkgnum'};
2741 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2743 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2744 'pkgnum' => $pkgnum,
2746 or return { 'error' => "unknown pkgnum $pkgnum" };
2748 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2750 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2751 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2753 warn "creating $class record\n"
2755 my $svc_x = $class->new( {
2756 'pkgnum' => $p->{'pkgnum'},
2757 'svcpart' => $p->{'svcpart'},
2758 map { $_ => $p->{$_} } @$fields
2760 warn "inserting $class record\n"
2762 my $error = $svc_x->insert;
2765 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2767 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2770 my $return = { 'svc' => $part_svc->svc,
2772 map { $_ => $svc_x->get($_) } @$return_fields
2774 warn "_provision returning ". Dumper($return). "\n"
2783 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2784 return { 'error' => $session } if $context eq 'error';
2786 my $search = { 'custnum' => $custnum };
2787 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2788 my $cust_main = qsearchs('cust_main', $search )
2789 or return { 'error' => "unknown custnum $custnum" };
2791 my $pkgnum = $p->{'pkgnum'};
2793 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2794 'pkgnum' => $pkgnum,
2796 or return { 'error' => "unknown pkgnum $pkgnum" };
2798 my $svcpart = $p->{'svcpart'};
2800 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2801 'svcpart' => $svcpart, } )
2802 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2803 my $part_svc = $pkg_svc->part_svc;
2805 my $conf = new FS::Conf;
2808 'svc' => $part_svc->svc,
2809 'svcdb' => $part_svc->svcdb,
2810 'pkgnum' => $pkgnum,
2811 'svcpart' => $svcpart,
2812 'custnum' => $custnum,
2814 'security_phrase' => 0, #XXX !
2815 'svc_acct_pop' => [], #XXX !
2817 'init_popstate' => '',
2822 small_custview( $cust_main, $conf->config('countrydefault') ),
2826 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2827 && $ret->{'svcdb'} eq 'svc_phone') {
2828 $ret->{'svcnum'} = $p->{'svcnum'};
2829 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2830 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2831 $ret->{'email'} = $svc_phone->email;
2832 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2839 sub unprovision_svc {
2842 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2843 return { 'error' => $session } if $context eq 'error';
2845 my $search = { 'custnum' => $custnum };
2846 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2847 my $cust_main = qsearchs('cust_main', $search )
2848 or return { 'error' => "unknown custnum $custnum" };
2850 my $svcnum = $p->{'svcnum'};
2852 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2853 or return { 'error' => "unknown svcnum $svcnum" };
2855 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2856 unless $cust_svc->cust_pkg->custnum == $custnum;
2858 my $conf = new FS::Conf;
2860 return { 'svc' => $cust_svc->part_svc->svc,
2861 'error' => $cust_svc->cancel,
2863 small_custview( $cust_main, $conf->config('countrydefault') ),
2868 sub myaccount_passwd {
2870 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2871 return { 'error' => $session } if $context eq 'error';
2873 return { 'error' => "New passwords don't match." }
2874 if $p->{'new_password'} ne $p->{'new_password2'};
2876 return { 'error' => 'Enter new password' }
2877 unless length($p->{'new_password'});
2879 #my $search = { 'custnum' => $custnum };
2880 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2881 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2882 my $search = " AND custnum = $1";
2883 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2885 my $svc_acct = qsearchs( {
2886 'table' => 'svc_acct',
2887 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2888 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2889 'LEFT JOIN cust_main USING ( custnum ) ',
2890 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2891 'extra_sql' => $search, #important
2893 or return { 'error' => "Service not found" };
2897 my $conf = new FS::Conf;
2899 return { 'error' => 'Incorrect current password.' }
2900 if ( exists($p->{'old_password'})
2901 || $conf->exists('selfservice-password_change_oldpass')
2903 && ! $svc_acct->check_password($p->{'old_password'});
2905 $error = 'Password too short.'
2906 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2907 $error = 'Password too long.'
2908 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2910 $svc_acct->set_password($p->{'new_password'});
2911 $error ||= $svc_acct->replace();
2913 #regular pw change in self-service should change contact pw too, otherwise its
2914 #way too confusing. hell its confusing they're separate at all, but alas.
2915 #need to support the "ISP provides email that's used as a contact email" case
2917 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2918 if ( $contact && $contact->custnum == $custnum ) {
2919 #svc_acct was successful but this one returns an error? "shouldn't happen"
2920 $error ||= $contact->change_password($p->{'new_password'});
2923 my($label, $value) = $svc_acct->cust_svc->label;
2925 return { 'error' => $error,
2932 # sub contact_passwd {
2934 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2935 # return { 'error' => $session } if $context eq 'error';
2937 # return { 'error' => 'Not logged in as a contact.' }
2938 # unless $session->{'contactnum'};
2940 # return { 'error' => "New passwords don't match." }
2941 # if $p->{'new_password'} ne $p->{'new_password2'};
2943 # return { 'error' => 'Enter new password' }
2944 # unless length($p->{'new_password'});
2946 # #my $search = { 'custnum' => $custnum };
2947 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2948 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2949 # my $search = " AND selfservice_access IS NOT NULL ".
2950 # " AND selfservice_access = 'Y' ".
2951 # " AND ( disabled IS NULL OR disabled = '' )".
2952 # " AND custnum IS NOT NULL AND custnum = $1";
2953 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2955 # my $contact = qsearchs( {
2956 # 'table' => 'contact',
2957 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2958 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2959 # 'extra_sql' => $search, #important
2961 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2962 # # deleted since then?
2966 # # use these svc_acct length restrictions??
2967 # my $conf = new FS::Conf;
2968 # $error = 'Password too short.'
2969 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2970 # $error = 'Password too long.'
2971 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2973 # $error ||= $contact->change_password($p->{'new_password'});
2975 # return { 'error' => $error, };
2982 my $info = skin_info($p);
2984 my $conf = new FS::Conf;
2985 my $verification = $conf->config('selfservice-password_reset_verification')
2986 or return { %$info, 'error' => 'Password resets disabled' };
2991 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2993 $contact = FS::contact->by_selfservice_email($p->{'email'});
2995 $cust_main = $contact->cust_main if $contact;
2997 #also look for an svc_acct, otherwise it would be super confusing
2999 my($username, $domain) = split('@', $p->{'email'});
3000 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3001 if ( $svc_domain ) {
3002 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3003 'domsvc' => $svc_domain->svcnum }
3006 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3007 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3009 #precaution: don't change svc_acct password not part of the same
3010 # customer as contact
3011 $svc_acct = '' if ! $cust_pkg
3012 || $cust_pkg->custnum != $cust_main->custnum;
3017 return { %$info, 'error' => 'Email address not found' }
3018 unless $contact || $svc_acct;
3020 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3022 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3023 or return { %$info, 'error' => 'Account not found' };
3025 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3026 'domsvc' => $svc_domain->svcnum }
3028 or return { %$info, 'error' => 'Account not found' };
3030 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3031 or return { %$info, 'error' => 'Account not found' };
3033 $cust_main = $cust_pkg->cust_main;
3038 'email' => sub { 1; },
3040 my( $p, $cust_main ) = @_;
3041 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3042 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3045 my( $p, $cust_main ) = @_;
3046 my $cust_pay = qsearchs({
3047 'table' => 'cust_pay',
3048 'hashref' => { 'custnum' => $cust_main->custnum },
3049 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3053 $p->{'amount'} == $cust_pay->paid;
3056 my( $p, $cust_main ) = @_;
3057 $p->{'zip'} eq $cust_main->zip
3058 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3062 foreach my $verify ( split(',', $verification) ) {
3064 &{ $verify{$verify} }( $p, $cust_main )
3065 or return { %$info, 'error' => 'Account not found' };
3069 #okay, we're verified
3073 my $error = $contact->send_reset_email(
3074 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3078 return { %$info, 'error' => $error }; #????
3081 } elsif ( $svc_acct ) {
3083 #create a unique session
3085 my $reset_session = {
3086 'svcnum' => $svc_acct->svcnum,
3090 my $timeout = '1 hour'; #?
3092 my $reset_session_id;
3094 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3095 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3098 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3102 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3103 $cust_main->agentnum);
3104 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3105 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3107 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3108 my $error = $msg_template->send( 'cust_main' => $cust_main,
3109 'object' => $svc_acct,
3110 'substitutions' => {
3111 'session_id' => $reset_session_id,
3115 return { %$info, 'error' => $error }; #????
3120 return { %$info, 'error' => '' };
3123 sub check_reset_passwd {
3126 my $conf = new FS::Conf;
3127 my $verification = $conf->config('selfservice-password_reset_verification')
3128 or return { 'error' => 'Password resets disabled' };
3130 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3131 or return { 'error' => "Can't resume session" }; #better error message
3133 if ( $reset_session->{'svcnum'} ) {
3135 my $svcnum = $reset_session->{'svcnum'};
3137 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3138 or return { 'error' => "Service not found" };
3140 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3141 my $info = skin_info($p);
3145 'session_id' => $p->{'session_id'},
3146 'username' => $svc_acct->username,
3149 } elsif ( $reset_session->{'contactnum'} ) {
3151 my $contactnum = $reset_session->{'contactnum'};
3153 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3154 or return { 'error' => "Contact not found" };
3156 my @contact_email = $contact->contact_email;
3157 return { 'error' => 'No contact email' } unless @contact_email;
3159 $p->{'agentnum'} = $contact->cust_main->agentnum;
3160 my $info = skin_info($p);
3164 'session_id' => $p->{'session_id'},
3165 'email' => $contact_email[0]->email, #the first?
3170 return { 'error' => 'No svcnum or contactnum in session' }; #??
3176 sub process_reset_passwd {
3179 my $conf = new FS::Conf;
3180 my $verification = $conf->config('selfservice-password_reset_verification')
3181 or return { 'error' => 'Password resets disabled' };
3183 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3184 or return { 'error' => "Can't resume session" }; #better error message
3189 if ( $reset_session->{'svcnum'} ) {
3191 my $svcnum = $reset_session->{'svcnum'};
3193 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3194 or return { 'error' => "Service not found" };
3196 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3197 $info ||= skin_info($p);
3202 if ( $reset_session->{'contactnum'} ) {
3204 my $contactnum = $reset_session->{'contactnum'};
3206 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3207 or return { 'error' => "Contact not found" };
3209 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3210 $info ||= skin_info($p);
3214 return { %$info, 'error' => "New passwords don't match." }
3215 if $p->{'new_password'} ne $p->{'new_password2'};
3217 return { %$info, 'error' => 'Enter new password' }
3218 unless length($p->{'new_password'});
3222 $svc_acct->set_password($p->{'new_password'});
3223 my $error = $svc_acct->replace();
3225 return { %$info, 'error' => $error } if $error;
3227 #my($label, $value) = $svc_acct->cust_svc->label;
3228 #return { 'error' => $error,
3229 # #'label' => $label,
3230 # #'value' => $value,
3237 my $error = $contact->change_password($p->{'new_password'});
3239 return { %$info, 'error' => $error }; # if $error;
3243 #password changed ,so remove session, don't want it reused
3244 _cache->remove($p->{'session_id'});
3246 return { %$info, 'error' => '' };
3252 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3253 return { 'error' => $session } if $context eq 'error';
3256 if ( $session->{'pkgnum'} ) {
3258 #tickets for specific service with pkg-balances on
3259 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3260 'pkgnum' => $session->{'pkgnum'} })
3261 or return { 'error' => 'unknown package' };
3262 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3263 push @tickets, $cust_svc->tickets( $p->{status} );
3268 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3269 or return { 'error' => "unknown custnum $custnum" };
3271 @tickets = $cust_main->tickets( $p->{status} );
3274 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3275 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3276 my $conf = new FS::Conf;
3277 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3281 ($a->{'_selfservice_priority'} eq '') <=>
3282 ($b->{'_selfservice_priority'} eq '')
3285 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3291 +{ tickets => \@tickets };
3298 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3299 return { 'error' => $session } if $context eq 'error';
3301 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3302 FS::TicketSystem->init();
3304 my $conf = new FS::Conf;
3305 my $queue = $p->{'queue'}
3306 || $conf->config('ticket_system-selfservice_queueid')
3307 || $conf->config('ticket_system-default_queueid');
3309 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3310 my $err_or_ticket = FS::TicketSystem->create_ticket(
3311 '', #create RT session based on FS CurrentUser (fs_selfservice)
3313 'custnum' => $custnum,
3314 'svcnum' => $session->{'svcnum'},
3315 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3318 if ( ref($err_or_ticket) ) {
3319 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3321 return { 'error' => '',
3322 'ticket_id' => $err_or_ticket->id,
3325 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3327 return { 'error' => $err_or_ticket };
3335 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3336 return { 'error' => $session } if $context eq 'error';
3338 return { error => 'requested format not implemented' }
3339 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3341 my $conf = new FS::Conf;
3342 my $age_threshold = 0;
3343 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3344 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3346 my $search = { 'custnum' => $custnum };
3347 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3348 my $cust_main = qsearchs('cust_main', $search )
3349 or return { 'error' => "unknown custnum $custnum" };
3351 # does it make more sense to just run one sql query for this instead of all the
3352 # insanity below? would increase performance greately for large data sets?
3354 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3355 my @part_svc = $cust_pkg->part_svc;
3356 foreach my $part_svc ( @part_svc ) {
3357 if($part_svc->svcdb eq 'svc_phone'){
3358 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3359 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3360 push @svc_phone, $cust_pkg_svc->svc_x
3361 if $cust_pkg_svc->date_inserted >= $age_threshold;
3369 my($xls_r,$xls_c) = (0,0);
3372 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3373 if($p->{'format'} eq 'csv') {
3374 $csv = new Text::CSV_XS { 'always_quote' => 1,
3377 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3378 $content .= $csv->string;
3380 elsif($p->{'format'} eq 'xls') {
3381 my $XLS1 = new IO::Scalar \$content;
3382 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3383 or return { 'error' => "Error opening .xls file: $!" };
3384 $xls = $xls_workbook->add_worksheet('DIDs');
3385 foreach ( @fields ) {
3386 $xls->write(0,$xls_c++,$_);
3391 foreach my $svc_phone ( @svc_phone ) {
3392 my @cols = map { $svc_phone->$_ } @fields;
3393 if($p->{'format'} eq 'csv') {
3394 return { 'error' => 'Unable to create CSV' }
3395 unless $csv->combine(@cols);
3396 $content .= $csv->string;
3398 elsif($p->{'format'} eq 'xls') {
3401 $xls->write($xls_r,$xls_c++,$_);
3407 $xls_workbook->close() if $p->{'format'} eq 'xls';
3409 { content => $content, format => $p->{'format'}, };
3414 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3415 return { 'error' => $session } if $context eq 'error';
3417 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3418 # FS::TicketSystem->init();
3419 # return { 'error' => 'get_ticket configuration error' }
3420 # if $FS::TicketSystem::system ne 'RT_Internal';
3422 # check existence and ownership as part of this
3423 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3424 my $rt_session = FS::TicketSystem->session('');
3425 my $Ticket = FS::TicketSystem->get_ticket_object(
3427 ticket_id => $p->{'ticket_id'},
3430 return { 'error' => 'ticket not found' } if !$Ticket;
3432 if ( length( $p->{'subject'} || '' ) ) {
3434 if ( $p->{'subject'} ne $Ticket->Subject ) {
3435 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3436 return { 'error' => "unable to set subject: $msg" } if !$val;
3440 if(length($p->{'reply'})) {
3441 my @err_or_res = FS::TicketSystem->correspond_ticket(
3443 'ticket_id' => $p->{'ticket_id'},
3444 'content' => $p->{'reply'},
3447 return { 'error' => 'unable to reply to ticket' }
3448 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3451 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3452 my $err_or_ticket = FS::TicketSystem->get_ticket(
3454 'ticket_id' => $p->{'ticket_id'},
3457 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3458 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3460 return { 'error' => $err_or_ticket };
3463 my @custs = @{$err_or_ticket->{'custs'}};
3464 my @txns = @{$err_or_ticket->{'txns'}};
3467 # superseded by check in get_ticket_object
3468 #return { 'error' => 'invalid ticket requested' }
3469 #unless grep($_ eq $custnum, @custs);
3471 foreach my $txn ( @txns ) {
3472 push @filtered_txns, $txn
3473 if ($txn->{'type'} eq 'EmailRecord'
3474 || $txn->{'type'} eq 'Correspond'
3475 || $txn->{'type'} eq 'Create');
3478 warn "$me get_ticket: successful: \n"
3480 return { 'error' => '',
3481 'transactions' => \@filtered_txns,
3482 'ticket_fields' => $err_or_ticket->{'fields'},
3483 'ticket_id' => $p->{'ticket_id'},
3487 sub adjust_ticket_priority {
3489 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3490 return { 'error' => $session } if $context eq 'error';
3492 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3493 # FS::TicketSystem->init;
3494 my $ss_priority = FS::TicketSystem->selfservice_priority;
3496 return { 'error' => 'adjust_ticket_priority configuration error' }
3497 if $FS::TicketSystem::system ne 'RT_Internal'
3500 my $values = $p->{'values'}; #hashref, id => priority value
3503 foreach my $id (keys %$values) {
3504 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3505 my $Ticket = FS::TicketSystem->get_ticket_object('',
3507 'custnum' => $custnum,
3510 $ticket_error{$id} = 'ticket not found';
3514 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3515 # We're not going to implement it for RT_External.
3516 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3517 my $new_value = $values->{$id};
3518 next if $old_value eq $new_value;
3520 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3522 # AddCustomFieldValue works fine (replacing any existing value) if it's
3523 # a single-valued custom field, which it should be. If it's not, you're
3524 # doing something wrong.
3526 if ( length($new_value) ) {
3527 ($val, $msg) = $Ticket->AddCustomFieldValue(
3528 Field => $ss_priority,
3529 Value => $new_value,
3533 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3534 Field => $ss_priority,
3535 Value => $old_value,
3539 $ticket_error{$id} = $msg if !$val;
3540 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3542 return { 'error' => '',
3543 'ticket_error' => \%ticket_error,
3544 %{ customer_info($p) } # send updated customer info back
3550 sub _custoragent_session_custnum {
3553 my($context, $session, $custnum);
3554 if ( $p->{'session_id'} ) {
3556 $context = 'customer';
3557 $session = _cache->get($p->{'session_id'})
3558 or return ( 'error' => "Can't resume session" ); #better error message
3559 $custnum = $session->{'custnum'};
3561 } elsif ( $p->{'agent_session_id'} ) {
3564 my $agent_cache = new FS::ClientAPI_SessionCache( {
3565 'namespace' => 'FS::ClientAPI::Agent',
3567 $session = $agent_cache->get($p->{'agent_session_id'})
3568 or return ( 'error' => "Can't resume session" ); #better error message
3569 $custnum = $p->{'custnum'};
3573 return ( 'error' => "Can't resume session" ); #better error message
3576 ($context, $session, $custnum);